diff options
author | TATTAVARADA <statta@research.att.com> | 2017-04-27 07:53:18 -0400 |
---|---|---|
committer | st782s <statta@research.att.com> | 2017-04-27 08:31:27 -0400 |
commit | 6beb446925c967aca92f5513adf36c5db77c00d6 (patch) | |
tree | 9392057ed0739de2445c5b2a2a8bee6dcdacbcf7 /ecomp-sdk/quantum/src/main/java/org | |
parent | 246b225194e3e8dc1926294de591a94fd9787fa7 (diff) |
[PORTAL-7] Rebase
This rebasing includes common libraries and common overlays projects
abstraction of components
Change-Id: Ia1efa4deacdc5701e6205104ac021a6c80ed60ba
Signed-off-by: st782s <statta@research.att.com>
Diffstat (limited to 'ecomp-sdk/quantum/src/main/java/org')
166 files changed, 0 insertions, 22037 deletions
diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/FusionObject.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/FusionObject.java deleted file mode 100644 index 00866388..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/FusionObject.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core; - -/** - * <p> - * Title: FusionObject - * </p> - * - * <p> - * Description: This interface is implemented by all top-level support classes - * of each package in FUSION. This allows all top-level support classes to have - * some commonality for easier maintenance. - * </p> - * - * <p> - * Copyright: Copyright (c) 2007 - * </p> - * - * - * @version 1.1 - */ -public interface FusionObject { - - public class Parameters { - // HashMap parameters passed to the Service and Dao tiers - public static final String PARAM_USERID = "userId"; - public static final String PARAM_HTTP_REQUEST = "request"; - public static final String PARAM_FILTERS = "filters"; - public static final String PARAM_CLIENT_DEVICE = "client_device"; - // Request parameters passed in the Web tier - public static final String REQUEST_PARAM_DISPLAY_SUCCESS_MESSAGE = "display_success_message"; - } - - /** - * <p> - * Title: FusionObject.Utilities - * </p> - * - * <p> - * Description: Inner class that has some utility functions available for - * any class that implements it. - * </p> - * - * <p> - * Copyright: Copyright (c) 2007 - * </p> - * - * - * @version 1.1 - */ - public class Utilities { - /** - * nvl - replaces a string value with an empty string if null. - * - * @param s - * String - the string value that needs to be checked - * @return String - returns the original string value if not null. - * Otherwise an empty string ("") is returned. - */ - public static String nvl(String s) { - return (s == null) ? "" : s; - } - - /** - * nvl - replaces a string value with a default value if null. - * - * @param s - * String - the string value that needs to be checked - * @param sDefault - * String - the default value - * @return String - returns the original string value if not null. - * Otherwise the default value is returned. - */ - public static String nvl(String s, String sDefault) { - return nvl(s).equals("") ? sDefault : s; - } - - /** - * Tests the specified string for nullity. - * - * @param a - * String to test for nullity. - * @return True if the specified string is null, empty or the 4-character - * sequence "null" (ignoring case); otherwise false. - */ - public static boolean isNull(String a) { - if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null")) - return true; - else - return false; - } - - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/LoginBean.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/LoginBean.java deleted file mode 100644 index e5a58e82..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/LoginBean.java +++ /dev/null @@ -1,196 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.command; - -import java.util.Set; - -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.domain.support.FusionCommand; - -public class LoginBean extends FusionCommand { - - private String loginId; - private String loginPwd; - private String hrid; - private String userid; - private String siteAccess; - private String loginErrorMessage; - - private User user; - @SuppressWarnings("rawtypes") - private Set menu; - @SuppressWarnings("rawtypes") - private Set businessDirectMenu; - - /** - * getLoginId - * - * @return String - */ - public String getLoginId() { - return loginId; - } - - /** - * getLoginPwd - * - * @return String - */ - public String getLoginPwd() { - return loginPwd; - } - - /** - * getMenu - * - * @return Set - */ - @SuppressWarnings("rawtypes") - public Set getMenu() { - return menu; - } - - /** - * getUser - * - * @return User - */ - public User getUser() { - return user; - } - - /** - * getHrid - * - * @return String - */ - public String getHrid() { - return hrid; - } - - /** - * getSiteAccess - * - * @return String - */ - public String getSiteAccess() { - return siteAccess; - } - - /** - * getBusinessDirectMenu - * - * @return Set - */ - @SuppressWarnings("rawtypes") - public Set getBusinessDirectMenu() { - return businessDirectMenu; - } - - /** - * getLoginErrorMessage - * - * @return String - */ - public String getLoginErrorMessage() { - return loginErrorMessage; - } - - - - /** - * setLoginId - * - * @param loginId String - */ - public void setLoginId(String loginId) { - this.loginId = loginId; - } - - /** - * setLoginPwd - * - * @param loginPwd String - */ - public void setLoginPwd(String loginPwd) { - this.loginPwd = loginPwd; - } - - @SuppressWarnings("rawtypes") - public void setMenu(Set menu) { - this.menu = menu; - } - - /** - * setUser - * - * @param user User - */ - public void setUser(User user) { - this.user = user; - } - - /** - * setHrid - * - * @param hrid String - */ - public void setHrid(String hrid) { - this.hrid = hrid; - } - - /** - * setSiteAccess - * - * @param siteAccess String - */ - public void setSiteAccess(String siteAccess) { - this.siteAccess = siteAccess; - } - - /** - * setBusinessDirectMenu - * - * @param businessDirectMenu Set - */ - @SuppressWarnings("rawtypes") - public void setBusinessDirectMenu(Set businessDirectMenu) { - this.businessDirectMenu = businessDirectMenu; - } - - /** - * setLoginErrorMessage - * - * @param loginErrorMessage String - */ - public void setLoginErrorMessage(String loginErrorMessage) { - this.loginErrorMessage = loginErrorMessage; - } - - public String getUserid() { - return userid; - } - - public void setUserid(String userid) { - this.userid = userid; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/PostDroolsBean.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/PostDroolsBean.java deleted file mode 100644 index 541d9f71..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/PostDroolsBean.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.command; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonSerialize -public class PostDroolsBean { - - private String droolsFile; - private String className; - private String selectedRules; - - public String getDroolsFile() { - return droolsFile; - } - public void setDroolsFile(String droolsFile) { - this.droolsFile = droolsFile; - } - public String getSelectedRules() { - return selectedRules; - } - public void setSelectedRules(String selectedRules) { - this.selectedRules = selectedRules; - } - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/PostSearchBean.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/PostSearchBean.java deleted file mode 100644 index b07b8fed..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/PostSearchBean.java +++ /dev/null @@ -1,374 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.command; - -import java.util.List; - -import org.openecomp.portalsdk.core.command.support.SearchBase; -import org.openecomp.portalsdk.core.domain.User; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonSerialize -public class PostSearchBean extends SearchBase { - - private User user = null; - private User userOrig = null; - private String[] selected; - private String[] postHrid; - private String[] postOrgUserId; - private String[] postFirstName; - private String[] postLastName; - private String[] postOrgCode; - private String[] postPhone; - private String[] postEmail; - private String[] postAddress1; - private String[] postAddress2; - private String[] postCity; - private String[] postState; - private String[] postZipCode; - private String[] postLocationClli; - private String[] postBusinessCountryCode; - private String[] postBusinessCountryName; - private String[] postDepartment; - private String[] postDepartmentName; - private String[] postBusinessUnit; - private String[] postBusinessUnitName; - private String[] postJobTitle; - private String[] postOrgManagerUserId; - private String[] postCommandChain; - private String[] postCompanyCode; - private String[] postCompany; - private String[] postCostCenter; - private String[] postSiloStatus; - private String[] postFinancialLocCode; - - - public PostSearchBean() { - this(null); - } // PostSearchBean - - @SuppressWarnings("rawtypes") - public PostSearchBean(List items) { - super(items); - - user = new User(); - userOrig = new User(); - - setSortBy1(""); - setSortBy1Orig(""); - - //setSortByList(...); - } // PostSearchBean - - - public String getFirstName() { return user.getFirstName(); } - public String getLastName() { return user.getLastName(); } - public String getHrid() { return user.getHrid(); } - public String getOrgUserId() { return user.getOrgUserId(); } - public String getOrgCode() { return user.getOrgCode(); } - public String getEmail() { return user.getEmail(); } - public String getOrgManagerUserId() { return user.getOrgManagerUserId(); } - - public String getFirstNameOrig() { return user.getFirstName(); } - public String getLastNameOrig() { return user.getLastName(); } - public String getHridOrig() { return user.getHrid(); } - public String getOrgUserIdOrig() { return user.getOrgUserId(); } - public String getOrgCodeOrig() { return user.getOrgCode(); } - public String getEmailOrig() { return user.getEmail(); } - public String getOrgManagerUserIdOrig() { return user.getOrgManagerUserId(); } - - - public User getUser() { return user; } - - public String[] getPostEmail() { - return postEmail; - } - - public String[] getPostFirstName() { - return postFirstName; - } - - public String[] getPostHrid() { - return postHrid; - } - - public String[] getPostLastName() { - return postLastName; - } - - public String[] getPostOrgCode() { - return postOrgCode; - } - - public String[] getPostPhone() { - return postPhone; - } - - public String[] getPostOrgUserId() { - return postOrgUserId; - } - - public String[] getSelected() { - return selected; - } - - public String[] getPostAddress1() { - return postAddress1; - } - - public String[] getPostBusinessCountryCode() { - return postBusinessCountryCode; - } - - public String[] getPostCity() { - return postCity; - } - - public String[] getPostCommandChain() { - return postCommandChain; - } - - public String[] getPostCompany() { - return postCompany; - } - - public String[] getPostCompanyCode() { - return postCompanyCode; - } - - public String[] getPostDepartment() { - return postDepartment; - } - - public String[] getPostDepartmentName() { - return postDepartmentName; - } - - public String[] getPostBusinessCountryName() { - return postBusinessCountryName; - } - - public String[] getPostJobTitle() { - return postJobTitle; - } - - public String[] getPostLocationClli() { - return postLocationClli; - } - - public String[] getPostOrgManagerUserId() { - return postOrgManagerUserId; - } - - public String[] getPostState() { - return postState; - } - - public String[] getPostZipCode() { - return postZipCode; - } - - public void setFirstName(String value) { user.setFirstName(value); } - public void setLastName(String value) { user.setLastName(value); } - public void setHrid(String value) { user.setHrid(value); } - public void setOrgUserId(String value) { user.setOrgUserId(value); } - public void setOrgCode(String value) { user.setOrgCode(value); } - public void setEmail(String value) { user.setEmail(value); } - public void setOrgManagerUserId(String value) { user.setOrgManagerUserId(value); } - - public void setFirstNameOrig(String value) { userOrig.setFirstName(value); } - public void setLastNameOrig(String value) { userOrig.setLastName(value); } - public void setHridOrig(String value) { userOrig.setHrid(value); } - public void setOrgUserIdOrig(String value) { userOrig.setOrgUserId(value); } - public void setOrgCodeOrig(String value) { userOrig.setOrgCode(value); } - public void setEmailOrig(String value) { userOrig.setEmail(value); } - public void setOrgManagerUserIdOrig(String value) { userOrig.setOrgManagerUserId(value); } - - public void setUser(User value) { this.user = value; } - - public void setPostEmail(String[] postEmail) { - this.postEmail = postEmail; - } - - public void setPostFirstName(String[] postFirstName) { - this.postFirstName = postFirstName; - } - - public void setPostHrid(String[] postHrid) { - this.postHrid = postHrid; - } - - public void setPostLastName(String[] postLastName) { - this.postLastName = postLastName; - } - - public void setPostOrgCode(String[] postOrgCode) { - this.postOrgCode = postOrgCode; - } - - public void setPostPhone(String[] postPhone) { - this.postPhone = postPhone; - } - - public void setPostOrgUserId(String[] postOrgUserId) { - this.postOrgUserId = postOrgUserId; - } - - public void setSelected(String[] selected) { - this.selected = selected; - } - - public void setPostAddress1(String[] postAddress1) { - this.postAddress1 = postAddress1; - } - - public void setPostBusinessCountryCode(String[] postBusinessCountryCode) { - this.postBusinessCountryCode = postBusinessCountryCode; - } - - public void setPostCity(String[] postCity) { - this.postCity = postCity; - } - - public void setPostCommandChain(String[] postCommandChain) { - this.postCommandChain = postCommandChain; - } - - public void setPostCompany(String[] postCompany) { - this.postCompany = postCompany; - } - - public void setPostCompanyCode(String[] postCompanyCode) { - this.postCompanyCode = postCompanyCode; - } - - public void setPostDepartment(String[] postDepartment) { - this.postDepartment = postDepartment; - } - - public void setPostDepartmentName(String[] postDepartmentName) { - this.postDepartmentName = postDepartmentName; - } - - public void setPostBusinessCountryName(String[] postBusinessCountryName) { - this.postBusinessCountryName = postBusinessCountryName; - } - - public void setPostJobTitle(String[] postJobTitle) { - this.postJobTitle = postJobTitle; - } - - public void setPostLocationClli(String[] postLocationClli) { - this.postLocationClli = postLocationClli; - } - - public void setPostOrgManagerUserId(String[] postOrgManagerUserId) { - this.postOrgManagerUserId = postOrgManagerUserId; - } - - public void setPostState(String[] postState) { - this.postState = postState; - } - - public void setPostZipCode(String[] postZipCode) { - this.postZipCode = postZipCode; - } - - public String[] getPostAddress2() { - return postAddress2; - } - - public void setPostAddress2(String[] postAddress2) { - this.postAddress2 = postAddress2; - } - - public User getUserOrig() { - return userOrig; - } - - public void setUserOrig(User userOrig) { - this.userOrig = userOrig; - } - - public String[] getPostBusinessUnit() { - return postBusinessUnit; - } - - public void setPostBusinessUnit(String[] postBusinessUnit) { - this.postBusinessUnit = postBusinessUnit; - } - - public String[] getPostBusinessUnitName() { - return postBusinessUnitName; - } - - public void setPostBusinessUnitName(String[] postBusinessUnitName) { - this.postBusinessUnitName = postBusinessUnitName; - } - - public String[] getPostCostCenter() { - return postCostCenter; - } - - public void setPostCostCenter(String[] postCostCenter) { - this.postCostCenter = postCostCenter; - } - - public String[] getPostSiloStatus() { - return postSiloStatus; - } - - public void setPostSiloStatus(String[] postSiloStatus) { - this.postSiloStatus = postSiloStatus; - } - - public String[] getPostFinancialLocCode() { - return postFinancialLocCode; - } - - public void setPostFinancialLocCode(String[] postFinancialLocCode) { - this.postFinancialLocCode = postFinancialLocCode; - } - - public void resetSearch() { - super.resetSearch(); - setUser(new User()); - } // resetSearch - - - public boolean isCriteriaUpdated() { - if(user==null&&userOrig==null) - return false; - else if(user==null||userOrig==null) - return true; - else - return (! ( - Utilities.nvl(user.getFirstName()).equals(Utilities.nvl(userOrig.getFirstName()))&& - Utilities.nvl(user.getLastName()).equals(Utilities.nvl(userOrig.getLastName()))&& - //Utilities.nvl(user.getHrid()).equals(Utilities.nvl(userOrig.getHrid()))&& - Utilities.nvl(user.getOrgUserId()).equals(Utilities.nvl(userOrig.getOrgUserId()))&& - Utilities.nvl(user.getOrgCode()).equals(Utilities.nvl(userOrig.getOrgCode()))&& - Utilities.nvl(user.getEmail()).equals(Utilities.nvl(userOrig.getEmail()))&& - Utilities.nvl(user.getOrgManagerUserId()).equals(Utilities.nvl(userOrig.getOrgManagerUserId()))&& - true)); - } // isCriteriaUpdated - -} // PostSearchBean diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/UserRowBean.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/UserRowBean.java deleted file mode 100644 index 7230add8..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/UserRowBean.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.command; - -import org.openecomp.portalsdk.core.domain.User; - -public class UserRowBean extends User { - - /** - * - */ - private static final long serialVersionUID = -2724597119083972190L; - private String sessionId; - private String lastAccess; - private String remaining; - private String loginTime; - private String LastLoginTime; - - - public String getLastAccess(){ - return this.lastAccess; - } - - - public void setLastAccess(String lastAccess){ - this.lastAccess = lastAccess; - } - - - public String getRemaining(){ - return this.remaining; - } - - - public void setRemaining(String remaining){ - this.remaining = remaining; - } - - - public String getSessionId() { - return sessionId; - } - - - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } - - - public String getLoginTime() { - return loginTime; - } - - - public void setLoginTime(String loginTime) { - this.loginTime = loginTime; - } - - - public String getLastLoginTime() { - return LastLoginTime; - } - - - public void setLastLoginTime(String lastLoginTime) { - LastLoginTime = lastLoginTime; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/support/SearchBase.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/support/SearchBase.java deleted file mode 100644 index 6fb60aa7..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/support/SearchBase.java +++ /dev/null @@ -1,268 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.command.support; - -import java.util.List; - -import org.openecomp.portalsdk.core.domain.support.FusionCommand; - -public abstract class SearchBase extends FusionCommand { - - public static String SORT_BY_MODIFIER_DESC = "D"; - public static String SORT_BY_MODIFIER_ASC = "A"; - public static String SORT_BY_MODIFIER_DESC_IMAGE_NAME = "sort_desc.gif"; - public static String SORT_BY_MODIFIER_ASC_IMAGE_NAME = "sort_asc.gif"; - - - private String sortBy1 = null; - private String sortBy2 = null; - private String sortBy3 = null; - - private String sortBy1Orig = null; - private String sortBy2Orig = null; - private String sortBy3Orig = null; - - private String sortByModifier1 = null; - private String sortByModifier2 = null; - private String sortByModifier3 = null; - - private String sortByModifier1Orig = null; - private String sortByModifier2Orig = null; - private String sortByModifier3Orig = null; - - private String accessType = "WRITE"; //null; - - private String submitAction = ""; - private String masterId = ""; - private String detailId = ""; - - private String showResult = "Y"; - - private SearchResult searchResult = null; - - @SuppressWarnings("rawtypes") - public SearchBase(List items) { - searchResult = (items == null) ? (new SearchResult()) : (new SearchResult(items)); - } // SearchBase - - - public String getSortBy1() { - return sortBy1; - } - - public String getSortBy2() { - return sortBy2; - } - - public String getSortBy3() { - return sortBy3; - } - - public String getSortBy1Orig() { - return sortBy1; - } - - public String getSortBy2Orig() { - return sortBy2; - } - - public String getSortBy3Orig() { - return sortBy3; - } - - public String getAccessType() { - return accessType; - } - - public String getSubmitAction() { - return submitAction; - } - - public String getMasterId() { - return masterId; - } - - public String getDetailId() { - return detailId; - } - - public String getShowResult() { - return showResult; - } - - //public ArrayList getSortByList() { return sortByList; } - - public SearchResult getSearchResult() { - return searchResult; - } - - public String getSortByModifier1() { - return sortByModifier1; - } - - public String getSortByModifier1Orig() { - return sortByModifier1; - } - - public String getSortByModifier2() { - return sortByModifier2; - } - - public String getSortByModifier2Orig() { - return sortByModifier2; - } - - public String getSortByModifier3() { - return sortByModifier3; - } - - public String getSortByModifier3Orig() { - return sortByModifier3; - } - - public int getPageNo() { - return (isCriteriaUpdated() || isSortingUpdated()) ? 0 : getSearchResult().getPageNo(); - } - - public int getPageSize() { - return getSearchResult().getPageSize(); - } - - public int getDataSize() { - return getSearchResult().getDataSize(); - } - - public int getNewDataSize() { - return isCriteriaUpdated() ? -1 : getDataSize(); - } - - - public void setSortBy1(String sortBy1) { - this.sortBy1 = sortBy1; - } - - public void setSortBy2(String sortBy2) { - this.sortBy2 = sortBy2; - } - - public void setSortBy3(String sortBy3) { - this.sortBy3 = sortBy3; - } - - public void setSortBy1Orig(String sortBy1Orig) { - this.sortBy1Orig = sortBy1Orig; - } - - public void setSortBy2Orig(String sortBy2Orig) { - this.sortBy2Orig = sortBy2Orig; - } - - public void setSortBy3Orig(String sortBy3Orig) { - this.sortBy3Orig = sortBy3Orig; - } - - public void setAccessType(String accessType) { - this.accessType = accessType; - } - - public void setSubmitAction(String submitAction) { - this.submitAction = submitAction; - } - - public void setMasterId(String masterId) { - this.masterId = masterId; - } - - public void setDetailId(String detailId) { - this.detailId = detailId; - } - - public void setShowResult(String showResult) { - this.showResult = showResult; - } - - public void setSearchResult(SearchResult searchResult) { - this.searchResult = searchResult; - } - - public void setSortByModifier1(String sortByModifier1) { - this.sortByModifier1 = sortByModifier1; - } - - public void setSortByModifier1Orig(String sortByModifier1Orig) { - this.sortByModifier1Orig = sortByModifier1Orig; - } - - public void setSortByModifier2(String sortByModifier2) { - this.sortByModifier2 = sortByModifier2; - } - - public void setSortByModifier2Orig(String sortByModifier2Orig) { - this.sortByModifier2Orig = sortByModifier2Orig; - } - - public void setSortByModifier3(String sortByModifier3) { - this.sortByModifier3 = sortByModifier3; - } - - public void setSortByModifier3Orig(String sortByModifier3Orig) { - this.sortByModifier3Orig = sortByModifier3Orig; - } - - public void setSortingUpdated(boolean sortingUpdated) { - } - - public void setPageNo(int pageNo) { - getSearchResult().setPageNo(pageNo); - } - - public void setPageSize(int pageSize) { - getSearchResult().setPageSize(pageSize); - } - - public void setDataSize(int dataSize) { - getSearchResult().setDataSize(dataSize); - } - - - public void resetSearch() { - setSortBy1(null); - setSortBy2(null); - setSortBy3(null); - setSortByModifier1(SearchBase.SORT_BY_MODIFIER_ASC); - setSortByModifier2(SearchBase.SORT_BY_MODIFIER_ASC); - setSortByModifier3(SearchBase.SORT_BY_MODIFIER_ASC); - setPageNo(0); - setDataSize( -1); - } // resetSearch - - - public abstract boolean isCriteriaUpdated(); - - public boolean isSortingUpdated() { - return (!(Utilities.nvl(sortBy1).equals(Utilities.nvl(sortBy1Orig)) && - Utilities.nvl(sortBy2).equals(Utilities.nvl(sortBy2Orig)) && - Utilities.nvl(sortBy3).equals(Utilities.nvl(sortBy3Orig)) && - Utilities.nvl(sortByModifier1).equals(Utilities.nvl(sortByModifier1Orig)) && - Utilities.nvl(sortByModifier2).equals(Utilities.nvl(sortByModifier2Orig)) && - Utilities.nvl(sortByModifier3).equals(Utilities.nvl(sortByModifier3Orig)))); - } // isSortingUpdated - -} // SearchBase diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/support/SearchResult.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/support/SearchResult.java deleted file mode 100644 index 4a2c05f1..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/command/support/SearchResult.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.command.support; - -import java.util.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 pageSize = 50; - private int dataSize = -1; - - private String accessType = null; - - public SearchResult() {} - - @SuppressWarnings("unchecked") - public SearchResult(List items) { - super(items); - } - - public int getPageNo() { return pageNo; } - public int getPageSize() { return pageSize; } - public int getDataSize() { return dataSize; } - - public int getSize() { return size(); } // for Struts bean property access - - public String getAccessType() { return accessType; } - - public void setPageNo(int pageNo) { this.pageNo=pageNo; } - public void setPageSize(int pageSize) { this.dataSize=pageSize; } - public void setDataSize(int dataSize) { this.dataSize=dataSize; } - - public void setAccessType(String accessType) { this.accessType = accessType; } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/AppConfig.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/AppConfig.java deleted file mode 100644 index 3a4753e3..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/AppConfig.java +++ /dev/null @@ -1,301 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.conf; - -import java.util.ArrayList; -import java.util.List; - -import javax.sql.DataSource; - -import org.openecomp.portalsdk.core.interceptor.ResourceInterceptor; -import org.openecomp.portalsdk.core.interceptor.SessionTimeoutInterceptor; -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.format.AppMessagesEnum; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.menu.MenuBuilder; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.openecomp.portalsdk.core.service.DataAccessServiceImpl; -import org.openecomp.portalsdk.core.util.CipherUtil; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.AppUtils; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.annotation.Bean; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; -import org.springframework.web.servlet.view.UrlBasedViewResolver; -import org.springframework.web.servlet.view.tiles3.TilesConfigurer; -import org.springframework.web.servlet.view.tiles3.TilesView; - -import com.mchange.v2.c3p0.ComboPooledDataSource; - -/** - * Configures Spring features in the ECOMP Portal SDK including request - * interceptors and view resolvers. Application should subclass and override - * methods as needed. - */ -public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, ApplicationContextAware { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppConfig.class); - - private final List<String> tileDefinitions = new ArrayList<String>(); - protected ApplicationContext appApplicationContext = null; - - public AppConfig() { - //loads all default fields and marks logging - //has been started for each log file type. - initGlobalLocalContext(); - } - - /** - * Creates and returns a new instance of a secondary (order=2) - * {@link ViewResolver} that finds files by adding prefix "/WEB-INF/jsp/" - * and suffix ".jsp" to the base view name. - * - * @return New instance of {@link ViewResolver}. - */ - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setViewClass(JstlView.class); - viewResolver.setPrefix("/WEB-INF/jsp/"); - viewResolver.setSuffix(".jsp"); - viewResolver.setOrder(2); - return viewResolver; - } - - /** - * Loads all the default logging fields into the - * global MDC context and marks each log file type - * that logging has been started. - */ - private void initGlobalLocalContext() { - logger.init(); - } - - /* - * Any requests from the url pattern /static/**, Spring will look for the - * resources from the /static/ Same as <mvc:resources mapping="/static/**" - * location="/static/"/> in xml - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - // registry.addResourceHandler("/static/**").addResourceLocations("/static/"); - registry.addResourceHandler("/**").addResourceLocations("/"); - } - - /** - * Creates and returns a new instance of a {@link DataAccessService} class. - * - * @return New instance of {@link DataAccessService}. - */ - @Bean - public DataAccessService dataAccessService() { - return new DataAccessServiceImpl(); - } - - /** - * Creates and returns a new instance of a {@link SystemProperties} class. - * - * @return New instance of {@link SystemProperties}. - */ - @Bean - public SystemProperties systemProperties() { - return new SystemProperties(); - } - - /** - * Creates and returns a new instance of a {@link MenuBuilder} class. - * - * @return New instance of {@link MenuBuilder}. - */ - @Bean - public MenuBuilder menuBuilder() { - return new MenuBuilder(); - } - - /** - * Creates and returns a new instance of a {@link UserUtils} class. - * - * @return New instance of {@link UserUtils}. - */ - @Bean - public UserUtils userUtil() { - return new UserUtils(); - } - - /** - * Creates and returns a new instance of an {@link AppUtils} class. - * - * @return New instance of {@link AppUtils}. - */ - @Bean - public AppUtils appUtils() { - return new AppUtils(); - } - - /** - * Creates and returns a new instance of a {@link TilesConfigurer} class. - * - * @return New instance of {@link TilesConfigurer}. - */ - @Bean - public TilesConfigurer tilesConfigurer() { - TilesConfigurer tilesConfigurer = new TilesConfigurer(); - tilesConfigurer.setDefinitions(tileDefinitions()); - tilesConfigurer.setCheckRefresh(true); - return tilesConfigurer; - } - - /** - * - * Application Data Source - * - * @return DataSource Object - */ - - @Bean - public DataSource dataSource() throws Exception { - systemProperties(); - ComboPooledDataSource dataSource = new ComboPooledDataSource(); - try { - dataSource.setDriverClass(SystemProperties.getProperty(SystemProperties.DB_DRIVER)); - dataSource.setJdbcUrl(SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL)); - dataSource.setUser(SystemProperties.getProperty(SystemProperties.DB_USERNAME)); - // dataSource.setPassword(SystemProperties.getProperty(SystemProperties.DB_PASSWOR)); - String password = SystemProperties.getProperty(SystemProperties.DB_PASSWOR); - if (SystemProperties.containsProperty(SystemProperties.DB_ENCRYPT_FLAG)) { - String encryptFlag = SystemProperties.getProperty(SystemProperties.DB_ENCRYPT_FLAG); - if (encryptFlag != null && encryptFlag.equalsIgnoreCase("true")) { - password = CipherUtil.decrypt(password); - } - } - dataSource.setPassword(password); - dataSource - .setMinPoolSize(Integer.parseInt(SystemProperties.getProperty(SystemProperties.DB_MIN_POOL_SIZE))); - dataSource - .setMaxPoolSize(Integer.parseInt(SystemProperties.getProperty(SystemProperties.DB_MAX_POOL_SIZE))); - dataSource.setIdleConnectionTestPeriod( - Integer.parseInt(SystemProperties.getProperty(SystemProperties.IDLE_CONNECTION_TEST_PERIOD))); - dataSource.setTestConnectionOnCheckout(true); - dataSource.setPreferredTestQuery("SELECT 1"); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Error initializing database, verify database settings in properties file: " - + UserUtils.getStackTrace(e),AlarmSeverityEnum.CRITICAL); - logger.error(EELFLoggerDelegate.debugLogger, "Error initializing database, verify database settings in properties file: " - + UserUtils.getStackTrace(e),AlarmSeverityEnum.CRITICAL); - // Raise an alarm that opening a connection to the database is - // failed. - logger.logEcompError(AppMessagesEnum.BeDaoSystemError); - throw e; - } - return dataSource; - } - - /* - * TODO: Check whether it is appropriate to extend the list of tile - * definitions at every invocation. - */ - protected String[] tileDefinitions() { - tileDefinitions.add("/WEB-INF/fusion/defs/definitions.xml"); - tileDefinitions.addAll(addTileDefinitions()); - - return tileDefinitions.toArray(new String[0]); - } - - /** - * Creates and returns a new empty list. This method should be overridden by - * child classes. - * - * @return An empty list. - */ - public List<String> addTileDefinitions() { - return new ArrayList<String>(); - } - - /** - * Creates and returns a new instance of a primary (order=1) - * {@link UrlBasedViewResolver} that finds files using the contents of - * definitions.xml files. - * - * @return New instance of {@link UrlBasedViewResolver} - */ - @Bean - public UrlBasedViewResolver tileViewResolver() { - UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); - viewResolver.setViewClass(TilesView.class); - viewResolver.setOrder(1); - return viewResolver; - } - - /** - * Adds new instances of the following interceptors to the specified - * interceptor registry: {@link SessionTimeoutInterceptor}, - * {@link ResourceInterceptor} - */ - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new SessionTimeoutInterceptor()) - .excludePathPatterns(getExcludeUrlPathsForSessionTimeout()); - registry.addInterceptor(resourceInterceptor()); - } - - /** - * Creates and returns a new instance of a {@link ResourceInterceptor}. - * - * @return New instance of {@link ResourceInterceptor} - */ - @Bean - public ResourceInterceptor resourceInterceptor() { - return new ResourceInterceptor(); - } - - private String[] excludeUrlPathsForSessionTimeout = {}; - - /** - * Gets the array of Strings that are paths excluded for session timeout. - * - * @return Array of String - */ - public String[] getExcludeUrlPathsForSessionTimeout() { - return excludeUrlPathsForSessionTimeout; - } - - /** - * Sets the array of Strings that are paths excluded for session timeout. - */ - public void setExcludeUrlPathsForSessionTimeout(final String... excludeUrlPathsForSessionTimeout) { - this.excludeUrlPathsForSessionTimeout = excludeUrlPathsForSessionTimeout; - } - - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - appApplicationContext = applicationContext; - - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/AppInitializer.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/AppInitializer.java deleted file mode 100644 index df0d56d6..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/AppInitializer.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.conf; - -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; - -public abstract class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppInitializer.class); - private final String activeProfile = "src"; - - @Override - protected WebApplicationContext createServletApplicationContext() { - WebApplicationContext context = super.createServletApplicationContext(); - - try { - - ((ConfigurableEnvironment) context.getEnvironment()).setActiveProfiles(activeProfile); - } catch (Exception e) { - - logger.error(EELFLoggerDelegate.errorLogger, "Unable to set the active profile" + e.getMessage(),AlarmSeverityEnum.MAJOR); - throw e; - - } - - return context; - } - - @Override - protected Class<?>[] getRootConfigClasses() { - return null; - } - - @Override - protected Class<?>[] getServletConfigClasses() { - - return new Class[] { AppConfig.class }; - } - - /* - * URL request will direct to the Spring dispatcher for processing - */ - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/Configurable.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/Configurable.java deleted file mode 100644 index 9585e45d..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/Configurable.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.conf; - -import java.util.List; - -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; - -public interface Configurable { - - public ViewResolver viewResolver(); - - public void addResourceHandlers(ResourceHandlerRegistry registry) ; - - public DataAccessService dataAccessService(); - - public List<String> addTileDefinitions(); - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/HibernateConfiguration.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/HibernateConfiguration.java deleted file mode 100644 index b70ced48..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/HibernateConfiguration.java +++ /dev/null @@ -1,155 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.conf; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import javax.sql.DataSource; - -import org.hibernate.SessionFactory; -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.mchange.v2.c3p0.ComboPooledDataSource; - -@Configuration -@EnableTransactionManagement -public class HibernateConfiguration { - - @Autowired - private SystemProperties systemProperties; - - @Autowired - private HibernateMappingLocatable mappingLocate; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HibernateConfiguration.class); - - DataSource dataSource; - - - @Bean - public LocalSessionFactoryBean sessionFactory() { - LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); - sessionFactory.setDataSource(getDataSource()); - sessionFactory.setPackagesToScan(new String[] { "org.openecomp"}); - sessionFactory.setHibernateProperties(hibernateProperties()); - sessionFactory.setMappingLocations(mappingLocate.getMappingLocations()); - return sessionFactory; - } - - - - - @SuppressWarnings("rawtypes") - @Bean - public Map dataSourceMap() throws Exception { - Connection conn = null; - Statement stmt = null; - Map<String, ComboPooledDataSource> dataSourceMap = new HashMap<String, ComboPooledDataSource>(); - - try { - conn = getDataSource().getConnection(); - stmt = conn.createStatement(); - String sql; - sql = "SELECT schema_id,datasource_type,connection_url,user_name,password,driver_class,min_pool_size,max_pool_size,idle_connection_test_period FROM schema_info"; - ResultSet rs = stmt.executeQuery(sql); - - while (rs.next()) { - ComboPooledDataSource dataSource = new ComboPooledDataSource(); - dataSource.setDriverClass(rs.getString("driver_class")); - dataSource.setJdbcUrl(rs.getString("connection_url")); - dataSource.setUser(rs.getString("user_name")); - dataSource.setPassword(rs.getString("password")); - dataSource.setMinPoolSize(rs.getInt("min_pool_size")); - dataSource.setMaxPoolSize(rs.getInt("max_pool_size")); - dataSource.setIdleConnectionTestPeriod(rs.getInt("idle_connection_test_period")); - dataSourceMap.put(rs.getString("schema_id"), dataSource); - } - rs.close(); - stmt.close(); - conn.close(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Error initializing database, verify database settings in properties file: " + e.getMessage(),AlarmSeverityEnum.CRITICAL); - e.printStackTrace(); - dataSourceMap = null; - throw e; - } finally { - try { - if (stmt != null) - stmt.close(); - } catch (SQLException se2) {} - try { - if (conn != null) - conn.close(); - } catch (SQLException se) { se.printStackTrace();} - } - - return dataSourceMap; - } - - private Properties hibernateProperties() { - Properties properties = new Properties(); - properties.put("hibernate.dialect", SystemProperties.getProperty(SystemProperties.HB_DIALECT)); - properties.put("hibernate.show_sql", SystemProperties.getProperty(SystemProperties.HB_SHOW_SQL)); - return properties; - } - - @Bean - @Autowired - public HibernateTransactionManager transactionManager(SessionFactory s) { - HibernateTransactionManager txManager = new HibernateTransactionManager(); - txManager.setSessionFactory(s); - return txManager; - } - - public SystemProperties getSystemProperties() { - return systemProperties; - } - - public void setSystemProperties(SystemProperties systemProperties) { - this.systemProperties = systemProperties; - } - - - - - public DataSource getDataSource() { - return dataSource; - } - - - @Autowired - public void setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/HibernateMappingLocatable.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/HibernateMappingLocatable.java deleted file mode 100644 index a3bbe18d..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/conf/HibernateMappingLocatable.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.conf; - -import org.springframework.core.io.Resource; - -public interface HibernateMappingLocatable { - - public Resource[] getMappingLocations(); - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AdminAuthGenericController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AdminAuthGenericController.java deleted file mode 100644 index 8a1f1d2c..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AdminAuthGenericController.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; -/*package org.openecomp.portalsdk.core.controller; - -import java.io.IOException; -import java.util.List; - -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.onboarding.crossapi.IGenericRolesService; -import org.openecomp.portalsdk.core.onboarding.crossapi.IGenericUsersService; -import com.fasterxml.jackson.core.JsonProcessingException; - - -@RestController -@RequestMapping("/api") -public class AdminAuthGenericController extends RestrictedRESTfulBaseController { - protected final Log logger = LogFactory.getLog(getClass()); - @Autowired - IGenericUsersService genericUserService; - - @Autowired - IGenericRolesService genericRolesService; - - *//** - * RESTful service method to fetch available roles - * @return - *//* - @RequestMapping(value={"/roles"}, method = RequestMethod.GET, produces = "application/json") - public String getAvailableRoles() throws Exception{ - return genericRolesService.getAvailableRoles(); - } - - *//** - * RESTful service method to save user - expects user details in json string - * @param userJson - *//* - @RequestMapping(value={"/user"}, method = RequestMethod.POST) - public String pushUser(@RequestBody String userJson) throws Exception{ - return genericUserService.pushUser(userJson); - } - - *//** - * RESTful service method to edit user - expects user details in json string - * @param userJson - *//* - @RequestMapping(value={"/user/{loginId}"}, method = RequestMethod.POST) - public String editUser(@PathVariable("loginId") String loginId, @RequestBody String userJson) throws Exception{ - return genericUserService.editUser(loginId, userJson); - } - - *//** - * RESTful service method to save user role using user's login Id and details in role Json string - * @param loginId - * @param roleJson - * @throws JsonProcessingException - *//* - @RequestMapping(value={"/user/{loginId}/roles"}, method = RequestMethod.POST) - public String pushUserRole(@PathVariable("loginId") String loginId, @RequestBody String rolesJson) throws Exception{ - return genericRolesService.pushUserRole(loginId, rolesJson); - } - - - *//** - * Below method is to retrieve user - TODO @Talasila - Created to test the fn_app relation to fn_user_role. If not needed, please remove this method. - * @param id - * @return - * @throws Exception - *//* - @RequestMapping(value={"/user/{loginId}"}, method = RequestMethod.GET, produces = "application/json") - public String getUser(@PathVariable("loginId") String loginId) throws Exception{ - return genericUserService.getUser(loginId); - } - - @RequestMapping(value={"/users"}, method = RequestMethod.GET, produces = "application/json") - public String getUsers() throws Exception{ - return genericUserService.getUsers(); - } - - *//** - * RESTful service method to fetch individual user's roles using user's loginId - * @param loginId - * @return - *//* - @RequestMapping(value={"/user/{loginId}/roles"}, method = RequestMethod.GET, produces = "application/json") - public String getUserRoles(@PathVariable("loginId") String loginId) throws Exception{ - return genericRolesService.getUserRoles(loginId); - } - - *//** - * RESTful service method to fetch available roles - * @return - *//* - - //Commenting this out as it depends on Role API - Ikram - @RequestMapping(value={"/rolesFull"}, method = RequestMethod.GET, produces = "application/json") - public List<Role> getAvailableFullRoles(){ - return genericRolesService.getAvailableFullRoles(); - } - - @ExceptionHandler(Exception.class) - void handleBadRequests(Exception e, HttpServletResponse response) throws IOException { - response.sendError(HttpStatus.BAD_REQUEST.value(),e.getMessage()); - } -} -*/ diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AngularAdminController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AngularAdminController.java deleted file mode 100644 index e3aab7dd..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AngularAdminController.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -@Controller -@RequestMapping("/") -public class AngularAdminController extends RestrictedBaseController{ - - @RequestMapping(value = {"/userProfile" }, method = RequestMethod.GET) - public ModelAndView view(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - - return new ModelAndView("user_profile_list","model", model); - } - - @RequestMapping(value = {"/admin" }, method = RequestMethod.GET) - public ModelAndView adminView(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - - return new ModelAndView(getViewName(),"model", model); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastController.java deleted file mode 100644 index 6dfe9cac..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastController.java +++ /dev/null @@ -1,130 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.BroadcastMessage; -import org.openecomp.portalsdk.core.service.BroadcastService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.AppUtils; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping("/") -public class BroadcastController extends RestrictedBaseController { - - @Autowired - private BroadcastService broadcastService; - - @RequestMapping(value = { "/broadcast" }, method = RequestMethod.GET) - public ModelAndView broadcast(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - try { - model.put("broadcastMessage", mapper.writeValueAsString(broadcastService.getBroadcastMessage(request))); - model.put("broadcastSites", mapper.writeValueAsString(referenceData(request).get("broadcastSites"))); - } catch (Exception e) { - e.printStackTrace(); - } - return new ModelAndView(getViewName(), model); - } - - @RequestMapping(value = { "/get_broadcast" }, method = RequestMethod.GET) - public void getBroadcast(HttpServletRequest request, HttpServletResponse response) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - try { - - model.put("broadcastMessage", mapper.writeValueAsString(broadcastService.getBroadcastMessage(request))); - model.put("broadcastSites", mapper.writeValueAsString(referenceData(request).get("broadcastSites"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected Map referenceData(HttpServletRequest request) { - Map lookupData = new HashMap(); - - if ("true".equals(SystemProperties.getProperty(SystemProperties.CLUSTERED))) { - lookupData.put("broadcastSites", AppUtils.getLookupList("fn_lu_broadcast_site", "broadcast_site_cd", - "broadcast_site_descr", "", "broadcast_site_descr")); - } - - return lookupData; - } - - @RequestMapping(value = { "/broadcast/save" }, method = RequestMethod.POST) - public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception { - - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(), - BroadcastMessage.class); - - broadcastService.saveBroadcastMessage(broadcastMessage); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(broadcastMessage); - JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastListController.java deleted file mode 100644 index 7e0789c2..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastListController.java +++ /dev/null @@ -1,142 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.BroadcastMessage; -import org.openecomp.portalsdk.core.service.BroadcastService; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping("/") -public class BroadcastListController extends RestrictedBaseController { - - @Autowired - private BroadcastService broadcastService; - - @RequestMapping(value = { "/broadcast_list" }, method = RequestMethod.GET) - public ModelAndView broadcastList(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - - model.put("model", broadcastService.getBcModel(request)); - return new ModelAndView(getViewName(), model); - } - - @RequestMapping(value = { "/get_broadcast_list" }, method = RequestMethod.GET) - public void getBroadcast(HttpServletRequest request, HttpServletResponse response) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - try { - model.put("model", broadcastService.getBcModel(request)); - model.put("messagesList", broadcastService.getBcModel(request).get("messagesList")); - model.put("messageLocations", broadcastService.getBcModel(request).get("messageLocations")); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - @RequestMapping(value = { "/broadcast_list/remove" }, method = RequestMethod.POST) - public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { - - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(), - BroadcastMessage.class); - - broadcastService.removeBroadcastMessage(broadcastMessage); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(broadcastMessage); - JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - @RequestMapping(value = { "/broadcast_list/toggleActive" }, method = RequestMethod.POST) - public ModelAndView toggleActive(HttpServletRequest request, HttpServletResponse response) throws Exception { - - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(), - BroadcastMessage.class); - - broadcastService.saveBroadcastMessage(broadcastMessage); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(broadcastMessage); - JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CacheAdminController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CacheAdminController.java deleted file mode 100644 index 095c41b6..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CacheAdminController.java +++ /dev/null @@ -1,252 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.jcs.JCS; -import org.apache.jcs.admin.CacheRegionInfo; -import org.apache.jcs.admin.JCSAdminBean; -import org.apache.jcs.engine.behavior.ICacheElement; -import org.json.JSONArray; -import org.json.JSONObject; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -@Controller -@RequestMapping("/") -public class CacheAdminController extends RestrictedBaseController { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CacheAdminController.class); - private JCSAdminBean jcsAdminBean = new JCSAdminBean(); - - @RequestMapping(value = {"/jcs_admin" }, method = RequestMethod.GET) - public ModelAndView cacheAdmin(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - - model.put("model", getRegions()); - - return new ModelAndView(getViewName(),model); - } - - @RequestMapping(value = {"/get_regions" }, method = RequestMethod.GET) - public void getRegions(HttpServletRequest request,HttpServletResponse response) { - // ObjectMapper mapper = new ObjectMapper(); - try{ - JsonMessage msg = new JsonMessage(getRegions().toString()); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - }catch (Exception e) { - e.printStackTrace(); - } - - } - - @RequestMapping(value = {"/jcs_admin/clearRegion" }, method = RequestMethod.GET) - public void clearRegion(HttpServletRequest request,HttpServletResponse response) throws Exception { - String cacheName = (String) request.getParameter("cacheName"); - clearCacheRegion(cacheName); - - response.setContentType("application/json"); - PrintWriter out = response.getWriter(); - out.write(getRegions().toString()); - } - - @RequestMapping(value = {"/jcs_admin/clearAll" }, method = RequestMethod.GET) - public void clearAll(HttpServletRequest request,HttpServletResponse response) throws Exception { - clearAllRegions(); - - response.setContentType("application/json"); - PrintWriter out = response.getWriter(); - out.write(getRegions().toString()); - } - - @RequestMapping(value = {"/jcs_admin/clearItem" }, method = RequestMethod.GET) - public void clearItem(HttpServletRequest request,HttpServletResponse response) throws Exception { - String keyName = (String) request.getParameter("keyName"); - String cacheName = (String) request.getParameter("cacheName"); - clearCacheRegionItem(cacheName, keyName); - - response.setContentType("application/json"); - PrintWriter out = response.getWriter(); - out.write(getRegions().toString()); - } - - @RequestMapping(value = {"/jcs_admin/showItemDetails" }, method = RequestMethod.GET) - public void showItemDetails(HttpServletRequest request,HttpServletResponse response) throws Exception { - String cacheName = (String) request.getParameter("cacheName"); - String keyName = (String) request.getParameter("keyName"); - String details = null; - - try { - details = getItemDetails(cacheName, keyName); - } catch (Exception e) { - details = "There was an error retrieving the region details. Please try again."; - logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while retrieving the item details for the cache region - " - + cacheName + e.getMessage()); - - } - - response.setContentType("application/json"); - PrintWriter out = response.getWriter(); - out.write(details); - } - - @RequestMapping(value = {"/jcs_admin/showRegionDetails" }, method = RequestMethod.GET) - public void showRegionDetails(HttpServletRequest request,HttpServletResponse response) throws Exception { - String cacheName = (String) request.getParameter("cacheName"); - String details = null; - - try { - details = getRegionStats(cacheName); - } catch (Exception e) { - details = "There was an error retrieving the region details. Please try again."; - logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while retrieving the region details for the cache region - " - + cacheName + e.getMessage()); - - } - - response.setContentType("application/json"); - PrintWriter out = response.getWriter(); - out.write(details); - } - - @SuppressWarnings("unchecked") - public JSONArray getRegions(){ - LinkedList<CacheRegionInfo> regions = null; - JSONArray ja = new JSONArray(); - try { - regions = getJcsAdminBean().buildCacheInfo(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); - for (CacheRegionInfo cri : regions) { - JSONObject jo = new JSONObject(); - jo.put("cacheName", cri.getCache().getCacheName()); - jo.put("size", cri.getCache().getSize()); - jo.put("byteCount", cri.getByteCount()); - jo.put("status", cri.getStatus()); - jo.put("hitCountRam", cri.getCache().getHitCountRam()); - jo.put("hitCountAux", cri.getCache().getHitCountAux()); - jo.put("missCountNotFound", cri.getCache().getMissCountNotFound()); - jo.put("missCountExpired", cri.getCache().getMissCountExpired()); - jo.put("items",new JSONArray(mapper.writeValueAsString(getRegionItems(cri.getCache().getCacheName())))); - ja.put(jo); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while retrieving the list of cache regions" + e.getMessage()); - - } - - return ja; - } - - private String getRegionStats(String cacheName) throws Exception { - String stats = ""; - - JCS cache = JCS.getInstance(cacheName); - stats = cache.getStats(); - - return stats; - } - - private String getItemDetails(String cacheName, String keyName) - throws Exception { - String details = ""; - - JCS cache = JCS.getInstance(cacheName); - ICacheElement element = cache.getCacheElement(keyName); - - if (element != null) { - ObjectMapper mapper = new ObjectMapper(); - mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); - details = mapper.writeValueAsString(element); - } - - return details; - } - - @SuppressWarnings("rawtypes") - private List getRegionItems(String cacheName) { - List items = null; - - try { - items = getJcsAdminBean().buildElementInfo(cacheName); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while retrieving the list of items for cache region - " - + cacheName + e.getMessage()); - - } - - return items; - } - - private void clearAllRegions() { - try { - getJcsAdminBean().clearAllRegions(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while clearing all cache regions." + e.getMessage()); - - } - } - - private void clearCacheRegion(String cacheName) { - try { - getJcsAdminBean().clearRegion(cacheName); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while clearing the cache region - " - + cacheName + e.getMessage()); - - } - } - - private void clearCacheRegionItem(String cacheName, String keyName) { - try { - getJcsAdminBean().removeItem(cacheName, keyName); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while removing cache region item - " - + keyName + e.getMessage()); - - } - } - - public JCSAdminBean getJcsAdminBean() { - return jcsAdminBean; - } - - public void setJcsAdminBean(JCSAdminBean jcsAdminBean) { - this.jcsAdminBean = jcsAdminBean; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborateListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborateListController.java deleted file mode 100644 index 9e43e948..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborateListController.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.UserProfileService; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping("/") -public class CollaborateListController extends RestrictedBaseController{ - @Autowired - UserProfileService service; - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CollaborateListController.class); - - @RequestMapping(value = {"/collaborate_list" }, method = RequestMethod.GET) - public ModelAndView ProfileSearch(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - User user = UserUtils.getUserSession(request); - - List<User> profileList =null; - try { - profileList = service.findAllUserWithOnOffline(user.getOrgUserId()); - model.put("profileList", mapper.writeValueAsString(profileList)); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Error happened during collaborate list search" + e.getMessage()); - - } - return new ModelAndView(getViewName(),"model", model); - } - - @RequestMapping(value = {"/get_collaborate_list" }, method = RequestMethod.GET) - public void getCollaborateList(HttpServletRequest request,HttpServletResponse response) { - - ObjectMapper mapper = new ObjectMapper(); - User user = UserUtils.getUserSession(request); - - List<User> profileList =null; - try { - profileList = service.findAllUserWithOnOffline(user.getOrgUserId()); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(profileList)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Error happened during get collaborate list" + e.getMessage()); - - } - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborationController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborationController.java deleted file mode 100644 index a9c1d44b..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborationController.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -@Controller -@RequestMapping("/") -public class CollaborationController extends RestrictedBaseController{ - - @RequestMapping(value = {"/collaboration" }, method = RequestMethod.GET) - public ModelAndView view(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - User user = UserUtils.getUserSession(request); - - model.put("name",(user.getFirstName() + " " + (user.getLastName() != null? user.getLastName().substring(0,1): "" ))); - return new ModelAndView(getViewName(),"model", model); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ElementModelController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ElementModelController.java deleted file mode 100644 index a6e7b966..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ElementModelController.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.portalsdk.core.service.ElementLinkService; -import org.openecomp.portalsdk.core.service.ElementMapService; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - - -@Controller -@RequestMapping("/") -public class ElementModelController extends RestrictedBaseController{ - - @RequestMapping(value = {"/elementMapLayout" }, method = RequestMethod.POST) - public ModelAndView layout(HttpServletRequest request, - HttpServletResponse response) throws Exception{ - - Map<String, Object> model = new HashMap<String, Object>(); - String collapseDomains = request.getParameter("collapsedDomains"); - String expandDomains = request.getParameter("expandedDomains"); - - String contentFileName = request.getParameter("contentFileName"); - String layoutFileName = request.getParameter("layoutFileName"); - - ElementMapService main = new ElementMapService(); - String yamlString = main.main1(new String[]{collapseDomains,expandDomains, contentFileName, layoutFileName }); - - //response.setContentType("application/json"); - //PrintWriter out = response.getWriter(); - //out.print(yamlString); - //out.flush(); - - //return null; - model.put("output_string", yamlString); - return new ModelAndView("data_out", "model", model); - } - - @RequestMapping(value = {"/elementMapLink" }, method = RequestMethod.POST) - public ModelAndView callflow(HttpServletRequest request, - HttpServletResponse response) throws Exception{ - - Map<String, Object> model = new HashMap<String, Object>(); - String callFlowName = request.getParameter("callFlowName"); - String callFlowStep = request.getParameter("callFlowStep"); - - ElementLinkService main = new ElementLinkService(); - String yamlString = main.main1(new String[]{callFlowName,callFlowStep }); - model.put("output_string", yamlString); - return new ModelAndView("data_out", "model", model); - } - - public ModelAndView callflowAdditional(HttpServletRequest request, - HttpServletResponse response) throws Exception{ - - Map<String, Object> model = new HashMap<String, Object>(); - String callFlowName = request.getParameter("callFlowName"); - String callFlowStep = request.getParameter("callFlowStep"); - - ElementLinkService main = new ElementLinkService(); - String yamlString = main.main2(new String[]{callFlowName,callFlowStep }); - model.put("output_string", yamlString); - return new ModelAndView("data_out", "model", model); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ExternalLoginController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ExternalLoginController.java deleted file mode 100644 index 90e47d42..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ExternalLoginController.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.portalsdk.core.command.LoginBean; -import org.openecomp.portalsdk.core.menu.MenuProperties; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler; -import org.openecomp.portalsdk.core.service.LoginService; -import org.openecomp.portalsdk.core.service.ProfileService; -import org.openecomp.portalsdk.core.web.support.AppUtils; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.servlet.ModelAndView; - -@Controller -@RequestMapping("/") -public class ExternalLoginController extends UnRestrictedBaseController{ - @Autowired - ProfileService service; - @Autowired - private LoginService loginService; - String viewName; - - @RequestMapping(value = {"/login_external.htm" }, method = RequestMethod.GET) - public ModelAndView ExternalLogin(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - return new ModelAndView(getViewName(),"model", model); - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @RequestMapping(value = {"/login_external/login" }, method = RequestMethod.POST) - public @ResponseBody String ExternalLogin(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - Map model = new HashMap(); - LoginBean commandBean = new LoginBean(); - String loginId = request.getParameter("loginId"); - String password = request.getParameter("password"); - commandBean.setLoginId(loginId); - commandBean.setLoginPwd(password); - HashMap additionalParamsMap = new HashMap(); - - commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), - additionalParamsMap); - - if (commandBean.getUser() == null) { - String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage() - : "login.error.external.invalid"; - model.put("error", loginErrorMessage); - String[] errorCodes = new String[1]; - errorCodes[0] = loginErrorMessage; - return "failure"; - - } - else { - // store the currently logged in user's information in the session - UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), - null); - initateSessionMgtHandler(request); - // user has been authenticated, now take them to the welcome page - return "success"; - - } - - - } - - public String getJessionId(HttpServletRequest request){ - - return request.getSession().getId(); - - } - - protected void initateSessionMgtHandler(HttpServletRequest request) { - String jSessionId = getJessionId(request); - PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request)); - } - - public String getViewName() { - return viewName; - } - public void setViewName(String viewName) { - this.viewName = viewName; - } - public LoginService getLoginService() { - return loginService; - } - - public void setLoginService(LoginService loginService) { - this.loginService = loginService; - } - -} - diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FavoritesController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FavoritesController.java deleted file mode 100644 index b2ad61f4..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FavoritesController.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.App; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.aspect.AuditLog; -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.onboarding.rest.FavoritesClient; -import org.openecomp.portalsdk.core.service.AppService; -import org.openecomp.portalsdk.core.util.CipherUtil; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@Controller -@RequestMapping("/") -@org.springframework.context.annotation.Configuration -@EnableAspectJAutoProxy -@AuditLog -public class FavoritesController extends UnRestrictedBaseController { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FavoritesController.class); - - @Autowired - AppService appService; - - /** - * Makes the REST API call to Portal Back-end and retrieves Favorite menu - * items for the currently logged in user. - * - * @param request - * @param response - */ - @RequestMapping(value = { "/get_favorites" }, method = RequestMethod.GET) - public void getFavorites(HttpServletRequest request, HttpServletResponse response) { - String appName = ""; - String requestId = ""; - String appUserName = ""; - String decryptedPwd = ""; - - try { - HttpSession session = request.getSession(); - User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); - if (user == null || user.getId() == null) { - logger.info(EELFLoggerDelegate.errorLogger, - ("Http request did not contain user info, cannot retrieve favorites.")); - - response.setContentType("application/json"); - JSONArray jsonResponse = new JSONArray(); - JSONObject error = new JSONObject(); - error.put("error", "Http request did not contain user info, cannot retrieve favorites."); - jsonResponse.put(error); - response.getWriter().write(jsonResponse.toString()); - } else { - logger.info(EELFLoggerDelegate.errorLogger, - "Retrieving Favorites for the user '" + MDC.get(SystemProperties.MDC_LOGIN_ID) + "'."); - - App app = appService.getDefaultApp(); - if (app!=null) { - appName = app.getName(); - appUserName = app.getUsername(); - try{ - decryptedPwd = 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.SDK_NAME; - } - requestId = MDC.get(MDC_KEY_REQUEST_ID); - - String jsonResponse = FavoritesClient.getFavorites(MDC.get(SystemProperties.MDC_LOGIN_ID), appName, requestId, appUserName, decryptedPwd); - - logger.debug(EELFLoggerDelegate.debugLogger, "FavoritesMenu response: " + jsonResponse); - - response.setContentType("application/json"); - response.getWriter().write(jsonResponse); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred in FavoritesController.getFavorites while performing get_favorites. Details: " - + e.getMessage(), AlarmSeverityEnum.MINOR); - } - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FnMenuController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FnMenuController.java deleted file mode 100644 index f19a6f19..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FnMenuController.java +++ /dev/null @@ -1,224 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.Menu; -import org.openecomp.portalsdk.core.domain.MenuData; -import org.openecomp.portalsdk.core.service.FnMenuService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * Description: this java class is a controller for Admin to add/edit/delete menu items from FN_MENU - */ - -@Controller -@RequestMapping("/") -public class FnMenuController extends RestrictedBaseController { - @Autowired - FnMenuService service; - - String viewName; - - @RequestMapping(value = {"/admin_fn_menu/get_parent_list" }, method = RequestMethod.GET) - public void getParentList(HttpServletRequest request,HttpServletResponse response) throws Exception { - ObjectMapper mapper = new ObjectMapper(); - try{ - - response.getWriter().write(mapper.writeValueAsString(service.getParentList())); - - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - - } - - } - - @RequestMapping(value = {"/admin_fn_menu/get_function_cd_list" }, method = RequestMethod.GET) - public void getFunctionCDList(HttpServletRequest request,HttpServletResponse response) throws Exception { - ObjectMapper mapper = new ObjectMapper(); - try{ - - response.getWriter().write(mapper.writeValueAsString(service.getFunctionCDList())); - - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - - } - - } - - @RequestMapping(value = {"/admin_fn_menu" }, method = RequestMethod.GET) - public void getFnMenuList(HttpServletRequest request,HttpServletResponse response) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - List<MenuData> temp =null; - List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>(); - List<MenuData> parentList = new ArrayList<>(); - - try { - temp = service.getFnMenuItems(); - for(MenuData menu: temp){ - MenuData parentData = new MenuData(); - parentData.setId(menu.getId()); - parentData.setLabel(menu.getLabel()); - if(menu.getParentMenu()!=null){ - parentData.setParentId(menu.getParentMenu().getId()); - } - parentData.setAction(menu.getAction()); - parentData.setFunctionCd(menu.getFunctionCd()); - parentData.setImageSrc(menu.getImageSrc()); - parentData.setSortOrder(menu.getSortOrder()); - parentData.setActive(menu.isActive()); - parentData.setServlet(menu.getServlet()); - parentData.setQueryString(menu.getQueryString()); - parentData.setExternalUrl(menu.getExternalUrl()); - parentData.setTarget(menu.getTarget()); - parentData.setMenuSetCode(menu.getMenuSetCode()); - parentData.setSeparator(menu.isSeparator()); - parentData.setImageSrc(menu.getImageSrc()); - parentList.add(parentData); - List<MenuData> tempList = new ArrayList<MenuData>(); - childItemList.add(tempList); - } - model.put("fnMenuItems", parentList); - - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (JsonGenerationException e) { - e.printStackTrace(); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - - @RequestMapping(value = {"/admin_fn_menu/updateFnMenu" }, method = RequestMethod.POST) - public ModelAndView updateFnMenu(HttpServletRequest request, - HttpServletResponse response) throws Exception { - - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Menu fnMenuItem = mapper.readValue(root.get("availableFnMenuItem").toString(), Menu.class); - - service.saveFnMenu(fnMenuItem); - request.getSession().removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); - request.getSession().removeAttribute(SystemProperties.LEFT_MENU_CHILDREND); - request.getSession().removeAttribute(SystemProperties.LEFT_MENU_PARENT); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(service.getMenuItem(fnMenuItem.getId())); - - out.write(responseString); - - return null; - - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - - } - return null; - - } - - @RequestMapping(value = {"/admin_fn_menu/removeMenuItem" }, method = RequestMethod.POST) - public ModelAndView removeFnMenu(HttpServletRequest request, - HttpServletResponse response) throws Exception { - - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Menu fnMenuItem = mapper.readValue(root.get("fnMenuItem").toString(), Menu.class); - Menu fnMenuItemRow = service.getMenuItemRow(fnMenuItem.getId()); - - service.removeMenuItem(fnMenuItemRow); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(service.getMenuItem(fnMenuItem.getId())); - out.write(responseString); - - return null; - - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - - - } - return null; - - } - - public String getViewName() { - return viewName; - } - public void setViewName(String viewName) { - this.viewName = viewName; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FuncMenuController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FuncMenuController.java deleted file mode 100644 index 5baebf00..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FuncMenuController.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.App; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.aspect.AuditLog; -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; -import org.openecomp.portalsdk.core.onboarding.rest.FunctionalMenuClient; -import org.openecomp.portalsdk.core.onboarding.ueb.UebException; -import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; -import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; -import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes; -import org.openecomp.portalsdk.core.service.AppService; -import org.openecomp.portalsdk.core.util.CipherUtil; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@Controller -@RequestMapping("/") -@org.springframework.context.annotation.Configuration -@EnableAspectJAutoProxy -public class FuncMenuController extends UnRestrictedBaseController{ - - @Autowired - AppService appService; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FuncMenuController.class); - - @AuditLog - @RequestMapping(value = {"/get_functional_menu" }, method = RequestMethod.GET) - public void functionalMenu(HttpServletRequest request, HttpServletResponse response) { - - User user = UserUtils.getUserSession(request); - //JSONArray validMenu = new JSONArray("[{\"menuId\":140,\"column\":1,\"text\":\"RT SDK Menu\",\"parentMenuId\":139,\"url\":\"http://www.cnn.com\"},{\"menuId\":139,\"column\":1,\"text\":\"RT Menu\",\"parentMenuId\":11,\"url\":\"\"},{\"menuId\":11,\"column\":1,\"text\":\"Product Design\",\"parentMenuId\":1,\"url\":\"\"},{\"menuId\":1,\"column\":1,\"text\":\"Design\",\"url\":\"\"}]"); - - try { - if ( user != null ) { - String useRestForFunctionalMenu = PortalApiProperties.getProperty(PortalApiConstants.USE_REST_FOR_FUNCTIONAL_MENU); - String funcMenuJsonString = ""; - if (useRestForFunctionalMenu==null || useRestForFunctionalMenu=="" || useRestForFunctionalMenu.equalsIgnoreCase("false")) { - logger.info(EELFLoggerDelegate.errorLogger, "Making use of UEB communication and Requesting functional menu for user " + user.getOrgUserId()); - funcMenuJsonString = getFunctionalMenu(user.getOrgUserId()); - } else { - funcMenuJsonString = getFunctionalMenuViaREST(user.getOrgUserId()); - } - response.setContentType("application/json"); - response.getWriter().write(funcMenuJsonString); - } else { - logger.info(EELFLoggerDelegate.errorLogger, "Http request did not contain user info, cannot retrieve functional menu"); - response.setContentType("application/json"); - JSONArray jsonResponse = new JSONArray(); - JSONObject error = new JSONObject(); - error.put("error","Http request did not contain user info, cannot retrieve functional menu"); - jsonResponse.put(error); - response.getWriter().write(jsonResponse.toString()); - } - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json"); - JSONArray jsonResponse = new JSONArray(); - JSONObject error = new JSONObject(); - try { - if ( null == e.getMessage() ) { - error.put("error","No menu data"); - } else { - error.put("error",e.getMessage()); - } - jsonResponse.put(error); - response.getWriter().write(jsonResponse.toString()); - logger.error(EELFLoggerDelegate.errorLogger, "Error getting functional_menu: " + e.getMessage(),AlarmSeverityEnum.MAJOR); - } catch (IOException e1) { - e1.printStackTrace(); - } - } - - } - - //-------------------------------------------------------------------------- - // Makes a synchronous call to ECOMP Portal to get the JSON file that - // contains the contents of the functional menu. The JSON file will be - // in the payload of the returned UEB message. - //-------------------------------------------------------------------------- - private String getFunctionalMenu(String userId) throws UebException - { - String returnString = null; - UebMsg funcMenuUebMsg = null; - UebMsg msg = new UebMsg(); - msg.putMsgType(UebMsgTypes.UEB_MSG_TYPE_GET_FUNC_MENU); - msg.putUserId(userId); - funcMenuUebMsg = UebManager.getInstance().requestReply(msg); - if (funcMenuUebMsg != null) { - if (funcMenuUebMsg.getPayload().startsWith("Error:")) { - logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenu received an error in UEB msg = " + funcMenuUebMsg.getPayload()); - } else { - returnString = funcMenuUebMsg.getPayload(); - } - } - - logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenu response: " + returnString); - - return returnString; - } - - private String getFunctionalMenuViaREST(String userId) { - String appName = ""; - String requestId = ""; - String appUserName = ""; - String decryptedPwd = ""; - - logger.info(EELFLoggerDelegate.debugLogger, "Making use of REST API communication and Requesting functional menu for user " + userId); - - App app = appService.getDefaultApp(); - if (app!=null) { - appName = app.getName(); - appUserName = app.getUsername(); - try{ - decryptedPwd = 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.toString()); - } - } else { - logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database."); - appName = SystemProperties.SDK_NAME; - } - requestId = MDC.get(MDC_KEY_REQUEST_ID); - - String fnMenu = null; - try { - fnMenu = FunctionalMenuClient.getFunctionalMenu(userId, appName, requestId, appUserName, decryptedPwd); - }catch(Exception ex) { - fnMenu = "Failed to get functional menu: " + ex.toString(); - } - - logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenu response: {}", fnMenu); - - return fnMenu; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FusionBaseController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FusionBaseController.java deleted file mode 100644 index c7820115..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FusionBaseController.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.openecomp.portalsdk.core.domain.MenuData; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.interfaces.SecurityInterface; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.menu.MenuBuilder; -import org.openecomp.portalsdk.core.service.AppService; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.openecomp.portalsdk.core.service.FnMenuService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.ModelAttribute; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -public abstract class FusionBaseController implements SecurityInterface{ - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FusionBaseController.class); - - @Override - public boolean isAccessible() { - return true; - } - - public boolean isRESTfulCall(){ - return true; - } - @Autowired - private FnMenuService fnMenuService; - - @Autowired - private MenuBuilder menuBuilder; - - @Autowired - private DataAccessService dataAccessService; - - @Autowired - AppService appService; - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @ModelAttribute("menu") - public Map<String, Object> getMenu(HttpServletRequest request) { - HttpSession session = null; - Map<String, Object> model = new HashMap<String, Object>(); - try { - try { - String appName = appService.getDefaultAppName(); - if (appName==null || appName=="") { - appName = SystemProperties.SDK_NAME; - } - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, appName); - } catch (Exception e) { - } - - session = request.getSession(); - User user = UserUtils.getUserSession(request); - if(session!=null && user!=null){ - Set<MenuData> menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); - if(menuResult==null){ - Set appMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME),dataAccessService); - session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME), MenuBuilder.filterMenu(appMenu, request)); - menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); - } - model = setMenu(menuResult); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); - } - return model; - } - - public Map<String, Object> setMenu(Set<MenuData> menuResult) throws Exception{ - ObjectMapper mapper = new ObjectMapper(); - List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>();; - List<MenuData> parentList = new ArrayList<MenuData>();; - Map<String, Object> model = new HashMap<String, Object>(); - try{ - fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult); - }catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); - } - model.put("childItemList",childItemList!=null?mapper.writeValueAsString(childItemList):""); - model.put("parentList",parentList!=null?mapper.writeValueAsString(parentList):""); - return model; - } - - public MenuBuilder getMenuBuilder() { - return menuBuilder; - } - - public void setMenuBuilder(MenuBuilder menuBuilder) { - this.menuBuilder = menuBuilder; - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/LogoutController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/LogoutController.java deleted file mode 100644 index 57983621..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/LogoutController.java +++ /dev/null @@ -1,110 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.web.servlet.ModelAndView; - -@Controller -@RequestMapping("/") -public class LogoutController extends UnRestrictedBaseController{ - - private User user; - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LogoutController.class); - /** - * @param request - * @param response - * @return modelView - * - * globalLogout will invalid the current application session, then redirects to portal logout - */ - @RequestMapping(value = {"/logout.htm" }, method = RequestMethod.GET) - public ModelAndView globalLogout(HttpServletRequest request, HttpServletResponse response) { - ModelAndView modelView = null; - try{ - chatRoomLogout(request); - request.getSession().invalidate(); - String portalUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); - String portalDomain = portalUrl.substring(0, portalUrl.lastIndexOf('/')); - String redirectUrl = portalDomain+"/logout.htm"; - modelView = new ModelAndView("redirect:"+redirectUrl); - }catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "Logout Error: " + e.getMessage(),AlarmSeverityEnum.MAJOR); - } - return modelView; - } - - /** - * @param request - * @param response - * @return modelView - * - * appLogout is a function that will invalid the current session (application logout) and redirects user to Portal. - */ - @RequestMapping(value = {"/app_logout.htm" }, method = RequestMethod.GET) - public ModelAndView appLogout(HttpServletRequest request, HttpServletResponse response) { - ModelAndView modelView = null; - try{ - chatRoomLogout(request); - modelView = new ModelAndView("redirect:"+PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL)); - UserUtils.clearUserSession(request); - request.getSession().invalidate(); - }catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "Application Logout Error: " + e.getMessage(),AlarmSeverityEnum.MAJOR); - } - return modelView; - } - - - public void chatRoomLogout(HttpServletRequest request){ - request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); - setUser(UserUtils.getUserSession(request)); - // if(getUser()!=null){ - // Long login_IdLong = getUser().getId(); - // String name = getUser().getFirstName(); - // String login_IdStr = Long.toString(login_IdLong); - // } - //UserListName.getInstance().delUserName(name); - //UserListID.getInstance().delUserName(login_IdStr); - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/MenuListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/MenuListController.java deleted file mode 100644 index ee66a948..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/MenuListController.java +++ /dev/null @@ -1,245 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.MenuData; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; -import org.openecomp.portalsdk.core.restful.client.SharedContextRestClient; -import org.openecomp.portalsdk.core.restful.domain.SharedContext; -import org.openecomp.portalsdk.core.service.AppService; -import org.openecomp.portalsdk.core.service.FnMenuService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.fasterxml.jackson.databind.ObjectMapper; - - -@Controller -@RequestMapping("/") -public class MenuListController extends UnRestrictedBaseController{ - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MenuListController.class); - @Autowired - AppService appService; - @Autowired - FnMenuService fnMenuService; - @Autowired - SharedContextRestClient sharedContextRestClient; - /** - * - * Get Menu items and store into session. - * - * @param request - * @param response - */ - @SuppressWarnings("unchecked") - @RequestMapping(value = {"/get_menu" }, method = RequestMethod.GET) - public void ProfileSearch(HttpServletRequest request, HttpServletResponse response) { - logger.info("calling /get_menu.."); - try { - ObjectMapper mapper = new ObjectMapper(); - Set<MenuData> menuResult=null; - HttpSession session = request.getSession(); - List<List<MenuData>> childItemList = (List<List<MenuData>>) session.getAttribute(SystemProperties.LEFT_MENU_CHILDREND); - List<MenuData> parentList = (List<MenuData>) session.getAttribute(SystemProperties.LEFT_MENU_PARENT); - if(parentList==null || childItemList==null || parentList.size()==0 || childItemList.size()==0){ - childItemList=new ArrayList<List<MenuData>>(); - parentList = new ArrayList<MenuData>(); - menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); - fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult); - logger.info("storing leftmenu items into session"); - session.setAttribute(SystemProperties.LEFT_MENU_PARENT, parentList); - session.setAttribute(SystemProperties.LEFT_MENU_CHILDREND, childItemList); - } - String userName = (String) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(parentList),mapper.writeValueAsString(childItemList),userName); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - logger.info("done with /get_menu call without any errors"); - } catch (Exception e) { - logger.info("errors while calling /get_menu",e); - } - } - - /** - * - * Get app name from system.properties file. - * - * @param request - * @param response - */ - - @RequestMapping(value = {"/get_app_name" }, method = RequestMethod.GET) - public void getAppName(HttpServletRequest request, HttpServletResponse response) { - logger.info("calling /get_app_name."); - HttpSession session = request.getSession(true); - try { - // String appName = SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME); - String appName = (String) session.getAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)); - if(appName!=null && appName.equals("app_display_name")){ - appName = ""; - } - JsonMessage msg = new JsonMessage(appName); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - logger.info("done with /get_app_name call without any errors"); - } catch (Exception e) { - logger.error("errors while calling /get_app_name",e); - } - } - - @SuppressWarnings("unchecked") - @ModelAttribute("menu") - public Map<String, Object> getLeftMenuJSP(HttpServletRequest request) { - logger.info("invoking getting left menu"); - ObjectMapper mapper = new ObjectMapper(); - Map<String, Object> model = new HashMap<String, Object>(); - try { - HttpSession session = request.getSession(); - List<List<MenuData>> childItemList = (List<List<MenuData>>) session.getAttribute(SystemProperties.LEFT_MENU_CHILDREND); - List<MenuData> parentList = (List<MenuData>) session.getAttribute(SystemProperties.LEFT_MENU_PARENT); - if(parentList==null || childItemList==null){ - childItemList=new ArrayList<List<MenuData>>(); - parentList = new ArrayList<MenuData>(); - Set<MenuData> menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); - fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult); - session.setAttribute(SystemProperties.LEFT_MENU_PARENT, parentList); - session.setAttribute(SystemProperties.LEFT_MENU_CHILDREND, childItemList); - } - model.put("childItemList",mapper.writeValueAsString(childItemList)); - model.put("parentList",mapper.writeValueAsString(parentList)); - } catch (Exception e) { - logger.info("errors while getting left menu",e); - } - logger.info("done with getting left menu without any errors"); - return model; - } - - /** - * Answers requests for user information, which is fetched from the shared context at Portal. - * - * @param request - * @param response - * @return JSON block with user information. - */ - @RequestMapping(value = {"/get_userinfo" }, method = RequestMethod.GET) - public String getUserInfo(HttpServletRequest request, HttpServletResponse response) { - logger.info(EELFLoggerDelegate.debugLogger, "Getting shared context for user"); - try{ - String contextId= null; - if(request.getCookies()!=null){ - for(Cookie ck :request.getCookies()){ - if(ck.getName().equalsIgnoreCase("EPService")) - contextId = ck.getValue(); - } - } - logger.info(EELFLoggerDelegate.debugLogger, "ContextId is : " + contextId); - List<SharedContext> sharedContextRes = sharedContextRestClient.getUserContext(contextId); - logger.info(EELFLoggerDelegate.debugLogger, "Shared Context Response is : " + sharedContextRes); - Map<String, Object> model = new HashMap<String, Object>(); - for(SharedContext sharedContext: sharedContextRes){ - model.put(sharedContext.getCkey(), sharedContext.getCvalue()); - } - JSONObject j = new JSONObject(model); - response.getWriter().write(j.toString()); - } catch(Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to get shared context for user" + e.getMessage()); - } - return null; - } - - /** - * Get User information from app sessions - * @param request - * @param response - */ - @RequestMapping(value = {"/get_topMenuInfo" }, method = RequestMethod.GET) - public void getTopMenu(HttpServletRequest request, HttpServletResponse response) { - - HttpSession session = request.getSession(); - try { - String userName = (String) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME)); - String firstName = (String) session.getAttribute(SystemProperties.FIRST_NAME); - String lastName = (String) session.getAttribute(SystemProperties.LAST_NAME); - User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); - Map<String,String> map = new HashMap<String,String>(); - String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); - String portalDomain = redirectUrl.substring(0, redirectUrl.lastIndexOf('/')); - String portalUrl = portalDomain + "/processSingleSignOn"; - String getAccessUrl = portalDomain + "/get_access"; - String email = user.getEmail(); - String contactUsLink = SystemProperties.getProperty(SystemProperties.CONTACT_US_LINK); - String userId = UserUtils.getUserIdFromCookie(request); - - map.put("portalUrl", portalUrl); - map.put("contactUsLink", contactUsLink); - map.put("userName", userName); - map.put("firstName", firstName); - map.put("lastName", lastName); - map.put("userid", userId); - map.put("email", email); - map.put("getAccessUrl",getAccessUrl); - JSONObject j = new JSONObject(map); - response.getWriter().write(j.toString()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to serialize JSON" + e.getMessage()); - } - - } - - @RequestMapping(value = {"/page_redirect" }, method = RequestMethod.GET) - public void pageRedirect(HttpServletRequest request, HttpServletResponse response) { - String pageToURL=null; - try { - String pageTo = request.getParameter("page"); - if(pageTo.equals("contact")) - pageToURL = SystemProperties.getProperty(SystemProperties.CONTACT_US_LINK); - else if(pageTo.equals("access")){ - String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); - String portalDomain = redirectUrl.substring(0, redirectUrl.lastIndexOf('/')); - pageToURL = portalDomain + "/get_access"; - } - response.getWriter().write(pageToURL); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to serialize JSON" + e.getMessage()); - } - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/PostSearchController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/PostSearchController.java deleted file mode 100644 index fa5a1082..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/PostSearchController.java +++ /dev/null @@ -1,219 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.command.PostSearchBean; -import org.openecomp.portalsdk.core.domain.Lookup; -import org.openecomp.portalsdk.core.domain.Profile; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.LdapService; -import org.openecomp.portalsdk.core.service.PostSearchService; -import org.openecomp.portalsdk.core.service.ProfileService; -import org.openecomp.portalsdk.core.service.UserProfileService; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping("/") -public class PostSearchController extends RestrictedBaseController { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostSearchController.class); - - @SuppressWarnings("rawtypes") - private static List sortByList = null; - - @Autowired - private PostSearchService postSearchService; - - @Autowired - LdapService ldapService; - - @Autowired - private ProfileService profileService; - - @Autowired - UserProfileService userProfileService; - - public UserProfileService getUserProfileService() { - return userProfileService; - } - - public void setUserProfileService(UserProfileService userProfileService) { - this.userProfileService = userProfileService; - } - - @RequestMapping(value = { "/post_search" }, method = RequestMethod.GET) - public ModelAndView welcome(HttpServletRequest request, - @ModelAttribute("postSearchBean") PostSearchBean postSearchBean) { - Map<String, Object> model = new HashMap<String, Object>(); - - ObjectMapper mapper = new ObjectMapper(); - try { - postSearchBean = new PostSearchBean(); - model.put("profileList", mapper.writeValueAsString(postSearchBean.getSearchResult())); - model.put("postSearchBean", mapper.writeValueAsString(postSearchBean)); - model.put("existingUsers", mapper.writeValueAsString(getExistingUsers())); - model.put("sortByList", mapper.writeValueAsString(getSortByList())); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "welcome: failed to write JSON" + ex.getMessage()); - } - - return new ModelAndView(getViewName(), model); - } - - @RequestMapping(value = { "/post_search_sample" }, method = RequestMethod.GET) - public void getPostSearchProfile(HttpServletRequest request, HttpServletResponse response, - @ModelAttribute("postSearchBean") PostSearchBean postSearchBean) { - Map<String, Object> model = new HashMap<String, Object>(); - - ObjectMapper mapper = new ObjectMapper(); - try { - postSearchBean = new PostSearchBean(); - model.put("profileList", mapper.writeValueAsString(postSearchBean.getSearchResult())); - model.put("postSearchBean", mapper.writeValueAsString(postSearchBean)); - model.put("existingUsers", mapper.writeValueAsString(getExistingUsers())); - model.put("sortByList", mapper.writeValueAsString(getSortByList())); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "getPostSearchProfile: failed to write JSON" + ex.getMessage()); - } - - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private HashMap getExistingUsers() { - HashMap existingUsers = new HashMap(); - - List<Profile> list = profileService.findAll(); - - if (list != null) { - Iterator<Profile> i = list.iterator(); - while (i.hasNext()) { - Profile user = i.next(); - String orgUserId = user.getOrgUserId(); - Long id = user.getId(); // id scalar - if (orgUserId != null) - existingUsers.put(orgUserId, id); - } - } - return existingUsers; - } - - @RequestMapping(value = { "/post_search/search" }, method = RequestMethod.POST) - public ModelAndView search(HttpServletRequest request, HttpServletResponse response) throws Exception { - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PostSearchBean postSearchBean = mapper.readValue(root.get("postSearchBean").toString(), - PostSearchBean.class); - - //postSearchBean.setSearchResult(loadSearchResultData(request, postSearchBean)); - List<User> users = loadSearchResultDataFromFnTableOrExt(request,postSearchBean); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(users); - JSONObject j = new JSONObject("{users: " + responseString + "}"); - - out.write(j.toString()); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "search: failed to send search result" + ex.getMessage()); - } - - return null; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static List getSortByList() { - if (sortByList == null) { - sortByList = new ArrayList(); - sortByList.add(new Lookup("Last Name", "last_name")); - sortByList.add(new Lookup("First Name", "first_name")); - sortByList.add(new Lookup("HRID", "hrid")); - sortByList.add(new Lookup("SBCID", "sbcid")); - sortByList.add(new Lookup("Organization", "org_code")); - sortByList.add(new Lookup("Email", "email")); - } // if - - return sortByList; - } // getSortByList - - private List<User> loadSearchResultDataFromFnTableOrExt(HttpServletRequest request, PostSearchBean searchCriteria) - throws Exception { - return userProfileService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(), - searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(), - searchCriteria.getNewDataSize(), UserUtils.getUserSession(request).getId().intValue()); - } - - @RequestMapping(value = { "/post_search/process" }, method = RequestMethod.POST) - public ModelAndView process(HttpServletRequest request, HttpServletResponse response) throws Exception { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - JsonNode root = mapper.readTree(request.getReader()); - PostSearchBean postSearch = mapper.readValue(root.get("postSearchBean").toString(), PostSearchBean.class); - - postSearchService.process(request, postSearch); - List<User> users = loadSearchResultDataFromFnTableOrExt(request,postSearch); - - logger.info(EELFLoggerDelegate.auditLogger, "Import new user from webphone "); - - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String userString = mapper.writeValueAsString(users); - JSONObject j = new JSONObject("{users: " + userString + ",existingUsers: " - + mapper.writeValueAsString(getExistingUsers()) + "}"); - - out.write(j.toString()); - - return null; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileController.java deleted file mode 100644 index 1fd7800f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileController.java +++ /dev/null @@ -1,349 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.RoleService; -import org.openecomp.portalsdk.core.service.UserProfileService; -import org.openecomp.portalsdk.core.web.support.AppUtils; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping("/") -public class ProfileController extends RestrictedBaseController { - - @Autowired - UserProfileService service; - @Autowired - RoleService roleService; - - String viewName; - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileController.class); - - @RequestMapping(value = { "/profile" }, method = RequestMethod.GET) - public ModelAndView profile(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - User profile = null; - Long profileId = null; - - if (request.getRequestURI().indexOf("self_profile.htm") > -1) { - profile = UserUtils.getUserSession(request); - profileId = profile.getId(); - } else { - profileId = Long.parseLong(request.getParameter("profile_id")); - profile = (User) service.getUser(request.getParameter("profile_id")); - } - - try { - model.put("stateList", mapper.writeValueAsString(getStates())); - model.put("countries", mapper.writeValueAsString(getCountries())); - model.put("timeZones", mapper.writeValueAsString(getTimeZones())); - model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles())); - model.put("profile", mapper.writeValueAsString(profile)); - model.put("profileId", mapper.writeValueAsString(profileId)); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "profile: failed to write JSON" + e.getMessage()); - } - return new ModelAndView("profile", "model", model); - } - - @RequestMapping(value = { "/self_profile" }, method = RequestMethod.GET) - public ModelAndView self_profile(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - User profile = null; - Long profileId = null; - - profile = UserUtils.getUserSession(request); - profileId = profile.getId(); - profile = (User) service.getUser(profileId.toString()); - - try { - model.put("stateList", mapper.writeValueAsString(getStates())); - model.put("countries", mapper.writeValueAsString(getCountries())); - model.put("timeZones", mapper.writeValueAsString(getTimeZones())); - model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles())); - model.put("profile", mapper.writeValueAsString(profile)); - model.put("profileId", mapper.writeValueAsString(profileId)); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "self_profile: failed to write JSON" + e.getMessage()); - } - return new ModelAndView("profile", "model", model); - } - - @RequestMapping(value = { "/get_self_profile" }, method = RequestMethod.GET) - public void getSelfProfile(HttpServletRequest request, HttpServletResponse response) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - User profile = null; - Long profileId = null; - - profile = UserUtils.getUserSession(request); - profileId = profile.getId(); - profile = (User) service.getUser(profileId.toString()); - - try { - model.put("stateList", mapper.writeValueAsString(getStates())); - model.put("countries", mapper.writeValueAsString(getCountries())); - model.put("timeZones", mapper.writeValueAsString(getTimeZones())); - model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles())); - model.put("profile", mapper.writeValueAsString(profile)); - model.put("profileId", mapper.writeValueAsString(profileId)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getSelfProfile: failed to write JSON" + e.getMessage()); - } - - } - - @RequestMapping(value = { "/get_profile" }, method = RequestMethod.GET) - public void GetUser(HttpServletRequest request, HttpServletResponse response) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - try { - User profile = null; - Long profileId = null; - if (request.getRequestURI().indexOf("self_profile.htm") > -1) { - profile = UserUtils.getUserSession(request); - profileId = profile.getId(); - } else { - profileId = Long.parseLong(request.getParameter("profile_id")); - profile = (User) service.getUser(request.getParameter("profile_id")); - } - model.put("stateList", mapper.writeValueAsString(getStates())); - model.put("countries", mapper.writeValueAsString(getCountries())); - model.put("timeZones", mapper.writeValueAsString(getTimeZones())); - model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles())); - model.put("profile", mapper.writeValueAsString(profile)); - model.put("profileId", mapper.writeValueAsString(profileId)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "GetUser: failed to write JSON" + e.getMessage()); - } - } - - @RequestMapping(value = { "/profile/saveProfile" }, method = RequestMethod.POST) - public ModelAndView saveProfile(HttpServletRequest request, HttpServletResponse response) { - logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save"); - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - User user = mapper.readValue(root.get("profile").toString(), User.class); - - String selectedCountry = mapper.readValue(root.get("selectedCountry").toString(), String.class); - String selectedState = mapper.readValue(root.get("selectedState").toString(), String.class); - String selectedTimeZone = mapper.readValue(root.get("selectedTimeZone").toString(), String.class); - - Long profileId = Long.parseLong(request.getParameter("profile_id")); - - User domainUser = (User) service.getUser(request.getParameter("profile_id")); - // user.setRoles(domainUser.getRoles()); - user.setPseudoRoles(domainUser.getPseudoRoles()); - user.setUserApps(domainUser.getUserApps()); - if (!selectedCountry.equals("")) { - user.setCountry(selectedCountry); - } - if (!selectedState.equals("")) { - user.setState(selectedState); - } - if (!selectedTimeZone.equals("")) { - user.setTimeZoneId(Long.parseLong(selectedTimeZone)); - } - service.saveUser(user); - logger.info(EELFLoggerDelegate.auditLogger, "Save user's profile for user " + profileId); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - out.write("" + profileId); - return null; - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - try { - request.setCharacterEncoding("UTF-8"); - } catch (UnsupportedEncodingException e1) { - - e1.printStackTrace(); - - } - PrintWriter out = null; - try { - out = response.getWriter(); - } catch (IOException e1) { - logger.error(EELFLoggerDelegate.errorLogger, "saveProfile: failed to get writer" + e1.getMessage()); - } - out.write(e.getMessage()); - return null; - } - } - - @RequestMapping(value = { "/profile/removeRole" }, method = RequestMethod.POST) - public ModelAndView removeRole(HttpServletRequest request, HttpServletResponse response) throws Exception { - - logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save"); - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Role role = mapper.readValue(root.get("role").toString(), Role.class); - - // Long profileId = Long.parseLong(request.getParameter("profile_id")); - - User domainUser = (User) service.getUser(request.getParameter("profile_id")); - - domainUser.removeRole(role.getId()); - - service.saveUser(domainUser); - logger.info(EELFLoggerDelegate.auditLogger, "Remove role " + role.getId() + " from user " + request.getParameter("profile_id")); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - Map<String, Object> model = new HashMap<String, Object>(); - model.put("profile", mapper.writeValueAsString(domainUser)); - JSONObject j = new JSONObject(mapper.writeValueAsString(domainUser)); - - out.write(j.toString()); - - return null; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "removeRole" + e.getMessage()); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - @RequestMapping(value = { "/profile/addNewRole" }, method = RequestMethod.POST) - public ModelAndView addNewRole(HttpServletRequest request, HttpServletResponse response) throws Exception { - - logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save" ); - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Role role = mapper.readValue(root.get("role").toString(), Role.class); - - // Long profileId = Long.parseLong(request.getParameter("profile_id")); - - User domainUser = (User) service.getUser(request.getParameter("profile_id")); - - domainUser.addRole(role); - - service.saveUser(domainUser); - logger.info(EELFLoggerDelegate.auditLogger, "Add new role " + role.getName() + " to user " + request.getParameter("profile_id")); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - Map<String, Object> model = new HashMap<String, Object>(); - model.put("profile", mapper.writeValueAsString(domainUser)); - JSONObject j = new JSONObject(mapper.writeValueAsString(domainUser)); - - out.write(j.toString()); - - return null; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "addNewRole" + e.getMessage()); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - public String getViewName() { - return viewName; - } - - public void setViewName(String viewName) { - this.viewName = viewName; - } - - @SuppressWarnings("rawtypes") - public List getStates() { - return AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD"); - } - - @SuppressWarnings("rawtypes") - public List getCountries() { - return AppUtils.getLookupList("FN_LU_COUNTRY", "COUNTRY_CD", "COUNTRY", null, "COUNTRY"); - } - - @SuppressWarnings("rawtypes") - public List getTimeZones() { - return AppUtils.getLookupList("FN_LU_TIMEZONE", "TIMEZONE_ID", "TIMEZONE_NAME", null, "TIMEZONE_NAME"); - } - - @SuppressWarnings("rawtypes") - public List getAvailableRoles() { - return roleService.getAvailableRoles(); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileSearchController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileSearchController.java deleted file mode 100644 index 42ebd41e..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileSearchController.java +++ /dev/null @@ -1,149 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.MenuData; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.FnMenuService; -import org.openecomp.portalsdk.core.service.UserProfileService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping("/") -public class ProfileSearchController extends RestrictedBaseController{ - @Autowired - UserProfileService service; - @Autowired - FnMenuService fnMenuService; - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileSearchController.class); - @RequestMapping(value = {"/profile_search" }, method = RequestMethod.GET) - public ModelAndView ProfileSearch(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - List<User> profileList =null; - logger.info(EELFLoggerDelegate.applicationLogger, "Initiating ProfileSearch in ProfileSearchController"); - try { - profileList = service.findAll(); - model.putAll(setDashboardData(request)); - model.put("profileList", mapper.writeValueAsString(profileList)); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.applicationLogger, "error while profile_search process in ProfileSearchController" + e.getMessage()); - } - return new ModelAndView(getViewName(),"model", model); - } - - @RequestMapping(value = {"/get_user" }, method = RequestMethod.GET) - public void GetUser(HttpServletRequest request, HttpServletResponse response) { - logger.info(EELFLoggerDelegate.applicationLogger, "Initiating get_user in ProfileSearchController"); - ObjectMapper mapper = new ObjectMapper(); - List<User> profileList =null; - try { - profileList = service.findAll(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(profileList)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - - } catch (Exception e) { - logger.error(EELFLoggerDelegate.applicationLogger, "error while get_user process in ProfileSearchController" + e.getMessage()); - } - } - - @RequestMapping(value = {"/get_user_pagination" }, method = RequestMethod.GET) - public void getUserPagination(HttpServletRequest request, HttpServletResponse response) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - logger.info(EELFLoggerDelegate.applicationLogger, "Initiating get_user_pagination in ProfileSearchController"); - int pageNum = Integer.parseInt(request.getParameter("pageNum")); - int viewPerPage = Integer.parseInt(request.getParameter("viewPerPage")); - List<User> profileList =null; - try { - profileList = service.findAll(); - model.put("totalPage",(int) Math.ceil((double)profileList.size() / viewPerPage)); - profileList = profileList.subList(viewPerPage*(pageNum-1)<profileList.size()?viewPerPage*(pageNum-1):profileList.size(), viewPerPage*pageNum<profileList.size()?viewPerPage*pageNum:profileList.size()); - model.put("profileList", mapper.writeValueAsString(profileList)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - - } catch (Exception e) { - logger.error(EELFLoggerDelegate.applicationLogger, "error while get_user_pagination process in ProfileSearchController" + e.getMessage()); - } - } - - - @SuppressWarnings("unchecked") - public Map<String, Object>setDashboardData(HttpServletRequest request) throws Exception{ - ObjectMapper mapper = new ObjectMapper(); - Map<String, Object> model = new HashMap<String, Object>(); - List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>(); - List<MenuData> parentList = new ArrayList<MenuData>(); - logger.info(EELFLoggerDelegate.applicationLogger, "Initiating setDashboardData in ProfileSearchController"); - HttpSession session = request.getSession(); - try{ - Set<MenuData> menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); - fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult); - }catch(Exception e){ - logger.error(EELFLoggerDelegate.applicationLogger, "error while setDashboardData process in ProfileSearchController" + e.getMessage()); - } - model.put("childItemList",mapper.writeValueAsString(childItemList)); - model.put("parentList",mapper.writeValueAsString(parentList)); - return model; - } - - @RequestMapping(value = {"/profile/toggleProfileActive" }, method = RequestMethod.GET) - public void toggleProfileActive(HttpServletRequest request, HttpServletResponse response) throws IOException { - try{ - logger.info(EELFLoggerDelegate.applicationLogger, "Initiating toggleProfileActive in ProfileSearchController"); - String userId = request.getParameter("profile_id"); - User user = (User)service.getUser(userId); - user.setActive(!user.getActive()); - service.saveUser(user); - logger.info(EELFLoggerDelegate.auditLogger, "Change active status for user " + user.getId() + " to " + user.getActive()); - ObjectMapper mapper = new ObjectMapper(); - response.setContentType("application/json"); - PrintWriter out = response.getWriter(); - out.write(mapper.writeValueAsString(user.getActive())); - }catch(Exception e){ - logger.error(EELFLoggerDelegate.applicationLogger, "error while toggleProfileActive process in ProfileSearchController" + e.getMessage()); - } - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedBaseController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedBaseController.java deleted file mode 100644 index 2b2e3426..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedBaseController.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -public class RestrictedBaseController extends FusionBaseController{ - - protected String viewName; - private String exceptionView; - @Override - public boolean isAccessible() { - return false; - } - @Override - public boolean isRESTfulCall(){ - return false; - } - protected String getViewName() { - return viewName; - } - protected void setViewName(String viewName) { - this.viewName = viewName; - } - - public String getExceptionView() { - return (exceptionView == null) ? "runtime_error_handler" : exceptionView; - } - - public void setExceptionView(String exceptionView) { - this.exceptionView = exceptionView; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedRESTfulBaseController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedRESTfulBaseController.java deleted file mode 100644 index d11c7d76..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedRESTfulBaseController.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -public class RestrictedRESTfulBaseController extends FusionBaseController{ - - protected String viewName; - private String exceptionView; - @Override - public boolean isAccessible() { - return false; - } - @Override - public boolean isRESTfulCall(){ - return true; - } - protected String getViewName() { - return viewName; - } - protected void setViewName(String viewName) { - this.viewName = viewName; - } - - public String getExceptionView() { - return (exceptionView == null) ? "runtime_error_handler" : exceptionView; - } - - public void setExceptionView(String exceptionView) { - this.exceptionView = exceptionView; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleController.java deleted file mode 100644 index 0419e2b8..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleController.java +++ /dev/null @@ -1,332 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.RoleFunction; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.RoleService; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.ServletRequestUtils; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.type.TypeFactory; - -@Controller -@RequestMapping("/") -public class RoleController extends RestrictedBaseController { - @Autowired - RoleService service; - - String viewName; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleController.class); - - @RequestMapping(value = { "/role" }, method = RequestMethod.GET) - public ModelAndView role(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - Role role = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); - logger.info("role_id" + role.getId()); - try { - model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions())); - model.put("availableRoles", mapper.writeValueAsString(service.getAvailableChildRoles(role.getId()))); - model.put("role", mapper.writeValueAsString(role)); - } catch (Exception e) { - logger.error("role: failed", e); - logger.error(EELFLoggerDelegate.errorLogger, "Unable to set the active profile" + e.getMessage()); - } - return new ModelAndView(getViewName(), model); - } - - @RequestMapping(value = { "/get_role" }, method = RequestMethod.GET) - public void getRole(HttpServletRequest request, HttpServletResponse response) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - Role role = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); - logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + role.getId()); - try { - model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions())); - model.put("availableRoles", mapper.writeValueAsString(service.getAvailableChildRoles(role.getId()))); - model.put("role", mapper.writeValueAsString(role)); - - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getRole failed" + e.getMessage()); - } - - } - - @RequestMapping(value = { "/role/saveRole" }, method = RequestMethod.POST) - public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) throws Exception { - - logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.save"); - logger.info(EELFLoggerDelegate.auditLogger, "RoleController.save"); - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Role role = mapper.readValue(root.get("role").toString(), Role.class); - - List<Role> childRoles = mapper.readValue(root.get("childRoles").toString(), - TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class)); - - List<RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(), - TypeFactory.defaultInstance().constructCollectionType(List.class, RoleFunction.class)); - - Role domainRole = null; - if (role.getId() != null) { - logger.info(EELFLoggerDelegate.auditLogger, "updating existing role " + role.getId()); - domainRole = service.getRole(role.getId()); - - domainRole.setName(role.getName()); - domainRole.setPriority(role.getPriority()); - } else { - logger.info(EELFLoggerDelegate.auditLogger, "saving as new role"); - domainRole = new Role(); - domainRole.setName(role.getName()); - domainRole.setPriority(role.getPriority()); - if (role.getChildRoles().size() > 0) { - for (Object childRole : childRoles) { - domainRole.addChildRole((Role) childRole); - } - } - if (role.getRoleFunctions().size() > 0) { - for (Object roleFunction : roleFunctions) { - domainRole.addRoleFunction((RoleFunction) roleFunction); - } - } - } - - service.saveRole(domainRole); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(domainRole); - JSONObject j = new JSONObject("{role: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed" + e.getMessage()); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - @RequestMapping(value = { "/role/removeRoleFunction" }, method = RequestMethod.POST) - public ModelAndView removeRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception { - - logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction"); - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class); - - Role domainRole = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); - logger.info(EELFLoggerDelegate.auditLogger, "Remove role function " + roleFunction.getCode() + " from role " + ServletRequestUtils.getIntParameter(request, "role_id", 0)); - - domainRole.removeRoleFunction(roleFunction.getCode()); - - service.saveRole(domainRole); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(domainRole); - JSONObject j = new JSONObject("{role: " + responseString + "}"); - out.write(j.toString()); - - return null; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed" + e.getMessage()); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - @RequestMapping(value = { "/role/addRoleFunction" }, method = RequestMethod.POST) - public ModelAndView addRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception { - - logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction"); - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class); - - Role domainRole = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); - - domainRole.addRoleFunction(roleFunction); - - service.saveRole(domainRole); - logger.info(EELFLoggerDelegate.auditLogger, "Add role function " + roleFunction.getCode() + " to role " + ServletRequestUtils.getIntParameter(request, "role_id", 0)); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(domainRole); - JSONObject j = new JSONObject("{role: " + responseString + "}"); - out.write(j.toString()); - - return null; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed" + e.getMessage()); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - @RequestMapping(value = { "/role/removeChildRole" }, method = RequestMethod.POST) - public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception { - - logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeChileRole"); - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class); - - Role domainRole = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); - - domainRole.removeChildRole(childRole.getId()); - logger.info(EELFLoggerDelegate.auditLogger, "remove child role " + childRole.getId() + " from role " + ServletRequestUtils.getIntParameter(request, "role_id", 0)); - - - service.saveRole(domainRole); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(domainRole); - JSONObject j = new JSONObject("{role: " + responseString + "}"); - out.write(j.toString()); - - return null; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "removeChildRole failed" + e.getMessage()); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - @RequestMapping(value = { "/role/addChildRole" }, method = RequestMethod.POST) - public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception { - - logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.addChileRole"); - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class); - - Role domainRole = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); - - domainRole.addChildRole(childRole); - - service.saveRole(domainRole); - logger.info(EELFLoggerDelegate.auditLogger, "Add child role " + childRole.getId() + " to role " + ServletRequestUtils.getIntParameter(request, "role_id", 0)); - - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(domainRole); - JSONObject j = new JSONObject("{role: " + responseString + "}"); - out.write(j.toString()); - - return null; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "addChildRole failed" + e.getMessage()); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - public String getViewName() { - return viewName; - } - - public void setViewName(String viewName) { - this.viewName = viewName; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleFunctionListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleFunctionListController.java deleted file mode 100644 index 3b9eed62..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleFunctionListController.java +++ /dev/null @@ -1,184 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.RoleFunction; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.RoleService; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping("/") -public class RoleFunctionListController extends RestrictedBaseController { - @Autowired - RoleService service; - - String viewName; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleFunctionListController.class); - - @RequestMapping(value = {"/role_function_list" }, method = RequestMethod.GET) - public ModelAndView welcome(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - try { - model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions())); - } catch (JsonGenerationException e) { - e.printStackTrace(); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return new ModelAndView(getViewName(),model); - } - - @RequestMapping(value = {"/get_role_functions" }, method = RequestMethod.GET) - public void getRoleFunctionList(HttpServletRequest request,HttpServletResponse response) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - try { - model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions())); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (JsonGenerationException e) { - e.printStackTrace(); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - @RequestMapping(value = {"/role_function_list/saveRoleFunction" }, method = RequestMethod.POST) - public ModelAndView saveRoleFunction(HttpServletRequest request, - HttpServletResponse response) throws Exception { - - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - RoleFunction availableRoleFunction = mapper.readValue(root.get("availableRoleFunction").toString(), RoleFunction.class); - - RoleFunction domainRoleFunction = service.getRoleFunction(availableRoleFunction.getCode()); - - //role. toggle active ind - domainRoleFunction.setName(availableRoleFunction.getName()); - domainRoleFunction.setCode(availableRoleFunction.getCode()); - - service.saveRoleFunction(domainRoleFunction); - logger.info(EELFLoggerDelegate.auditLogger, "Save role function " + domainRoleFunction.getName()); - - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(service.getRoleFunctions()); - JSONObject j = new JSONObject("{availableRoleFunctions: "+responseString+"}"); - - out.write(j.toString()); - - return null; - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - @RequestMapping(value = {"/role_function_list/removeRoleFunction" }, method = RequestMethod.POST) - public ModelAndView removeRoleFunction(HttpServletRequest request, - HttpServletResponse response) throws Exception { - - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - RoleFunction availableRoleFunction = mapper.readValue(root.get("availableRoleFunction").toString(), RoleFunction.class); - - RoleFunction domainRoleFunction = service.getRoleFunction(availableRoleFunction.getCode()); - - service.deleteRoleFunction(domainRoleFunction); - logger.info(EELFLoggerDelegate.auditLogger, "Remove role function " + domainRoleFunction.getName()); - - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(service.getRoleFunctions()); - JSONObject j = new JSONObject("{availableRoleFunctions: "+responseString+"}"); - out.write(j.toString()); - - return null; - } catch (Exception e) { - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - public String getViewName() { - return viewName; - } - public void setViewName(String viewName) { - this.viewName = viewName; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleListController.java deleted file mode 100644 index 78fbc19f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleListController.java +++ /dev/null @@ -1,179 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.RoleService; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping("/") -public class RoleListController extends RestrictedBaseController { - @Autowired - RoleService service; - String viewName; - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleListController.class); - - - @RequestMapping(value = {"/role_list" }, method = RequestMethod.GET) - public ModelAndView role(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - try { - model.put("availableRoles", mapper.writeValueAsString(service.getAvailableRoles())); - } catch (JsonGenerationException e) { - e.printStackTrace(); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return new ModelAndView(getViewName(),model); - } - - @RequestMapping(value = {"/get_roles" }, method = RequestMethod.GET) - public void getRoles(HttpServletRequest request, HttpServletResponse response) { - Map<String, Object> model = new HashMap<String, Object>(); - ObjectMapper mapper = new ObjectMapper(); - - try { - model.put("availableRoles", mapper.writeValueAsString(service.getAvailableRoles())); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (JsonGenerationException e) { - e.printStackTrace(); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - - @RequestMapping(value = {"/role_list/toggleRole" }, method = RequestMethod.POST) - public ModelAndView toggleRole(HttpServletRequest request, - HttpServletResponse response) throws Exception { - - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Role role = mapper.readValue(root.get("role").toString(), Role.class); - - Role domainRole = service.getRole(role.getId()); - //role. toggle active ind - boolean active = domainRole.getActive(); - domainRole.setActive(!active); - - service.saveRole(domainRole); - logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId()); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(service.getAvailableRoles()); - JSONObject j = new JSONObject("{availableRoles: "+responseString+"}"); - - out.write(j.toString()); - - return null; - } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - @RequestMapping(value = {"/role_list/removeRole" }, method = RequestMethod.POST) - public ModelAndView removeRole(HttpServletRequest request, - HttpServletResponse response) throws Exception { - - try { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Role role = mapper.readValue(root.get("role").toString(), Role.class); - - Role domainRole = service.getRole(role.getId()); - - service.deleteDependcyRoleRecord(role.getId()); - service.deleteRole(domainRole); - logger.info(EELFLoggerDelegate.auditLogger, "Remove role " + domainRole.getId()); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(service.getAvailableRoles()); - JSONObject j = new JSONObject("{availableRoles: "+responseString+"}"); - out.write(j.toString()); - - return null; - } catch (Exception e) { - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - return null; - } - - } - - public String getViewName() { - return viewName; - } - public void setViewName(String viewName) { - this.viewName = viewName; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/SingleSignOnController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/SingleSignOnController.java deleted file mode 100644 index 4a0fb6f7..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/SingleSignOnController.java +++ /dev/null @@ -1,232 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.openecomp.portalsdk.core.command.LoginBean; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.menu.MenuProperties; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler; -import org.openecomp.portalsdk.core.service.LoginService; -import org.openecomp.portalsdk.core.service.ProfileService; -import org.openecomp.portalsdk.core.util.CipherUtil; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.AppUtils; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.util.WebUtils; - -@Controller -@RequestMapping("/") -public class SingleSignOnController extends UnRestrictedBaseController { - - private static final String EP_SERVICE = "EPService"; - private static final String USER_ID = "UserId"; - public static final String DEFAULT_SUCCESS_VIEW = "welcome"; - public static final String DEFAULT_FAILURE_VIEW = "login"; - public static final String ERROR_MESSAGE_KEY = "error"; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SingleSignOnController.class); - - @Autowired - ProfileService service; - @Autowired - private LoginService loginService; - String viewName; - private String welcomeView; - - public String getWelcomeView() { - return welcomeView; - } - - public void setWelcomeView(String welcomeView) { - this.welcomeView = welcomeView; - } - - /** - * Handles requests directed to the single sign-on page by the session - * timeout interceptor. - * - * @param request - * @return Redirect to an appropriate address - * @throws Exception - */ - @RequestMapping(value = { "/single_signon.htm" }, method = RequestMethod.GET) - public ModelAndView singleSignOnLogin(HttpServletRequest request) throws Exception { - - Map<String, String> model = new HashMap<String, String>(); - HashMap<String, String> additionalParamsMap = new HashMap<String, String>(); - LoginBean commandBean = new LoginBean(); - - // SessionTimeoutInterceptor sets these parameters - String forwardURL = URLDecoder.decode(request.getParameter("forwardURL"), "UTF-8"); - String redirectToPortal = request.getParameter("redirectToPortal"); - - if (isLoginCookieExist(request) && redirectToPortal == null) { - HttpSession session = null; - session = AppUtils.getSession(request); - User user = UserUtils.getUserSession(request); - if (session == null || user == null) { - String orgUserId = ""; - orgUserId = getUserIdFromCookie(request); - commandBean.setUserid(orgUserId); - commandBean = getLoginService().findUser(commandBean, - (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), - additionalParamsMap); - if (commandBean.getUser() == null) { - String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) - ? commandBean.getLoginErrorMessage() - : SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND; - model.put(ERROR_MESSAGE_KEY, SystemProperties.getProperty(loginErrorMessage)); - final String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL) - + "?noUserError=Yes"; - logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: user is null, redirect URL is {}", - redirectUrl); - return new ModelAndView("redirect:" + redirectUrl); - } else { - // store the user's information in the session - - UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), - commandBean.getBusinessDirectMenu(), ""); - initateSessionMgtHandler(request); - logger.debug(EELFLoggerDelegate.debugLogger, - "singleSignOnLogin: create new user session for expired user {}; user {} exists in the system", - commandBean.getUser().getOrgUserId()); - return new ModelAndView("redirect:" + forwardURL); - } - } // user is null or session is null - else { - // both user and session are non-null. - logger.info(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: redirecting to the forwardURL {}", - forwardURL); - return new ModelAndView("redirect:" + forwardURL); - } - - } else { - /* - * Login cookie not found, or redirect-to-portal parameter was found. - * - * Redirect the user to the portal with a suitable return URL. The - * forwardURL parameter that arrives as a parameter is a partial - * (not absolute) request path for a page in the application. The - * challenge here is to compute the correct absolute path for the - * original request so the portal can redirect the user back to the - * right place. - */ - String returnToAppUrl = null; - if (SystemProperties.containsProperty(SystemProperties.APP_BASE_URL)) { - // New feature: - // application can publish a base URL in system.properties - String appUrl = SystemProperties.getProperty(SystemProperties.APP_BASE_URL); - returnToAppUrl = appUrl + (appUrl.endsWith("/") ? "" : "/") + forwardURL; - logger.debug(EELFLoggerDelegate.debugLogger, - "singleSignOnLogin: using app base URL {} and redirectURL {}", appUrl, returnToAppUrl); - } else { - // Be backward compatible with applications that don't need this - // feature. - // This is the controller for the single_signon.htm page, so the - // replace - // should always find the specified token. - returnToAppUrl = ((HttpServletRequest) request).getRequestURL().toString().replace("single_signon.htm", - forwardURL); - logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: computed redirectURL {}", returnToAppUrl); - } - final String encodedReturnToAppUrl = URLEncoder.encode(returnToAppUrl, "UTF-8"); - // Also send the application's UEB key so Portal can block URL - // reflection attacks. - final String uebAppKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); - final String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); - final String portalUrl = url.substring(0, url.lastIndexOf('/')) + "/processSingleSignOn"; - final String redirectUrl = portalUrl + "?uebAppKey=" + uebAppKey + "&redirectUrl=" + encodedReturnToAppUrl; - logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: portal-bound redirect URL is {}", - redirectUrl); - return new ModelAndView("redirect:" + redirectUrl); - } - } - - protected void initateSessionMgtHandler(HttpServletRequest request) { - String portalJSessionId = getPortalJSessionId(request); - String jSessionId = getJessionId(request); - PortalTimeoutHandler.sessionCreated(portalJSessionId, jSessionId, AppUtils.getSession(request)); - } - - public boolean isLoginCookieExist(HttpServletRequest request) { - Cookie ep = WebUtils.getCookie(request, EP_SERVICE); - return (ep != null); - } - - public static String getUserIdFromCookie(HttpServletRequest request) throws Exception { - String userId = ""; - Cookie[] cookies = request.getCookies(); - Cookie userIdcookie = null; - if (cookies != null) - for (Cookie cookie : cookies) - if (cookie.getName().equals(USER_ID)) - userIdcookie = cookie; - if(userIdcookie!=null){ - userId = CipherUtil.decrypt(userIdcookie.getValue(), - SystemProperties.getProperty(SystemProperties.Decryption_Key)); - } - return userId; - - } - - public String getPortalJSessionId(HttpServletRequest request) { - Cookie ep = WebUtils.getCookie(request, EP_SERVICE); - return ep.getValue(); - - } - - public String getJessionId(HttpServletRequest request) { - return request.getSession().getId(); - } - - public String getViewName() { - return viewName; - } - - public void setViewName(String viewName) { - this.viewName = viewName; - } - - public LoginService getLoginService() { - return loginService; - } - - public void setLoginService(LoginService loginService) { - this.loginService = loginService; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UnRestrictedBaseController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UnRestrictedBaseController.java deleted file mode 100644 index 78bf4c51..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UnRestrictedBaseController.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -public class UnRestrictedBaseController extends FusionBaseController{ - protected String viewName; - - @Override - public boolean isAccessible() { - return true; - } - @Override - public boolean isRESTfulCall(){ - return false; - } - protected String getViewName() { - return viewName; - } - - protected void setViewName(String viewName) { - this.viewName = viewName; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UsageListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UsageListController.java deleted file mode 100644 index c5616575..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UsageListController.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.controller; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.openecomp.portalsdk.core.command.UserRowBean; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.UsageUtils; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -@Controller -@RequestMapping("/") -public class UsageListController extends RestrictedBaseController { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UsageListController.class); - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @RequestMapping(value = { "/usage_list" }, method = RequestMethod.GET) - public ModelAndView usageList(HttpServletRequest request) { - Map<String, Object> model = new HashMap<String, Object>(); - - HttpSession httpSession = request.getSession(); - HashMap activeUsers = (HashMap) httpSession.getServletContext().getAttribute("activeUsers"); - if (activeUsers.size() == 0) { - activeUsers.put(httpSession.getId(), httpSession); - httpSession.getServletContext().setAttribute("activeUsers", activeUsers); - } - ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers); - JSONArray ja = new JSONArray(); - try { - for (UserRowBean userRowBean : rows) { - JSONObject jo = new JSONObject(); - jo.put("id", userRowBean.getId()); - jo.put("lastName", userRowBean.getLastName()); - jo.put("email", userRowBean.getEmail()); - jo.put("lastAccess", userRowBean.getLastAccess()); - jo.put("remaining", userRowBean.getRemaining()); - jo.put("sessionId", userRowBean.getSessionId()); - if (!(httpSession.getId().equals(userRowBean.getSessionId()))) { - jo.put("delete", "yes"); - } else { - jo.put("delete", "no"); - } - ja.put(jo); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "usageList 1: failed" + e.getMessage()); - } - - model.put("model", ja); - - return new ModelAndView(getViewName(), model); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @RequestMapping(value = { "/get_usage_list" }, method = RequestMethod.GET) - public void usageList(HttpServletRequest request, HttpServletResponse response) { - HttpSession httpSession = request.getSession(); - HashMap activeUsers = (HashMap) httpSession.getServletContext().getAttribute("activeUsers"); - if (activeUsers.size() == 0) { - activeUsers.put(httpSession.getId(), httpSession); - httpSession.getServletContext().setAttribute("activeUsers", activeUsers); - } - ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers); - JSONArray ja = new JSONArray(); - try { - for (UserRowBean userRowBean : rows) { - JSONObject jo = new JSONObject(); - jo.put("id", userRowBean.getId()); - jo.put("lastName", userRowBean.getLastName()); - jo.put("email", userRowBean.getEmail()); - jo.put("lastAccess", userRowBean.getLastAccess()); - jo.put("remaining", userRowBean.getRemaining()); - jo.put("sessionId", userRowBean.getSessionId()); - if (!(httpSession.getId().equals(userRowBean.getSessionId()))) { - jo.put("delete", "yes"); - } else { - jo.put("delete", "no"); - } - ja.put(jo); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "usageList 2: failed" + e.getMessage()); - } - JsonMessage msg; - try { - msg = new JsonMessage(ja.toString()); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "usageList 3: failed" + e.getMessage()); - } - - } - - @SuppressWarnings("rawtypes") - @RequestMapping(value = { "/usage_list/removeSession" }, method = RequestMethod.GET) - public void removeSession(HttpServletRequest request, HttpServletResponse response) throws Exception { - HashMap activeUsers = (HashMap) request.getSession().getServletContext().getAttribute("activeUsers"); - UserRowBean data = new UserRowBean(); - data.setSessionId(request.getParameter("deleteSessionId")); - UsageUtils.getActiveUsersAfterDelete(activeUsers, data); - - HttpSession httpSession = request.getSession(); - ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers); - JSONArray ja = new JSONArray(); - try { - for (UserRowBean userRowBean : rows) { - JSONObject jo = new JSONObject(); - jo.put("id", userRowBean.getId()); - jo.put("lastName", userRowBean.getLastName()); - jo.put("email", userRowBean.getEmail()); - jo.put("lastAccess", userRowBean.getLastAccess()); - jo.put("remaining", userRowBean.getRemaining()); - jo.put("sessionId", userRowBean.getSessionId()); - if (!(httpSession.getId().equals(userRowBean.getSessionId()))) { - jo.put("delete", "yes"); - } else { - jo.put("delete", "no"); - } - ja.put(jo); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "removeSession: failed" + e.getMessage()); - } - - response.setContentType("application/json"); - PrintWriter out = response.getWriter(); - out.write(ja.toString()); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/AbstractDao.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/AbstractDao.java deleted file mode 100644 index 0b274068..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/AbstractDao.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.dao; -import java.io.Serializable; -import java.lang.reflect.ParameterizedType; - -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; - -public abstract class AbstractDao<PK extends Serializable, T> { - - private final Class<T> persistentClass; - - @SuppressWarnings("unchecked") - public AbstractDao(){ - this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]; - } - - @Autowired - private SessionFactory sessionFactory; - - protected Session getSession(){ - return sessionFactory.getCurrentSession(); - } - - @SuppressWarnings("unchecked") - public T getByKey(PK key) { - return (T) getSession().get(persistentClass, key); - } - - public void persist(T entity) { - getSession().persist(entity); - } - - public void delete(T entity) { - getSession().delete(entity); - } - - protected Criteria createEntityCriteria(){ - return getSession().createCriteria(persistentClass); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDao.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDao.java deleted file mode 100644 index 0094072c..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDao.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.dao; - -import java.util.List; - -import org.openecomp.portalsdk.core.domain.Profile; - -public interface ProfileDao { - List<Profile> findAll(); - Profile getProfile(int id); -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDaoImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDaoImpl.java deleted file mode 100644 index 8d8d0d6e..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/ProfileDaoImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.dao; - -import java.util.List; - -import org.hibernate.Criteria; -import org.hibernate.criterion.Restrictions; -import org.openecomp.portalsdk.core.domain.Profile; -import org.springframework.stereotype.Repository; - -@Repository("profileDao") -public class ProfileDaoImpl extends AbstractDao<Integer, Profile> implements ProfileDao{ - - - public List<Profile> findAll() { - Criteria crit = getSession().createCriteria(Profile.class); - @SuppressWarnings("unchecked") - List<Profile> p = crit.list(); - - return p; - } - - - public Profile getProfile(int id) { - Criteria crit = getSession().createCriteria(Profile.class); - crit.add(Restrictions.eq("id", id)); - Profile profile = (Profile) crit.uniqueResult(); - - return profile; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/hibernate/ModelOperationsCommon.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/hibernate/ModelOperationsCommon.java deleted file mode 100644 index cd9e644b..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/hibernate/ModelOperationsCommon.java +++ /dev/null @@ -1,453 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.dao.hibernate; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.hibernate.Criteria; -import org.hibernate.FetchMode; -import org.hibernate.Query; -import org.hibernate.SQLQuery; -import org.hibernate.Session; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.ProjectionList; -import org.hibernate.type.LongType; -import org.openecomp.portalsdk.core.dao.support.FusionDao; -import org.openecomp.portalsdk.core.domain.Lookup; -import org.openecomp.portalsdk.core.domain.support.DomainVo; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.SystemProperties; - -public abstract class ModelOperationsCommon extends FusionDao { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ModelOperationsCommon.class); - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public List _getList(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex, String orderBy) { - List list = null; - String className = domainClass.getName(); - - Session session = getSessionFactory().getCurrentSession(); - - logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records" - + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "") - + "..."); - - - if (filterClause != null && filterClause.length() > 0) { - logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause); - - } - - list = session.createQuery("from " + className + Utilities.nvl(filterClause, "") - + ((orderBy != null) ? " order by " + orderBy : "")).list(); - list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list; - - if (orderBy == null && list != null) { - Collections.sort(list); - } - - return list; - } - - public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, - List<Order> orderByList) { - return _getList(domainClass, projectionsList, restrictionsList, orderByList, null); - } - - public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, - List<Order> orderByList, HashMap<String, FetchMode> fetchModeMap) { - - Session session = getSessionFactory().getCurrentSession(); - - Criteria criteria = session.createCriteria(domainClass); - - if (projectionsList != null) { - criteria.setProjection(projectionsList); - } - - if (restrictionsList != null && !restrictionsList.isEmpty()) { - for (Criterion criterion : restrictionsList) - criteria.add(criterion); - } - - if (orderByList != null && !orderByList.isEmpty()) { - for (Order order : orderByList) - criteria.addOrder(order); - } - - if (fetchModeMap != null) { - Iterator<String> itr = fetchModeMap.keySet().iterator(); - String key = null; - while (itr.hasNext()) { - key = itr.next(); - criteria.setFetchMode(key, fetchModeMap.get(key)); - } - - } - return criteria.list(); - } - - @SuppressWarnings("rawtypes") - public DomainVo _get(Class domainClass, Serializable id) { - DomainVo vo = null; - - Session session = getSessionFactory().getCurrentSession(); - - logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString()); - - - vo = (DomainVo) session.get(domainClass, id); - - if (vo == null) { - try { - vo = (DomainVo) domainClass.newInstance(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed while instantiating a class of " + domainClass.getName() + e.getMessage()); - - } - } - - return vo; - } - - @SuppressWarnings("rawtypes") - public List _getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, - HashMap additionalParams) { - logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list..."); - - List list = null; - String dbOrderByCol = dbOrderBy; - - Session session = getSessionFactory().getCurrentSession(); - - // default the orderBy if null; - if (Utilities.nvl(dbOrderBy).length() == 0) { - dbOrderByCol = dbLabelCol; - dbOrderBy = dbLabelCol; - } else { - if (dbOrderBy.lastIndexOf(" ") > -1) { - dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" ")); - } - } - - StringBuffer sql = new StringBuffer(); - - sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ") - .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ") - .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ") - .append(dbOrderBy); - - try { - list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list(); - } catch (Exception e) { - list = null; - logger.info(EELFLoggerDelegate.debugLogger, "The results for the lookup list query [" + sql + "] were empty."); - } - - return list; - } // getLookupList - - /* This method is used to execute SQL queries */ - @SuppressWarnings("rawtypes") - protected final List _executeSQLQuery(String sql, Class domainClass) { - return _executeSQLQuery(sql, domainClass, null, null); - } - - /* This method is used to execute SQL queries with paging */ - @SuppressWarnings("rawtypes") - protected final List _executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex) { - Session session = getSessionFactory().getCurrentSession(); - - SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass); - - if (fromIndex != null && toIndex != null) { - query.setFirstResult(fromIndex.intValue()); - int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; - query.setMaxResults(pageSize); - } - - return query.list(); - } - - /* This method is used to execute HQL queries */ - @SuppressWarnings("rawtypes") - protected final List _executeQuery(String sql) { - return _executeQuery(sql, null, null); - } - - /* This method is used to execute HQL queries with paging */ - @SuppressWarnings("rawtypes") - protected final List _executeQuery(String sql, Integer fromIndex, Integer toIndex) { - Session session = getSessionFactory().getCurrentSession(); - - Query query = session.createQuery(sql); - - if (fromIndex != null && toIndex != null) { - query.setFirstResult(fromIndex.intValue()); - int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; - query.setMaxResults(pageSize); - } - - return query.list(); - } - - /* - * This method can be used to execute both HQL or SQL named queries. The - * distinction will come in the hbm.xml mapping file defining the named - * query. Named HQL queries use the <query> tag while named SQL queries use - * the <sql-query> tag. - */ - @SuppressWarnings("rawtypes") - protected final List _executeNamedQuery(String queryName, Map params) { - return _executeNamedQuery(queryName, params, null, null); - } - - /* - * This method can be used to execute both HQL or SQL named queries with - * paging. The distinction will come in the hbm.xml mapping file defining - * the named query. Named HQL queries use the <query> tag while named SQL - * queries use the <sql-query> tag. - */ - @SuppressWarnings("rawtypes") - protected final List _executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex) { - Session session = getSessionFactory().getCurrentSession(); - Query query = session.getNamedQuery(queryName); - bindQueryParameters(query, params); - if (fromIndex != null && toIndex != null) { - query.setFirstResult(fromIndex.intValue()); - int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; - query.setMaxResults(pageSize); - } - return query.list(); - } - - // RAPTOR ZK - /* - * This method can be used to execute both HQL or SQL named queries with - * paging. The distinction will come in the hbm.xml mapping file defining - * the named query. Named HQL queries use the <query> tag while named SQL - * queries use the <sql-query> tag. - */ - @SuppressWarnings("rawtypes") - protected final List _executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) { - Session session = getSessionFactory().getCurrentSession(); - Query query = session.getNamedQuery(queryName); - String queryStr = query.getQueryString(); - StringBuffer modifiedSql = new StringBuffer(" select count(*) as countRows from (" + queryStr + " ) al "); - if (whereClause != null && whereClause.length() > 0) - modifiedSql.append("where " + whereClause); - // SQLQuery sqlQuery = session.createSQLQuery(" select count(*) as - // {reportSearch.countRows} from ("+ modifiedSql.toString()+")"); - SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString()); - bindQueryParameters(sqlQuery, params); - sqlQuery.addScalar("countRows", LongType.INSTANCE); - // sqlQuery.addEntity("reportSearch", entity); - // sqlQuery.setResultTransformer(new - // AliasToBeanResultTransformer(SearchCount.class)); - return sqlQuery.list(); - - } - - /* - * This method can be used to execute both HQL or SQL named queries with - * paging. The distinction will come in the hbm.xml mapping file defining - * the named query. Named HQL queries use the <query> tag while named SQL - * queries use the <sql-query> tag. It is modified to test ZK filter. - */ - @SuppressWarnings("rawtypes") - protected final List _executeNamedQuery(Class entity, String queryName, String whereClause, Map params, - Integer fromIndex, Integer toIndex) { - Session session = getSessionFactory().getCurrentSession(); - Query query = session.getNamedQuery(queryName); - bindQueryParameters(query, params); - String queryStr = query.getQueryString(); - StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al "); - if (whereClause != null && whereClause.length() > 0) - modifiedSql.append("where " + whereClause); - - SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString()); - bindQueryParameters(sqlQuery, params); - sqlQuery.addEntity("reportSearch", entity); - - if (fromIndex != null && toIndex != null) { - sqlQuery.setFirstResult(fromIndex.intValue()); - int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; - sqlQuery.setMaxResults(pageSize); - } - return sqlQuery.list(); - } - - /* - * This method can be used to execute both HQL or SQL named queries with - * paging. The distinction will come in the hbm.xml mapping file defining - * the named query. Named HQL queries use the <query> tag while named SQL - * queries use the <sql-query> tag. - */ - @SuppressWarnings("rawtypes") - protected final List _executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, - boolean asc, Integer fromIndex, Integer toIndex) { - Session session = getSessionFactory().getCurrentSession(); - Query query = session.getNamedQuery(queryName); - bindQueryParameters(query, params); - String queryStr = query.getQueryString(); - queryStr = String.format(queryStr, _orderBy, asc ? "ASC" : "DESC"); - SQLQuery sqlQuery = session.createSQLQuery(queryStr); - bindQueryParameters(sqlQuery, params); - sqlQuery.addEntity("reportSearch", entity); - if (fromIndex != null && toIndex != null) { - sqlQuery.setFirstResult(fromIndex.intValue()); - int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; - sqlQuery.setMaxResults(pageSize); - } - return sqlQuery.list(); - } - - // Where Clause - @SuppressWarnings("rawtypes") - protected final List _executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, - String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) { - Session session = getSessionFactory().getCurrentSession(); - Query query = session.getNamedQuery(queryName); - bindQueryParameters(query, params); - String queryStr = query.getQueryString(); - queryStr = String.format(queryStr, _orderBy, asc ? "ASC" : "DESC"); - // StringBuffer modifiedSql = new StringBuffer(queryStr ); - StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al "); - // modifiedSql.insert(queryStr.lastIndexOf("order by"), " " + - // whereClause + " "); - if (whereClause != null && whereClause.length() > 0) - modifiedSql.append("where " + whereClause); - SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString()); - bindQueryParameters(sqlQuery, params); - sqlQuery.addEntity("reportSearch", entity); - if (fromIndex != null && toIndex != null) { - sqlQuery.setFirstResult(fromIndex.intValue()); - int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; - sqlQuery.setMaxResults(pageSize); - } - return sqlQuery.list(); - } - - // RAPTOR ZK END - - /* Processes custom Insert/Update/Delete SQL statements */ - protected final int _executeUpdateQuery(String sql) throws Exception { - Session session = getSessionFactory().getCurrentSession(); - Query query = session.createSQLQuery(sql); - return query.executeUpdate(); - } - - /* Processes Insert/Update/Delete Named SQL statements */ - @SuppressWarnings("rawtypes") - protected final int _executeNamedUpdateQuery(String queryName, Map params) throws Exception { - Session session = getSessionFactory().getCurrentSession(); - Query query = session.getNamedQuery(queryName); - bindQueryParameters(query, params); - return query.executeUpdate(); - } - - protected final void _update(DomainVo vo, Integer userId) { - _update(vo, ((userId != null) ? userId.intValue() : 0)); - } - - protected final void _update(DomainVo vo, int userId) { - Date timestamp = new Date(); - - Session session = getSessionFactory().getCurrentSession(); - - if (vo.getId() == null || vo.getId().intValue() == 0) { // add new - vo.setCreated(timestamp); - vo.setModified(timestamp); - - if (userId != 0 - && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) { - vo.setCreatedId(new Long(userId)); - vo.setModifiedId(new Long(userId)); - } - } else { // update existing - vo.setModified(timestamp); - - if (userId != 0 - && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) { - vo.setModifiedId(new Long(userId)); - } - } - - session.saveOrUpdate(vo); - } - - protected final void _remove(DomainVo vo) { - Session session = getSessionFactory().getCurrentSession(); - session.delete(vo); - } - - @SuppressWarnings("rawtypes") - protected final int _remove(Class domainClass, String whereClause) { - int rowsAffected = 0; - - Session session = getSessionFactory().getCurrentSession(); - - StringBuffer sql = new StringBuffer("delete from "); - - sql.append(domainClass.getName()).append(" where ").append(whereClause); - - rowsAffected = session.createQuery(sql.toString()).executeUpdate(); - - return rowsAffected; - } - - protected final void _flush() { - Session session = getSessionFactory().getCurrentSession(); - session.flush(); - } - - @SuppressWarnings("rawtypes") - private void bindQueryParameters(Query query, Map params) { - if (params != null) { - for (Iterator i = params.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); - - Object parameterValue = entry.getValue(); - - if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) { - query.setParameter((String) entry.getKey(), parameterValue); - } else { - if (parameterValue instanceof Collection) { - query.setParameterList((String) entry.getKey(), (Collection) parameterValue); - } else { - if (parameterValue instanceof Object[]) { - query.setParameterList((String) entry.getKey(), (Object[]) parameterValue); - } - } - } - } - } - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/support/FusionDao.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/support/FusionDao.java deleted file mode 100644 index 75b3c80b..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/dao/support/FusionDao.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.dao.support; - -import org.hibernate.SessionFactory; -import org.openecomp.portalsdk.core.FusionObject; - -public class FusionDao implements FusionObject { - private SessionFactory sessionFactory; - - public void setSessionFactory(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; - } - - public SessionFactory getSessionFactory() { - return this.sessionFactory; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/App.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/App.java deleted file mode 100644 index 6e8e6c80..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/App.java +++ /dev/null @@ -1,206 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -/** - * Represents a row in the FN_APP table in the EP_SDK database. (A nearly - * identical table is defined in Portal database.) - * - * @version 1.0 - */ -public class App extends DomainVo { - - private static final long serialVersionUID = 3465979916929796990L; - - // superclass defines Id - private String name; // app_name - private String imageUrl; // app_image_url - private String description; // app_description - private String notes; // app_notes - private String url; // app_url - private String alternateUrl; // app_alternate_url - private String restEndpoint; // app_rest_endpoint - private String mlAppName; // ml_app_name - private String mlAppAdminId; // ml_app_admin_id; - private String motsId; // mots_id - private String appPassword; // app_password - private String open; - private String enabled; - private byte[] thumbnail; - private String username; // app_username - private String uebKey; // ueb_key - private String uebSecret; // ueb_secret - private String uebTopicName; // ueb_topic_name - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAppPassword() { - return appPassword; - } - - public void setAppPassword(String appPassword) { - this.appPassword = appPassword; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getImageUrl() { - return imageUrl; - } - - public void setImageUrl(String imageUrl) { - this.imageUrl = imageUrl; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getNotes() { - return notes; - } - - public void setNotes(String notes) { - this.notes = notes; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getAlternateUrl() { - return alternateUrl; - } - - public void setAlternateUrl(String alternateUrl) { - this.alternateUrl = alternateUrl; - } - - public String getRestEndpoint() { - return restEndpoint; - } - - public void setRestEndpoint(String restEndpoint) { - this.restEndpoint = restEndpoint; - } - - public String getMlAppName() { - return mlAppName; - } - - public void setMlAppName(String mlAppName) { - this.mlAppName = mlAppName; - } - - public String getMlAppAdminId() { - return mlAppAdminId; - } - - public void setMlAppAdminId(String mlAppAdminId) { - this.mlAppAdminId = mlAppAdminId; - } - - public String getMotsId() { - return motsId; - } - - public void setMotsId(String motsId) { - this.motsId = motsId; - } - - public String getOpen() { - return open; - } - - public void setOpen(String open) { - this.open = open; - } - - public String getEnabled() { - return enabled; - } - - public void setEnabled(String enabled) { - this.enabled = enabled; - } - - public byte[] getThumbnail() { - return this.thumbnail; - } - - public void setThumbnail(byte[] thumbnail) { - this.thumbnail = thumbnail; - } - - public String getUebKey() { - return uebKey; - } - - public void setUebKey(String uebKey) { - this.uebKey = uebKey; - } - - public String getUebSecret() { - return uebSecret; - } - - public void setUebSecret(String uebSecret) { - this.uebSecret = uebSecret; - } - - public String getUebTopicName() { - return uebTopicName; - } - - public void setUebTopicName(String uebTopicName) { - this.uebTopicName = uebTopicName; - } - - /** - * Answers true if the objects have the same ID. - */ - public int compareTo(Object obj) { - Long c1 = getId(); - Long c2 = ((App) obj).getId(); - return c1.compareTo(c2); - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/AuditLog.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/AuditLog.java deleted file mode 100644 index f861232f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/AuditLog.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import java.util.Date; - -import org.openecomp.portalsdk.core.domain.support.DomainVo; -public class AuditLog extends DomainVo { - - /** - * - */ - private static final long serialVersionUID = 1L; - public static final String CD_ACTIVITY_LOGIN = "login"; - public static final String CD_ACTIVITY_LOGOUT = "logout"; - public static final String CD_ACTIVITY_MOBILE_LOGIN = "mobile_login"; - public static final String CD_ACTIVITY_MOBILE_LOGOUT = "mobile_logout"; - - /*-------Profile activities -----------*/ - public static final String CD_ACTIVITY_ROLE_ADD = "add_role"; - public static final String CD_ACTIVITY_ROLE_REMOVE = "remove_role"; - public static final String CD_ACTIVITY_CHILD_ROLE_ADD = "add_child_role"; - public static final String CD_ACTIVITY_CHILD_ROLE_REMOVE = "remove_child_role"; - public static final String CD_ACTIVITY_ROLE_ADD_FUNCTION = "add_role_function"; - public static final String CD_ACTIVITY_ROLE_REMOVE_FUNCTION = "remove_role_function"; - public static final String CD_ACTIVITY_USER_ROLE_ADD = "add_user_role"; - public static final String CD_ACTIVITY_USER_ROLE_REMOVE = "remove_user_role"; - - - private String activityCode; - private String affectedRecordId; - private String comments; - - 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; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/BroadcastMessage.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/BroadcastMessage.java deleted file mode 100644 index e005df41..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/BroadcastMessage.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import java.util.Date; - -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -public class BroadcastMessage extends DomainVo{ - /** - * - */ - private static final long serialVersionUID = 1L; - - public BroadcastMessage() { - } - - public static final String ID_MESSAGE_LOCATION_LOGIN = "10"; - public static final String ID_MESSAGE_LOCATION_WELCOME = "20"; - - private String messageText; - private Integer locationId; - private Date startDate; - private Date endDate; - private Integer sortOrder; - private Boolean active; - private String siteCd; - - public Boolean getActive() { - return active; - } - - public Date getEndDate() { - return endDate; - } - - public Integer getLocationId() { - return locationId; - } - - public String getMessageText() { - return messageText; - } - - public Integer getSortOrder() { - return sortOrder; - } - - public Date getStartDate() { - return startDate; - } - - public String getSiteCd() { - return siteCd; - } - - - public void setActive(Boolean active) { - this.active = active; - } - - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - - public void setLocationId(Integer locationId) { - this.locationId = locationId; - } - - public void setMessageText(String messageText) { - this.messageText = messageText; - } - - public void setSortOrder(Integer sortOrder) { - this.sortOrder = sortOrder; - } - - public void setStartDate(Date startDate) { - this.startDate = startDate; - } - - public void setSiteCd(String siteCd) { - this.siteCd = siteCd; - } - - - public int compareTo(Object obj){ - Integer c1 = getLocationId(); - Integer c2 = ((BroadcastMessage)obj).getLocationId(); - - if (c1.compareTo(c2) == 0) { - c1 = getSortOrder(); - c2 = ((BroadcastMessage)obj).getSortOrder(); - - if (c1.compareTo(c2) == 0) { - Long c3 = getId(); - Long c4 = ((BroadcastMessage)obj).getId(); - - return c3.compareTo(c4); - } - } - - return c1.compareTo(c2); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/DomainVo.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/DomainVo.java deleted file mode 100644 index 9d173996..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/DomainVo.java +++ /dev/null @@ -1,177 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -/* Super class from which all data objects descend - * - * Per Sunder T on 3 June 2016: - * - * Yes, we need to get rid of domain.DomainVO and fold all the references to the support.DomainVO. - */ -@SuppressWarnings("rawtypes") -@Deprecated -public class DomainVo extends FusionVo implements Serializable, Cloneable, Comparable { - - /** - * - */ - private static final long serialVersionUID = 1L; - protected Long id; - protected Date created; - protected Date modified; - protected Long createdId; - protected Long modifiedId; - protected Long rowNum; - - protected Serializable auditUserId; - - Set auditTrail = null; - - public DomainVo() { - } - - public void setId(Long i) { - id = i; - } - - public void setCreated(Date created) { - this.created = created; - } - - public void setModified(Date modified) { - this.modified = modified; - } - - public void setCreatedId(Long createdId) { - this.createdId = createdId; - } - - public void setModifiedId(Long modifiedId) { - this.modifiedId = modifiedId; - } - - public void setAuditUserId(Serializable auditUserId) { - this.auditUserId = auditUserId; - } - - public void setRowNum(Long rowNum) { - this.rowNum = rowNum; - } - - public void setAuditTrail(Set auditTrail) { - this.auditTrail = auditTrail; - } - - public Long getId() { - return id; - } - - public Date getCreated() { - return created; - } - - public Date getModified() { - return modified; - } - - public Long getCreatedId() { - return createdId; - } - - public Long getModifiedId() { - return modifiedId; - } - - public Serializable getAuditUserId() { - return auditUserId; - } - - public Long getRowNum() { - return rowNum; - } - - public Set getAuditTrail() { - return auditTrail; - } - - @SuppressWarnings("unchecked") - public void addAuditTrailLog(AuditLog auditLog) { - if (getAuditTrail() == null) { - setAuditTrail(new HashSet()); - } - - getAuditTrail().add(auditLog); - } - - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - public Object copy() { - return copy(false); - } - - public Object copy(boolean isIdNull) { - // let's create a "copy" of the object using serialization - ByteArrayOutputStream baos = null; - ByteArrayInputStream bais = null; - ObjectOutputStream oos = null; - ObjectInputStream ois = null; - - DomainVo newVo = null; - - try { - - baos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(baos); - oos.writeObject(this); - - bais = new ByteArrayInputStream(baos.toByteArray()); - ois = new ObjectInputStream(bais); - newVo = (DomainVo) ois.readObject(); - - if (isIdNull) { - newVo.setId(null); - } - - } catch (Exception e) { - e.printStackTrace(); - } - - return newVo; - } - - public int compareTo(Object obj) { - Long c1 = getId(); - Long c2 = ((DomainVo) obj).getId(); - - return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/FnMenu.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/FnMenu.java deleted file mode 100644 index e2c1f46d..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/FnMenu.java +++ /dev/null @@ -1,142 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - - -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -/** - * <p>RoleFunction.java</p> - * - * <p>Represents a role function data object.</p> - * - * @version 1.0 - */ -public class FnMenu extends DomainVo { - /** - * - */ - private static final long serialVersionUID = 1L; - - public FnMenu() {} - - private Integer menuId; - private String label; - private Integer parentId; - private String action; - private String functionCd; - private Integer sortOrder; - private String servlet; - private String queryString; - private String externalUrl; - private String target; - private String active; - private String separator; - private String imageSrc; - private String menuSetCode; - - public Integer getMenuId() { - return menuId; - } - public void setMenuId(Integer menuId) { - this.menuId = menuId; - } - public String getLabel() { - return label; - } - public void setLabel(String label) { - this.label = label; - } - public Integer getParentId() { - return parentId; - } - public void setParentId(Integer parentId) { - this.parentId = parentId; - } - public String getAction() { - return action; - } - public void setAction(String action) { - this.action = action; - } - public String getFunctionCd() { - return functionCd; - } - public void setFunctionCd(String functionCd) { - this.functionCd = functionCd; - } - public Integer getSortOrder() { - return sortOrder; - } - public void setSortOrder(Integer sortOrder) { - this.sortOrder = sortOrder; - } - public String getServlet() { - return servlet; - } - public void setServlet(String servlet) { - this.servlet = servlet; - } - public String getQueryString() { - return queryString; - } - public void setQueryString(String queryString) { - this.queryString = queryString; - } - public String getExternalUrl() { - return externalUrl; - } - public void setExternalUrl(String externalUrl) { - this.externalUrl = externalUrl; - } - public String getTarget() { - return target; - } - public void setTarget(String target) { - this.target = target; - } - public String getActive() { - return active; - } - public void setActive(String active) { - this.active = active; - } - public String getSeparator() { - return separator; - } - public void setSeparator(String separator) { - this.separator = separator; - } - public String getImageSrc() { - return imageSrc; - } - public void setImageSrc(String imageSrc) { - this.imageSrc = imageSrc; - } - public String getMenuSetCode() { - return menuSetCode; - } - public void setMenuSetCode(String menuSetCode) { - this.menuSetCode = menuSetCode; - } - - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/FusionVo.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/FusionVo.java deleted file mode 100644 index dc1b8d4c..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/FusionVo.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import org.openecomp.portalsdk.core.FusionObject; - -public class FusionVo implements FusionObject { - public FusionVo() { - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LoginBean.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LoginBean.java deleted file mode 100644 index 52c6d00e..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LoginBean.java +++ /dev/null @@ -1,187 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import java.util.Set; - -import org.openecomp.portalsdk.core.domain.support.FusionCommand; - -@SuppressWarnings("rawtypes") -public class LoginBean extends FusionCommand { - - private String loginId; - private String loginPwd; - private String hrid; - private String orgUserId; - private String siteAccess; - private String loginErrorMessage; - - private User user; - private Set menu; - private Set businessDirectMenu; - - /** - * getLoginId - * - * @return String - */ - public String getLoginId() { - return loginId; - } - - /** - * getLoginPwd - * - * @return String - */ - public String getLoginPwd() { - return loginPwd; - } - - /** - * getMenu - * - * @return Set - */ - public Set getMenu() { - return menu; - } - - /** - * getUser - * - * @return User - */ - public User getUser() { - return user; - } - - /** - * getHrid - * - * @return String - */ - public String getHrid() { - return hrid; - } - - /** - * getSiteAccess - * - * @return String - */ - public String getSiteAccess() { - return siteAccess; - } - - /** - * getBusinessDirectMenu - * - * @return Set - */ - public Set getBusinessDirectMenu() { - return businessDirectMenu; - } - - /** - * getLoginErrorMessage - * - * @return String - */ - public String getLoginErrorMessage() { - return loginErrorMessage; - } - - public String getOrgUserId() { - return orgUserId; - } - - /** - * setLoginId - * - * @param loginId String - */ - public void setLoginId(String loginId) { - this.loginId = loginId; - } - - /** - * setLoginPwd - * - * @param loginPwd String - */ - public void setLoginPwd(String loginPwd) { - this.loginPwd = loginPwd; - } - - public void setMenu(Set menu) { - this.menu = menu; - } - - /** - * setUser - * - * @param user User - */ - public void setUser(User user) { - this.user = user; - } - - /** - * setHrid - * - * @param hrid String - */ - public void setHrid(String hrid) { - this.hrid = hrid; - } - - /** - * setSiteAccess - * - * @param siteAccess String - */ - public void setSiteAccess(String siteAccess) { - this.siteAccess = siteAccess; - } - - /** - * setBusinessDirectMenu - * - * @param businessDirectMenu Set - */ - public void setBusinessDirectMenu(Set businessDirectMenu) { - this.businessDirectMenu = businessDirectMenu; - } - - /** - * setLoginErrorMessage - * - * @param loginErrorMessage String - */ - public void setLoginErrorMessage(String loginErrorMessage) { - this.loginErrorMessage = loginErrorMessage; - } - - public void setOrgUserId(String orgUserId) { - this.orgUserId = orgUserId; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Lookup.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Lookup.java deleted file mode 100644 index a71bdfc1..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Lookup.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import java.io.Serializable; - -import org.openecomp.portalsdk.core.domain.support.NameValueId; - -public class Lookup extends FusionVo implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private NameValueId nameValueId = new NameValueId(); - - public Lookup() {} - - public Lookup(String label, String value) { - this(); - setLabel(label); - setValue(value); - } - - public String getValue() { - return getNameValueId().getVal(); - } - - public String getLabel() { - return getNameValueId().getLab(); - } - - public void setValue(String value) { - getNameValueId().setVal(value); - } - - public void setLabel(String label) { - getNameValueId().setLab(label); - } - - public NameValueId getNameValueId() { - return nameValueId; - } - - public void setNameValueId(NameValueId nameValueId) { - this.nameValueId = nameValueId; - } - - // required by ZK for to set the selectedItems of Listboxes (used heavily for <select>-style drop-downs) - public int hashCode() { - int hash = getValue().hashCode(); - hash = hash + getLabel().hashCode(); - - return hash; - } - - public boolean equals( Object obj ) { - boolean equivalent = false; - - Lookup lookup = (Lookup)obj; - if( lookup.getValue().equals(getValue()) && lookup.getLabel().equals(getLabel())) { - equivalent = true; - } - - return equivalent; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LuCountry.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LuCountry.java deleted file mode 100644 index 946df58a..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LuCountry.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -/** - * <p>luCountry.java</p> - * - * <p>Represents a country data object.</p> - * - * @version 1.0 - */ -public class LuCountry extends DomainVo{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - LuCountry() {} - - public String getCountry() { - return country; - } - - public String getAbbr() { - return abbr; - } - - public void setCountry(String country) { - this.country = country; - } - - public void setAbbr(String abbr) { - this.abbr = abbr; - } - - - public String getFullName() { - return fullName; - } - - public void setFullName(String fullName) { - this.fullName = fullName; - } - - public String getWebphoneCountryLabel() { - return webphoneCountryLabel; - } - - public void setWebphoneCountryLabel(String webphoneCountryLabel) { - this.webphoneCountryLabel = webphoneCountryLabel; - } - - public int compareTo(Object obj){ - String c1 = getCountry(); - String c2 = ((LuCountry)obj).getCountry(); - - return c1.compareTo(c2); - } - - - private String abbr; - private String country; - private String fullName; - private String webphoneCountryLabel; - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LuState.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LuState.java deleted file mode 100644 index 283ab011..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LuState.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -/** - * <p>State.java</p> - * - * <p>Represents a state data object.</p> - * - * @version 1.0 - */ -public class LuState extends DomainVo { - - /** - * - */ - private static final long serialVersionUID = 1L; - - LuState() {} - - public String getState() { - return state; - } - - public String getAbbr() { - return abbr; - } - - public void setState(String state) { - this.state = state; - } - - public void setAbbr(String abbr) { - this.abbr = abbr; - } - - - public int compareTo(Object obj){ - String c1 = getState(); - String c2 = ((LuState)obj).getState(); - - return c1.compareTo(c2); - } - - - private String abbr; - private String state; - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LuTimeZone.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LuTimeZone.java deleted file mode 100644 index e1a7a474..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/LuTimeZone.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -/** - * <p>LuTimeZone.java</p> - * - * <p>Represents a LuTimeZone data object.</p> - * - * @version 1.0 - */ -public class LuTimeZone extends DomainVo { - - /** - * - */ - private static final long serialVersionUID = 1L; - - LuTimeZone() {} - - public String getName() { - return name; - } - - public String getValue() { - return value; - } - - public void setName(String name) { - this.name = name; - } - - public void setValue(String value) { - this.value = value; - } - - - public Long getTimezoneId() { - return timezoneId; - } - - public void setTimezoneId(Long timezoneId) { - this.timezoneId = timezoneId; - } - - public int compareTo(Object obj){ - Long c1 = getId(); - Long c2 = ((LuTimeZone)obj).getId(); - - return c1.compareTo(c2); - } - - - private String name; - private Long timezoneId; - private String value; - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Menu.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Menu.java deleted file mode 100644 index 6d57e6d0..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Menu.java +++ /dev/null @@ -1,160 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - - -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -public class Menu extends DomainVo { - /** - * - */ - private static final long serialVersionUID = 1L; - - public Menu() {} - - public String getAction() { - return action; - } - - public boolean isActive() { - return active; - } - - public String getExternalUrl() { - return externalUrl; - } - - public String getFunctionCd() { - return functionCd; - } - - public String getLabel() { - return label; - } - - public String getMenuLevel() { - return menuLevel; - } - - public Long getParentId() { - return parentId; - } - - public String getQueryString() { - return queryString; - } - - public String getServlet() { - return servlet; - } - - public Short getSortOrder() { - return sortOrder; - } - - public String getTarget() { - return target; - } - - public String getMenuSetCode() { - return menuSetCode; - } - - public void setAction(String action) { - this.action = action; - } - - public void setActive(boolean active) { - this.active = active; - } - - public void setExternalUrl(String externalUrl) { - this.externalUrl = externalUrl; - } - - public void setFunctionCd(String functionCd) { - this.functionCd = functionCd; - } - - public void setLabel(String label) { - this.label = label; - } - - public void setMenuLevel(String menuLevel) { - this.menuLevel = menuLevel; - } - - public void setParentId(Long parentId) { - this.parentId = parentId; - } - - public void setQueryString(String queryString) { - this.queryString = queryString; - } - - public void setServlet(String servlet) { - this.servlet = servlet; - } - - public void setSortOrder(Short sortOrder) { - this.sortOrder = sortOrder; - } - - public void setTarget(String target) { - this.target = target; - } - - public void setMenuSetCode(String menuSetCode) { - this.menuSetCode = menuSetCode; - } - - public boolean isSeparator() { - return separator; - } - - public void setSeparator(boolean separator) { - this.separator = separator; - } - - public String getImageSrc() { - return imageSrc; - } - - public void setImageSrc(String imageSrc) { - this.imageSrc = imageSrc; - } - - private String menuLevel; - private String label; - private Long parentId; - private String action; - private String functionCd; - private Short sortOrder; - private String servlet; - private String queryString; - private String externalUrl; - private String target; - private boolean active; - private String menuSetCode; - private boolean separator; - private String imageSrc; - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/MenuData.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/MenuData.java deleted file mode 100644 index a5758b80..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/MenuData.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import java.util.Set; -import java.util.TreeSet; - -@SuppressWarnings("rawtypes") -public class MenuData extends Menu { - - /** - * - */ - private static final long serialVersionUID = 1L; - private MenuData parentMenu; - private Set childMenus = new TreeSet(); - - public MenuData() {} - - public Set getChildMenus() { - return childMenus; - } - - public MenuData getParentMenu() { - return parentMenu; - } - - public void setChildMenus(Set childMenus) { - this.childMenus = childMenus; - } - - public void setParentMenu(MenuData parentMenu) { - this.parentMenu = parentMenu; - } - - public int compareTo(Object obj){ - - Short c1 = getSortOrder(); - Short c2 = ((MenuData)obj).getSortOrder(); - - return (c1 == null || c2 == null) ? 1 : ((c1.compareTo(c2) == 0) ? 1 : c1.compareTo(c2)); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Profile.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Profile.java deleted file mode 100644 index b5592021..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Profile.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -public class Profile extends DomainVo{ - - private static final long serialVersionUID = 3409056457412656883L; - - private Long id; - private String first_name; - private String last_name; - private String email; - private String orgManagerUserId; - private String active_yn; - private String orgUserId; - public Profile() {} - - - public Long getId() { - return id; - } - - - public void setId(Long id) { - this.id = id; - } - - - public String getFirst_name() { - return first_name; - } - - public void setFirst_name(String first_name) { - this.first_name = first_name; - } - - public String getLast_name() { - return last_name; - } - - public void setLast_name(String last_name) { - this.last_name = last_name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getOrgManagerUserId() { - return orgManagerUserId; - } - - public void setOrgManagerUserId(String orgManagerUserId) { - this.orgManagerUserId = orgManagerUserId; - } - - public String getActive_yn() { - return active_yn; - } - - public void setActive_yn(String active_yn) { - this.active_yn = active_yn; - } - - public String getOrgUserId() { - return orgUserId; - } - - public void setOrgUserId(String orgUserId) { - this.orgUserId = orgUserId; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Role.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Role.java deleted file mode 100644 index 474bbb95..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/Role.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - - -import java.util.Iterator; -import java.util.Set; -import java.util.TreeSet; - -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -/** - * <p>Role.java</p> - * <p>Represents a role data object.</p> - * - * @version 1.0 - */ -@SuppressWarnings("rawtypes") -public class Role extends DomainVo { - - /** - * - */ - private static final long serialVersionUID = 1L; - private String name; - private boolean active; - private Integer priority; - - private Set roleFunctions = new TreeSet(); - - private Set childRoles = new TreeSet(); - @JsonIgnore - private Set parentRoles = new TreeSet(); - - public Role() {} - - public String getName() { - return name; - } - - public boolean getActive() { - return active; - } - - public Set getRoleFunctions() { - return roleFunctions; - } - - public Integer getPriority() { - return priority; - } - - public Set getChildRoles() { - return childRoles; - } - - public Set getParentRoles() { - return parentRoles; - } - - public void setName(String name) { - this.name = name; - } - - public void setActive(boolean active) { - this.active = active; - } - - public void setRoleFunctions(Set roleFunctions) { - this.roleFunctions = roleFunctions; - } - - public void setPriority(Integer priority) { - this.priority = priority; - } - - public void setChildRoles(Set childRoles) { - this.childRoles = childRoles; - } - - public void setParentRoles(Set parentRoles) { - this.parentRoles = parentRoles; - } - - @SuppressWarnings("unchecked") - public void addRoleFunction(RoleFunction roleFunction) { - this.roleFunctions.add(roleFunction); - } - - @SuppressWarnings("unchecked") - public void addChildRole(Role role) { - this.childRoles.add(role); - } - - @SuppressWarnings("unchecked") - public void addParentRole(Role role) { - this.parentRoles.add(role); - } - - public String getEditUrl() { - return "/role.htm?role_id=" + getId(); - } - - public String getToggleActiveImage() { - return "/static/fusion/images/" + (getActive() ? "active.png" : "inactive.png" ); - } - - public String getToggleActiveAltText() { - return getActive() ? "Click to Deactivate Role" : "Click to Activate Role"; - } - - public void removeChildRole(Long roleId) { - Iterator i = this.childRoles.iterator(); - - while (i.hasNext()) { - Role childRole = (Role)i.next(); - if (childRole.getId().equals(roleId)) { - this.childRoles.remove(childRole); - break; - } - } - } - - public void removeParentRole(Long roleId) { - Iterator i = this.parentRoles.iterator(); - - while (i.hasNext()) { - Role parentRole = (Role)i.next(); - if (parentRole.getId().equals(roleId)) { - this.parentRoles.remove(parentRole); - break; - } - } - } - - public void removeRoleFunction(String roleFunctionCd) { - Iterator i = this.roleFunctions.iterator(); - - while (i.hasNext()) { - RoleFunction roleFunction = (RoleFunction)i.next(); - if (roleFunction.getCode().equals(roleFunctionCd)) { - this.roleFunctions.remove(roleFunction); - break; - } - } - } - - public int compareTo(Object obj){ - String c1 = getName(); - String c2 = ((Role)obj).getName(); - - return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/RoleFunction.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/RoleFunction.java deleted file mode 100644 index c0387fda..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/RoleFunction.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - - -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -/** - * <p>RoleFunction.java</p> - * - * <p>Represents a role function data object.</p> - * - * @version 1.0 - */ -public class RoleFunction extends DomainVo { - /** - * - */ - private static final long serialVersionUID = 1L; - public RoleFunction() {} - - public String getName() { - return name; - } - - public String getCode() { - return code; - } - - public void setName(String name) { - this.name = name; - } - - public void setCode(String code) { - this.code = code; - } - - public String getEditUrl() { - return "/role_function.htm?role_function_id=" + getCode(); - } - - public int compareTo(Object obj){ - String c1 = getName(); - String c2 = ((RoleFunction)obj).getName(); - - return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); - } - - private String code; - private String name; - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessible.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessible.java deleted file mode 100644 index 53edefe4..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessible.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import java.io.Serializable; - -public class UrlsAccessible extends FusionVo implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private UrlsAccessibleKey urlsAccessibleKey = new UrlsAccessibleKey(); - - public UrlsAccessible() {} - - public UrlsAccessible(String url, String functionCd) { - this(); - setUrl(url); - setFunctionCd(functionCd); - } - - public String getUrl() { - return getUrlsAccessibleKey().getUrl(); - } - - public String getFunctionCd() { - return getUrlsAccessibleKey().getFunctionCd(); - } - - public void setUrl(String url) { - getUrlsAccessibleKey().setUrl(url); - } - - public void setFunctionCd(String functionCd) { - getUrlsAccessibleKey().setFunctionCd(functionCd); - } - - public UrlsAccessibleKey getUrlsAccessibleKey() { - return urlsAccessibleKey; - } - - public void setUrlsAccessibleKey(UrlsAccessibleKey urlsAccessibleKey) { - this.urlsAccessibleKey = urlsAccessibleKey; - } - - // required by ZK for to set the selectedItems of Listboxes (used heavily for <select>-style drop-downs) - public int hashCode() { - int hash = getUrl().hashCode(); - hash = hash + getFunctionCd().hashCode(); - - return hash; - } - - public boolean equals( Object obj ) { - boolean equivalent = false; - - UrlsAccessible lookup = (UrlsAccessible)obj; - if( lookup.getUrl().equals(getUrl()) && lookup.getFunctionCd().equals(getFunctionCd())) { - equivalent = true; - } - - return equivalent; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessibleKey.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessibleKey.java deleted file mode 100644 index f1cec496..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UrlsAccessibleKey.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -import java.io.Serializable; - - -public class UrlsAccessibleKey implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private String url; - private String functionCd; - - public UrlsAccessibleKey() { - } - - public UrlsAccessibleKey(String url, String functionCd) { - setUrl(url); - setFunctionCd(functionCd); - } - - - public String getUrl() { - return url; - } - - - public String getFunctionCd() { - return functionCd; - } - - - public void setUrl(String url) { - this.url = url; - } - - - public void setFunctionCd(String functionCd) { - this.functionCd = functionCd; - } - - - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (o == null) { - return false; - } - - if (!(o instanceof UrlsAccessibleKey)) { - return false; - } - - final UrlsAccessibleKey key = (UrlsAccessibleKey)o; - - if (getFunctionCd().equals(key.getFunctionCd()) & getUrl().equals(key.getUrl())) { - return true; - } - - return false; - } - - - public int hashCode() { - return getUrl().hashCode() + getFunctionCd().hashCode(); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/User.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/User.java deleted file mode 100644 index e6c4a178..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/User.java +++ /dev/null @@ -1,585 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - - -import java.util.Date; -import java.util.Iterator; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -/** - * <p>User.java</p> - * - * <p>Represents a user data object.</p> - * - * @version 1.0 - */ -@SuppressWarnings("rawtypes") -public class User extends DomainVo { - - /** - * - */ - private static final long serialVersionUID = 1L; - private Long orgId; - private Long managerId; - private String firstName; - private String middleInitial; - private String lastName; - private String phone; - private String fax; - private String cellular; - private String email; - private Long addressId; - private String alertMethodCd; - private String hrid; - private String orgUserId; - private String orgCode; - private String address1; - private String address2; - private String city; - private String state; - private String zipCode; - private String country; - private String orgManagerUserId; - private String locationClli; - private String businessCountryCode; - private String businessCountryName; - private String businessUnit; - private String businessUnitName; - private String department; - private String departmentName; - private String companyCode; - private String company; - private String zipCodeSuffix; - private String jobTitle; - private String commandChain; - private String siloStatus; - private String costCenter; - private String financialLocCode; - - - - private String loginId; - private String loginPwd; - private Date lastLoginDate; - private boolean active; - private boolean internal; - private Long selectedProfileId; - private Long timeZoneId; - private boolean online; - private String chatId; - - private Set userApps = new TreeSet(); - - private Set pseudoRoles = new TreeSet(); - - - public User() {} - - public Long getAddressId() { - return addressId; - } - - public String getAlertMethodCd() { - return alertMethodCd; - } - - public String getCellular() { - return cellular; - } - - public String getEmail() { - return email; - } - - public String getFax() { - return fax; - } - - public String getFirstName() { - return firstName; - } - - public String getHrid() { - return hrid; - } - - public Date getLastLoginDate() { - return lastLoginDate; - } - - public String getLastName() { - return lastName; - } - - public String getFullName() { - return getFirstName() + " " + getLastName(); - } - - public String getLoginId() { - return loginId; - } - - public String getLoginPwd() { - return loginPwd; - } - - public Long getManagerId() { - return managerId; - } - - public String getMiddleInitial() { - return middleInitial; - } - - public String getOrgCode() { - return orgCode; - } - - public Long getOrgId() { - return orgId; - } - - public String getPhone() { - return phone; - } - - public String getOrgUserId() { - return orgUserId; - } - - public boolean getActive() { - return active; - } - - public boolean getInternal() { - return internal; - } - - public String getAddress1() { - return address1; - } - - public String getAddress2() { - return address2; - } - - public String getCity() { - return city; - } - - public String getCountry() { - return country; - } - - public String getState() { - return state; - } - - public String getZipCode() { - return zipCode; - } - - public String getBusinessCountryCode() { - return businessCountryCode; - } - - public String getCommandChain() { - return commandChain; - } - - public String getCompany() { - return company; - } - - public String getCompanyCode() { - return companyCode; - } - - public String getDepartment() { - return department; - } - - public String getJobTitle() { - return jobTitle; - } - - public String getLocationClli() { - return locationClli; - } - - public String getOrgManagerUserId() { - return orgManagerUserId; - } - - public String getZipCodeSuffix() { - return zipCodeSuffix; - } - - public String getBusinessCountryName() { - return businessCountryName; - } - - public Set getPseudoRoles() { - return pseudoRoles; - } - - public Long getSelectedProfileId() { - return selectedProfileId; - } - - public void setAddressId(Long addressId) { - this.addressId = addressId; - } - - public void setAlertMethodCd(String alertMethodCd) { - this.alertMethodCd = alertMethodCd; - } - - public void setCellular(String cellular) { - this.cellular = cellular; - } - - public void setEmail(String email) { - this.email = email; - } - - public void setFax(String fax) { - this.fax = fax; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public void setHrid(String hrid) { - this.hrid = hrid; - } - - public void setLastLoginDate(Date lastLoginDate) { - this.lastLoginDate = lastLoginDate; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public void setLoginId(String loginId) { - this.loginId = loginId; - } - - public void setLoginPwd(String loginPwd) { - this.loginPwd = loginPwd; - } - - public void setManagerId(Long managerId) { - this.managerId = managerId; - } - - public void setMiddleInitial(String middleInitial) { - this.middleInitial = middleInitial; - } - - public void setOrgCode(String orgCode) { - this.orgCode = orgCode; - } - - public void setOrgId(Long orgId) { - this.orgId = orgId; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public void setOrgUserId(String orgUserId) { - this.orgUserId = orgUserId; - } - - public void setActive(boolean active) { - this.active = active; - } - - public void setInternal(boolean internal) { - this.internal = internal; - } - - public void setAddress1(String address1) { - this.address1 = address1; - } - - public void setAddress2(String address2) { - this.address2 = address2; - } - - public void setCity(String city) { - this.city = city; - } - - public void setCountry(String country) { - this.country = country; - } - - public void setState(String state) { - this.state = state; - } - - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } - - public void setBusinessCountryCode(String businessCountryCode) { - this.businessCountryCode = businessCountryCode; - } - - public void setCommandChain(String commandChain) { - this.commandChain = commandChain; - } - - public void setCompany(String company) { - this.company = company; - } - - public void setCompanyCode(String companyCode) { - this.companyCode = companyCode; - } - - public void setDepartment(String department) { - this.department = department; - } - - public void setJobTitle(String jobTitle) { - this.jobTitle = jobTitle; - } - - public void setLocationClli(String locationClli) { - this.locationClli = locationClli; - } - - public void setOrgManagerUserId(String orgManagerUserId) { - this.orgManagerUserId = orgManagerUserId; - } - - public void setZipCodeSuffix(String zipCodeSuffix) { - this.zipCodeSuffix = zipCodeSuffix; - } - - public void setBusinessCountryName(String businessCountryName) { - this.businessCountryName = businessCountryName; - } - - public void setPseudoRoles(Set pseudoRoles) { - this.pseudoRoles = pseudoRoles; - } - - public void setSelectedProfileId(Long selectedProfileId) { - this.selectedProfileId = selectedProfileId; - } - - public Long getTimeZoneId() { - return timeZoneId; - } - - public void setTimeZoneId(Long timeZoneId) { - this.timeZoneId = timeZoneId; - } - - public String getBusinessUnit() { - return businessUnit; - } - - public void setBusinessUnit(String businessUnit) { - this.businessUnit = businessUnit; - } - - public String getSiloStatus() { - return siloStatus; - } - - public void setSiloStatus(String siloStatus) { - this.siloStatus = siloStatus; - } - - public String getCostCenter() { - return costCenter; - } - - public void setCostCenter(String costCenter) { - this.costCenter = costCenter; - } - - public String getFinancialLocCode() { - return financialLocCode; - } - - public void setFinancialLocCode(String financialLocCode) { - this.financialLocCode = financialLocCode; - } - - public String getBusinessUnitName() { - return businessUnitName; - } - - public void setBusinessUnitName(String businessUnitName) { - this.businessUnitName = businessUnitName; - } - - public String getDepartmentName() { - return departmentName; - } - - public void setDepartmentName(String departmentName) { - this.departmentName = departmentName; - } - - public int compareTo(Object obj){ - User user = (User)obj; - - String c1 = getLastName() + getFirstName() + getMiddleInitial(); - String c2 = user.getLastName() + user.getFirstName() + user.getMiddleInitial(); - - return c1.compareTo(c2); - } - - public boolean isOnline() { - return online; - } - - public void setOnline(boolean online) { - this.online = online; - } - - public String getChatId() { - return chatId; - } - - public void setChatId(String chatId) { - this.chatId = chatId; - } - - public Set getUserApps() { - return userApps; - } - - public void setUserApps(Set userApps) { - this.userApps = userApps; - } - - @SuppressWarnings("unchecked") - public void addAppRoles(App app, SortedSet<Role> roles) { - if(roles!=null){ - //add all - Set userApps = new TreeSet(); - Iterator itr = roles.iterator(); - while(itr.hasNext()){ - Role role = (Role) itr.next(); - UserApp userApp = new UserApp(); - userApp.setUserId(this.id); - userApp.setApp(app); - userApp.setRole(role); - userApps.add(userApp); - } - setUserApps(userApps); - } else { - //remove all - this.userApps.clear(); - } - - - } - - @SuppressWarnings("unchecked") - public SortedSet<Role> getAppRoles(App app) { - SortedSet<Role> roles = new TreeSet(); - Set apps = getUserApps(); - Iterator appsItr = apps.iterator(); - UserApp userApp = null; - //getting default app - while(appsItr.hasNext()){ - UserApp tempUserApp = (UserApp)appsItr.next(); - if(tempUserApp.getApp().getId().equals(app.getId())){ - userApp = tempUserApp; - roles.add(userApp.getRole()); - } - } - return roles; - } - - public SortedSet<Role> getRoles() { - App app = new App(); - app.setId(new Long(1)); - app.setName("Default"); - return getAppRoles(app); - } - - public UserApp getDefaultUserApp(){ - Set apps = getUserApps(); - Iterator appsItr = apps.iterator(); - UserApp userApp = null; - //getting default app - while(appsItr.hasNext()){ - UserApp tempApp = (UserApp)appsItr.next(); - if(tempApp.equals(new Long(1))){ - userApp = tempApp; - break; - } - } - return userApp; - } - - public void setRoles(SortedSet<Role> roles) { - App app = new App(); - app.setId(new Long(1)); - app.setName("Default"); - addAppRoles(app,roles); - } - - public void removeRole(Long roleId) { - Set apps = getUserApps(); - Iterator appsItr = apps.iterator(); - //getting default app - while(appsItr.hasNext()){ - UserApp tempUserApp = (UserApp)appsItr.next(); - if(tempUserApp.getRole().getId().equals(roleId)){ - appsItr.remove(); - } - } - - } - - @SuppressWarnings("unchecked") - public void addRole(Role role){ - if(role!=null){ - SortedSet<Role> roles = getRoles(); - if(roles==null){ - roles = new TreeSet(); - } - roles.add(role); - setRoles(roles); - } - - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UserApp.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UserApp.java deleted file mode 100644 index 5c2c383f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UserApp.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -// Generated Aug 27, 2014 5:51:36 PM by Hibernate Tools 3.4.0.CR1 - -/** - * FnUserRole generated by hbm2java - */ -@SuppressWarnings("rawtypes") -public class UserApp implements java.io.Serializable, Comparable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private Long userId; - private App app; - private Role role; - private Short priority; - - public UserApp() { - } - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - - public App getApp() { - return app; - } - - public void setApp(App app) { - this.app = app; - } - - public Role getRole() { - return role; - } - - public void setRole(Role role) { - this.role = role; - } - - public Short getPriority() { - return this.priority; - } - - public void setPriority(Short priority) { - this.priority = priority; - } - - public boolean equals(Object other) { - if ((this == other)) - return true; - if ((other == null)) - return false; - if (!(other instanceof UserApp)) - return false; - UserApp castOther = (UserApp) other; - - return (this.getUserId().equals(castOther.getUserId())) - && (this.getApp().getId().equals(castOther.getApp().getId())) - && (this.getRole().getId().equals(castOther.getRole().getId())) - && ((this.priority==null && castOther.getPriority()==null) || this.getPriority().equals(castOther.getPriority())); - } - - public int hashCode() { - int result = 17; - - result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue()); - result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue()); - result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue()); - result = 37 * result + (int) (this.priority==null ? 0 : this.priority); - return result; - } - - public int compareTo(Object other){ - UserApp castOther = (UserApp) other; - - Long c1 = (this.getUserId()==null ? 0 : this.getUserId()) + (this.getApp()==null||this.getApp().getId()==null ? 0 : this.getApp().getId()) + (this.getRole()==null||this.getRole().getId()==null ? 0 : this.getRole().getId()) + (this.priority==null ? 0 : this.priority); - Long c2 = (castOther.getUserId()==null ? 0 : castOther.getUserId()) + (castOther.getApp()==null||castOther.getApp().getId()==null ? 0 : castOther.getApp().getId()) + (castOther.getRole()==null||castOther.getRole().getId()==null ? 0 : castOther.getRole().getId()) + (castOther.priority==null ? 0 : castOther.priority); - - return c1.compareTo(c2); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UserAppId.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UserAppId.java deleted file mode 100644 index 9458b90a..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/UserAppId.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain; - -// Generated Aug 27, 2014 5:51:36 PM by Hibernate Tools 3.4.0.CR1 - -/** - * FnUserRoleId generated by hbm2java - */ -public class UserAppId implements java.io.Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private Long userId; - private App app; - private Role role; - - public UserAppId() { - super(); - } - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - - public App getApp() { - return app; - } - - public void setApp(App app) { - this.app = app; - } - - public Role getRole() { - return role; - } - - public void setRole(Role role) { - this.role = role; - } - - public boolean equals(Object other) { - if ((this == other)) - return true; - if ((other == null)) - return false; - if (!(other instanceof UserAppId)) - return false; - UserAppId castOther = (UserAppId) other; - - return (this.getUserId() == castOther.getUserId()) - && (this.getApp().getId() == castOther.getApp().getId()) - && (this.getRole().getId() == castOther.getRole().getId()); - } - - public int hashCode() { - int result = 17; - - result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue()); - result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue()); - result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue()); - return result; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/sessionmgt/TimeoutVO.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/sessionmgt/TimeoutVO.java deleted file mode 100644 index 57e474c2..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/sessionmgt/TimeoutVO.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.sessionmgt; - -public class TimeoutVO implements Comparable<TimeoutVO>{ - - private String jSessionId; - private Long sessionTimOutMilliSec; - - public TimeoutVO(){ - - } - - public TimeoutVO(String _jSessionId, Long _sessionTimOutMilliSec) { - setjSessionId(_jSessionId); - setSessionTimOutMilliSec(_sessionTimOutMilliSec); - - } - - public String getjSessionId() { - return jSessionId; - } - - public void setjSessionId(String jSessionId) { - this.jSessionId = jSessionId; - } - - public Long getSessionTimOutMilliSec() { - return sessionTimOutMilliSec; - } - - public void setSessionTimOutMilliSec(Long sessionTimOutMilliSec) { - this.sessionTimOutMilliSec = sessionTimOutMilliSec; - } - - @Override - public int compareTo(TimeoutVO o) { - return sessionTimOutMilliSec.compareTo(o.sessionTimOutMilliSec); - } - - - - - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Attribute.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Attribute.java deleted file mode 100644 index a78d7bfa..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Attribute.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -public class Attribute { - public double width; - public double top; - public double left; - public String name; - public double height; - - public double getWidth() { - return width; - } - public void setWidth(double width) { - this.width = width; - } - public double getTop() { - return top; - } - public void setTop(double top) { - this.top = top; - } - public double getLeft() { - return left; - } - public void setLeft(double left) { - this.left = left; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public double getHeight() { - return height; - } - public void setHeight(double height) { - this.height = height; - } - - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/CollaborateList.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/CollaborateList.java deleted file mode 100644 index eaeab84d..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/CollaborateList.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -import java.io.Serializable; -import java.util.HashSet; - -public class CollaborateList implements Serializable { - - private static final long serialVersionUID = -4104440747626736243L; - private HashSet<String> userNameList = new HashSet<String>(); - private static CollaborateList userListData = new CollaborateList(); - private CollaborateList(){} - - public static CollaborateList getInstance(){ - return userListData; - } - - public HashSet<String> getAllUserName(){ - return userNameList; - } - - public static void addUserName(String name){ - final HashSet<String> allUserName = CollaborateList.getInstance().getAllUserName(); - if(allUserName.contains(name)){ - //System.out.println("cannot add this user"); - }else{ - allUserName.add(name); - } - } - - public static void delUserName(String name){ - final HashSet<String> allUserName = CollaborateList.getInstance().getAllUserName(); - allUserName.remove((String) name); - } - - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Container.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Container.java deleted file mode 100644 index 7d52af40..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Container.java +++ /dev/null @@ -1,331 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -import java.util.List; -import java.util.Map; - -public class Container { - - String id; - - public String name; - - Size size; - - Position p; - - public Map<String,Container> containerRowCol; - - public Map<String,Element> elementRowCol; - - int numOfRows; - - int numOfCols; - - double sum = 0; - - double interEleWd; - - double interEleH; - - double interEleToContainerWd; - - double interEleToContainerH; - - double interEleToInnerContainerWd; - - double interEleToInnerContainerH; - - public double top; - - public double left; - - public double height; - - public double width; - - public String visibilityType; - - - - - - public Container(String id, String name, int numOfRows, int numOfCols, double interEleWd, double interEleH, - double interEleToContainerWd, double interEleToContainerH, double interEleToInnerContainerWd, - double interEleToInnerContainerH) { - - this.id = id; - this.name = name; - this.numOfRows = numOfRows; - this.numOfCols = numOfCols; - this.interEleWd = interEleWd; - this.interEleH = interEleH; - this.interEleToContainerWd = interEleToContainerWd; - this.interEleToContainerH = interEleToContainerH; - this.interEleToInnerContainerWd = interEleToInnerContainerWd; - this.interEleToInnerContainerH = interEleToInnerContainerH; - - } - - - public List<Container> innerCList; - - public List<Element> elementList; - - public Container() { - - } - - - - public Map<String, Container> getContainerRowCol() { - return containerRowCol; - } - - - - - public Map<String, Element> getElementRowCol() { - return elementRowCol; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - public void setInnerContainer(Map<String,Container> innerCon) { - containerRowCol = innerCon; - } - - public void setElements(Map<String,Element> innerE) { - elementRowCol = innerE; - } - - - public Position getP() { - return p; - } - - public void setP(Position p) { - this.p = p; - } - - - public void setTop(double top) { - this.top = top; - } - - - public void setLeft(double left) { - this.left = left; - } - - - public void setHeight(double height) { - this.height = height; - } - - - public void setWidth(double width) { - this.width = width; - } - - - public void setInnerCList(List<Container> innerCList) { - this.innerCList = innerCList; - } - - - - public void setElementList(List<Element> elementList) { - this.elementList = elementList; - } - - public void setVisibilityType(String visibilityType) { - this.visibilityType = visibilityType; - } - - public Size computeSize() { - Size size = new Size(); - double width = 0; - double height = 0; - // System.out.println("Inside computesize"); - for (int i = 0; i<numOfRows; i++) { - if ((containerRowCol != null && containerRowCol.containsKey(i+String.valueOf(numOfCols-1))) || - (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(numOfCols-1)))) { - for (int j = 0; j < numOfCols; j++) { - if (containerRowCol!=null && containerRowCol.containsKey(i+String.valueOf(j))) { - width+=containerRowCol.get(i+String.valueOf(j)).computeSize().getWidth(); - // System.out.println(containerRowCol.get(i+String.valueOf(j)).getName()+" "+ - // containerRowCol.get(i+String.valueOf(j)).computeSize().getWidth()); - }else if (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(j))) - width+=elementRowCol.get(i+String.valueOf(j)).computeSize().getWidth(); - } - break; - } - } - // System.out.println("Object name "+this.getName()); - if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers") - || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) { - width+=(numOfCols-1)*interEleWd+2*interEleToInnerContainerWd; - } else { - width+=(numOfCols-1)*interEleWd+2*interEleToContainerWd; - } - size.setWidth(width); - for (int j = 0; j<numOfCols; j++) { - // System.out.println("Inside computesize height "+numOfCols); - // System.out.println(containerRowCol.toString()); - if ((containerRowCol != null && containerRowCol.containsKey(String.valueOf(numOfRows-1)+j)) || - (elementRowCol!= null && elementRowCol.containsKey(String.valueOf(numOfRows-1)+j))) { - //System.out.println("Inside if"); - for (int i = 0; i < numOfRows; i++) { - if (containerRowCol!= null && containerRowCol.containsKey(i+String.valueOf(j))) { - height+=containerRowCol.get(i+String.valueOf(j)).computeSize().getHeight(); - System.out.println("My C name "+this.getName()+":"+containerRowCol.get(i+String.valueOf(j)).computeSize().getHeight()); - } - else if (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(j))) - height+=elementRowCol.get(String.valueOf(i)+String.valueOf(j)).computeSize().getHeight(); - } - break; - } - } - if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers") - || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) { - height+=(numOfRows-1)*interEleH+2*interEleToInnerContainerH+0.1; - } else { - if (this.getName().equals("VoLTE UE") || this.getName().equals("3G UE") || this.getName().equals("HC UE-A") - || this.getName().equals("HC UE-B") || this.getName().equals("VNI UE") || this.getName().equals("PSTN")) { - height+=(numOfRows-1)*interEleH+interEleToContainerH/2; - }else - height+=(numOfRows-1)*interEleH+2*interEleToContainerH; - } - size.setHeight(height); - // System.out.println("C name "+this.getName()+" height "+height); - System.out.println("test C height "+this.getName()+" height "+height+" (numOfRows-1)*interEleH "+(numOfRows-1)*interEleH+ - " interEleToContainerH "+interEleToContainerH/2); - return size; - } - - - - public void computeElementPositions() { - double xsum = 0; - double ysum = 0; - for (int i=0; i<numOfRows; i++){ - for (int j=0; j<numOfCols; j++){ - if (containerRowCol != null && containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) { - Container c = containerRowCol.get(String.valueOf(i)+ String.valueOf(j)); - Position p = new Position(); - //System.out.println("within container"); - p.x =j*interEleWd+xsum+this.getP().getX()+ - interEleToContainerWd; - ysum = 0; - for (int k=0; k<i; k++) { - if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) - ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); - else if (elementRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) - ysum+= elementRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); - } - p.y = i*interEleH+ysum+this.getP().getY() + interEleToContainerH; - // containerCoord.add(c,p); - xsum+= c.computeSize().getWidth(); - c.setP(p); - - } else if (elementRowCol!=null && elementRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) { - Element e = elementRowCol.get(String.valueOf(i)+ String.valueOf(j)); - Position p = new Position(); - // System.out.println("i "+i+"j "+j); - // System.out.println("element "+e.getName()); - // System.out.println("Is this "+this.getP()); - if (j==numOfCols-1) { - for (int t=0; t<i; t++) { - if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(t)+ String.valueOf(j-1))) { - if (!elementRowCol.containsKey(String.valueOf(i)+ String.valueOf(j-1)) && - !containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j-1))) { - xsum+=containerRowCol.get(String.valueOf(t)+ String.valueOf(j-1)).computeSize().getWidth(); - break; - } - } - } - } - if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers") - || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") - || this.getName().equals("Neo") || this.getName().equals("Support")) { - p.x = j*interEleWd+xsum+this.getP().getX()+interEleToInnerContainerWd; - } - else if (this.getName().equals("VNI UE") || this.getName().equals("PSTN") || this.getName().equals("3G UE") - || this.getName().equals("HC UE-A") || this.getName().equals("HC UE-B")) { - p.x = j*interEleWd+xsum+this.getP().getX()+interEleToContainerWd-0.8; - }else { - p.x = j*interEleWd+xsum+this.getP().getX()+interEleToContainerWd; - System.out.println("element name "+e.getName()+" j*interEleWd "+j*interEleWd - +" xsum " +xsum+"this.getP().getX() "+this.getP().getX()+" interEleToContainerWd " +interEleToContainerWd+" p.x "+p.x); - } - ysum = 0; - for (int k=0; k<i; k++) { - if (containerRowCol!= null && containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) - ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); - else if (elementRowCol!=null && elementRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) - ysum+= elementRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); - else if (containerRowCol!= null) { - for (int chk=j; chk>0; chk--) { - if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(chk-1))) { - if (containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).computeSize().getWidth() - + containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).getP().getX() > p.x) { - ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).computeSize().getHeight(); - break; - } - } - } - } - - } - if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers") - || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) { - p.y = this.getP().getY()+ysum+i*interEleH+interEleToInnerContainerH+1; - } else { - // System.out.println("element name "+e.getName()+" this.getP().getY() "+this.getP().getY() - // +" ysum " +ysum+" i*interEleH "+i*interEleH+" interEleToContainerH " +interEleToContainerH); - if (e.getName().equals("")) { - p.y = this.getP().getY()+ysum+i*interEleH+(interEleToContainerH); - System.out.println("test element name "+this.getName()+" Container height "+this.computeSize().getHeight()+" this.getP().getY() "+this.getP().getY() - +" ysum " +ysum+" i*interEleH "+i*interEleH+" interEleToContainerH-3 " +interEleToContainerH+" p.y "+p.y); - }else - p.y = this.getP().getY()+ysum+i*interEleH+interEleToContainerH; - // System.out.println(e.getName()+"My contain this.getP().getY() "+this.getP().getY() - // +"elements Y "+p.y); - } - xsum+= e.computeSize().getWidth(); - e.setP(p); - System.out.println("my element name "+e.getName()+" e.getP().getX() "+e.getP().getX()); - System.out.println(); - } - } - xsum = 0; - } - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Domain.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Domain.java deleted file mode 100644 index 3e742785..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Domain.java +++ /dev/null @@ -1,259 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ - -package org.openecomp.portalsdk.core.domain.support; - -import java.util.List; -import java.util.Map; - -public class Domain { - // Unique identifier of the domain - String id; - // List<Container> cList; - - public String name; - Size size; - Position p; - - //Attribute1 at; - - public Position getP() { - return p; - } - - public void setP(Position p) { - this.p = p; - } - - //Horizontal space between a pair of containers - double interContWd = 1.0; - //Vertical space between a pair of containers - double interContH; - double domainToLayoutWd; - double domainToContH; - double domainToLayoutH; - int numOfRowsofContainer; - int numOfColsofContainer; - boolean indexChanged; - Map<String,Container> containerRowCol; - public Domain(String id, String name, double interContWd, double interContH, double domainToLayoutWd, - double domainToLayoutH, double domainToContH, int numOfRowsofContainer, int numOfColsofContainer) { - this.id = id; - this.name = name; - this.interContWd = interContWd; - this.interContH = interContH; - this.domainToLayoutWd = domainToLayoutWd; - this.domainToLayoutH = domainToLayoutH; - this.domainToContH = domainToContH; - this.numOfRowsofContainer = numOfRowsofContainer; - this.numOfColsofContainer = numOfColsofContainer; - // at = new Attribute1(); - } - - - - - public double top; - - public double left; - - public double height; - - public double width; - - public List<Container> containerList; - - public double newXafterColl; - - public double YafterColl; - - public void setNewXafterColl(double newXafterColl) { - this.newXafterColl = newXafterColl; - } - - public double getNewXafterColl() { - return newXafterColl; - } - - public double getYafterColl() { - return YafterColl; - } - - public void setYafterColl(double yafterColl) { - YafterColl = yafterColl; - } - - public void setDomainToLayoutWd(double domainToLayoutWd) { - this.domainToLayoutWd = domainToLayoutWd; - } - - public double getDomainToLayoutWd() { - return domainToLayoutWd; - } - - public double getTop() { - return top; - } - - public void setTop(double top) { - this.top = top; - } - - public double getLeft() { - return left; - } - - public void setLeft(double left) { - this.left = left; - } - - public double getHeight() { - return height; - } - - public void setHeight(double height) { - this.height = height; - } - - public double getWidth() { - return width; - } - - public void setWidth(double width) { - this.width = width; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setContainers(Map<String,Container> containerRowCol) { - this.containerRowCol = containerRowCol; - } - - public Map<String, Container> getContainerRowCol() { - return containerRowCol; - } - - - /* public Attribute1 getAt() { - return at; - } - - public void setAt(Attribute1 at) { - this.at = at; - }*/ - - public void setContainerList(List<Container> containerList) { - // new ArrayList<Container>(); - this.containerList = containerList; - } - - - -/* public boolean isCollapsed() { - return collapsed; - } - - public void setCollapsed(boolean collapsed) { - this.collapsed = collapsed; - }*/ - - public boolean isIndexChanged() { - return indexChanged; - } - - public void setIndexChanged(boolean indexChanged) { - this.indexChanged = indexChanged; - } - - //Compute the size of any domain - public Size computeSize() { - size = new Size(); - size.setHeight(5); - double width = 0; - for (int i = 0; i < numOfRowsofContainer; i++) { - if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(i)+String.valueOf(numOfColsofContainer-1))) { - for (int j = 0; j < numOfColsofContainer; j++) { - width+=containerRowCol.get(String.valueOf(i)+String.valueOf(j)).computeSize().getWidth(); - } - break; - } - - } - width+=(numOfColsofContainer-1)*interContWd; - if (this.getName().equals("VNI")) - size.setWidth(width-4); - else - size.setWidth(width); - return size; - } - - public void computeConatinerPositions() { - - double xsum = 0; - double ysum = 0; - for (int i=0; i< numOfRowsofContainer; i++){ - for (int j=0; j<numOfColsofContainer; j++){ - if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) { - Container c = containerRowCol.get(String.valueOf(i)+ String.valueOf(j)); - // System.out.println("container "+c.toString()); - Position p = new Position(); - if (this.getName().equals("VNI")) { - p.x = j*(interContWd-2)+xsum+domainToLayoutWd; - } else - p.x = j*interContWd+xsum+domainToLayoutWd; - // this.computeSize(); - // p.x = j*interContWd+xsum+this.getP().getX(); - ysum = 0; - for (int k=0; k<i; k++) { - // System.out.println("i value "+i); - if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) - ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); - // System.out.println("Container height "+containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).getName()+ - // ":"+" "+containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight()); - else if (j>0 && containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j-1)) && - !containerRowCol.get(String.valueOf(i)+ String.valueOf(j)).getName().equals("Alpharetta")) { - ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j-1)).computeSize().getHeight(); - } - } - System.out.println("C name "+c.getName()+" ysum "+ysum+" domainToLayoutH "+domainToLayoutH+" this.computeSize().getHeight() "+ - this.computeSize().getHeight()+" domainToContH "+domainToContH+" interContH "+interContH); - p.y = domainToLayoutH+ysum+this.computeSize().getHeight()+ - domainToContH+i*interContH; - - c.setP(p); - xsum+= c.computeSize().getWidth(); - - } - } - xsum = 0; - - } - - } - -} - - diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/DomainVo.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/DomainVo.java deleted file mode 100644 index 645a9132..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/DomainVo.java +++ /dev/null @@ -1,179 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.Date; -import java.util.Set; - -import org.openecomp.portalsdk.core.domain.FusionVo; - - -/* Super class from which all data objects descend */ -@SuppressWarnings("rawtypes") -public class DomainVo extends FusionVo implements Serializable, Cloneable, Comparable { - - /** - * - */ - private static final long serialVersionUID = 1L; - protected Long id; - protected Date created; - protected Date modified; - protected Long createdId; - protected Long modifiedId; - protected Long rowNum; - - protected Serializable auditUserId; - - Set auditTrail = null; - - public DomainVo() {} - - - public void setId(Long i) { - id = i; - } - - public void setCreated(Date created) { - this.created = created; - } - - public void setModified(Date modified) { - this.modified = modified; - } - - public void setCreatedId(Long createdId) { - this.createdId = createdId; - } - - public void setModifiedId(Long modifiedId) { - this.modifiedId = modifiedId; - } - - public void setAuditUserId(Serializable auditUserId) { - this.auditUserId = auditUserId; - } - - public void setRowNum(Long rowNum) { - this.rowNum = rowNum; - } - - public void setAuditTrail(Set auditTrail) { - this.auditTrail = auditTrail; - } - - public Long getId() { - return id; - } - - public Date getCreated() { - return created; - } - - public Date getModified() { - return modified; - } - - public Long getCreatedId() { - return createdId; - } - - public Long getModifiedId() { - return modifiedId; - } - - public Serializable getAuditUserId() { - return auditUserId; - } - - public Long getRowNum() { - return rowNum; - } - - public Set getAuditTrail() { - return auditTrail; - } - -/* public void addAuditTrailLog(AuditLog auditLog) { - if (getAuditTrail() == null) { - setAuditTrail(new HashSet()); - } - - getAuditTrail().add(auditLog); - }*/ - - - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - - public Object copy() { - return copy(false); - } - - - public Object copy(boolean isIdNull) { - // let's create a "copy" of the object using serialization - ByteArrayOutputStream baos = null; - ByteArrayInputStream bais = null; - ObjectOutputStream oos = null; - ObjectInputStream ois = null; - - DomainVo newVo = null; - - try { - - baos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(baos); - oos.writeObject(this); - - bais = new ByteArrayInputStream(baos.toByteArray()); - ois = new ObjectInputStream(bais); - newVo = (DomainVo)ois.readObject(); - - if (isIdNull) { - newVo.setId(null); - } - - } - catch (Exception e) { - e.printStackTrace(); - } - - return newVo; - } - - - - public int compareTo(Object obj){ - Long c1 = getId(); - Long c2 = ((DomainVo)obj).getId(); - - return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Element.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Element.java deleted file mode 100644 index 84f929fd..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Element.java +++ /dev/null @@ -1,161 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -public class Element { - - public String id; - public String name; - - public double top; - - public double left; - - public double height; - - public String imgFileName; - - public String borderType; - - public String bgColor; - - public ElementDetails details; - - //public List<ElementDetails> details; - - - public void setBgColor(String bgColor) { - this.bgColor = bgColor; - } - - public void setId(String id) { - this.id = id; - } - - public void setTop(double top) { - this.top = top; - } - - public void setLeft(double left) { - this.left = left; - } - - public void setHeight(double height) { - this.height = height; - } - - public void setWidth(double width) { - this.width = width; - } - - - public double width; - - - public String getId() { - return id; - } - - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - Position p; - - public Position getP() { - return p; - } - - public void setP(Position p) { - this.p = p; - } - - - - public Element(String id, String name, String imgPath, String bgColor, String logical_group, String display_longname, - String description, String primary_function, String key_interfaces, String location, String vendor, String vendor_shortname) { - this.id = id; - this.name = name; - this.imgFileName = imgPath; - this.bgColor = bgColor; - - - } - - public Element(String id, String name) { - this.id = id; - this.name = name; - } - - public Element(String id, String name, String imgFilename, String bgColor, String borderType, ElementDetails details) { - this.id = id; - this.name = name; - this.imgFileName = imgFilename; - this.bgColor = bgColor; - this.borderType = borderType; - this.details = details; - - } - - - public void setBorderType(String borderType) { - this.borderType = borderType; - } - - public String getImgFileName() { - return imgFileName; - } - - public void setImgFileName(String imgFileName) { - this.imgFileName = imgFileName; - } - - public String getBorderType() { - return borderType; - } - - - - public ElementDetails getDetails() { - return details; - } - - - - public void setDetails(ElementDetails details) { - this.details = details; - } - - public Size computeSize() { - Size size= new Size(); - size.setWidth(0.5*7.0); - size.setHeight(0.5*3.0); - // size.setWidth(0.5*10.0); - // size.setHeight(0.5*6.0); - return size; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/ElementDetails.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/ElementDetails.java deleted file mode 100644 index cebaeddc..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/ElementDetails.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -public class ElementDetails { - public String logical_group; - public String display_longname; - public String description; - public String primary_function; - public String network_function; - public String key_interfaces; - public String location; - public String vendor; - public String vendor_shortname; - public String enclosingContainer; - - -// public Map<String,String> details1; - -// public ElementDetails(Map<String, String> details) { - - // this.details = new HashMap<String, String>(); - // this.details1 = details; -// } - - - - - - public ElementDetails(String logical_group, String display_longname, String description, String primary_function, String network_function, - String key_interfaces, String location, String vendor, String vendor_shortname, String enclosingContainer) { - - this.logical_group = logical_group; - this.display_longname = display_longname; - this.description = description; - this.primary_function = primary_function; - this.network_function = network_function; - this.key_interfaces = key_interfaces; - this.location = location; - this.vendor = vendor; - this.vendor_shortname = vendor_shortname; - this.enclosingContainer = enclosingContainer; - } - - public void setLogical_group(String logical_group) { - this.logical_group = logical_group; - } - - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/FusionCommand.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/FusionCommand.java deleted file mode 100644 index 6ac85b6f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/FusionCommand.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -import org.openecomp.portalsdk.core.FusionObject; - -public class FusionCommand implements FusionObject { - - private String task; - - public FusionCommand() { - } - - public String getTask() { - return task; - } - - public void setTask(String task) { - this.task = task; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Layout.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Layout.java deleted file mode 100644 index 58056232..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Layout.java +++ /dev/null @@ -1,991 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -public class Layout { - - public Map<String,Domain> domainRowCol; - - Map<String,Domain> originalDomainRowCol; - - //Horizontal space between a pair of domains - double interDomainWd; - //Vertical space between a pair of domains - double interDomainH; - //Computing the co-ordinates of any domain - int numberofRowsofDomains; - - int numberofColsofDomains; - - Map<String, Domain> collapsedDomains; - - List<Domain> collapsedDomainsNewList; - - public List<Domain> getCollapsedDomainsNewList() { - return collapsedDomainsNewList; - } - - public void setCollapsedDomainsNewList(List<Domain> collapsedDomainsNewList) { - this.collapsedDomainsNewList = collapsedDomainsNewList; - } - - public void setCollapsedDomains(Map<String, Domain> collapsedDomains) { - this.collapsedDomains = collapsedDomains; - } - - public Map<String, Domain> getCollapsedDomains() { - return collapsedDomains; - } - - public int getNumberofColsofDomains() { - return numberofColsofDomains; - } - - public void setNumberofColsofDomains(int numberofColsofDomains) { - this.numberofColsofDomains = numberofColsofDomains; - } - - public Layout(Map<String,Domain> domainRowCol, double interDomainWd, double interDomainH, - int numberofRowsofDomains, int numberofColsofDomains) { - - this.domainRowCol = domainRowCol; - this.interDomainWd = interDomainWd; - this.interDomainH = interDomainH; - this.numberofRowsofDomains = numberofRowsofDomains; - this.numberofColsofDomains = numberofColsofDomains; - this.collapsedDomains = new HashMap<String, Domain>(); - this.originalDomainRowCol = new TreeMap<String,Domain>(); - this.collapsedDomainsNewList = new ArrayList<Domain>(); - } - - public Map<String, Domain> getDomainRowCol() { - return domainRowCol; - } - - public void setDomainRowCol(Map<String, Domain> domainRowCol) { - this.domainRowCol = domainRowCol; - } - - - public void computeDomainPositions() { - double xsum = 0; - double domainTolayout = 10.6; - for (int i=0; i< numberofRowsofDomains; i++){ - for (int j=0; j<numberofColsofDomains; j++){ - if (domainRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) { - Domain d = domainRowCol.get(String.valueOf(i)+ String.valueOf(j)); - Position p = new Position(); - if (j==0) - p.x = domainTolayout; - else - p.x = j*interDomainWd + xsum + domainTolayout; - if (getCollapsedDomainsNewList().size() > 0) - p.x+= accountForPlusSpaceBefore(d); - xsum+=d.computeSize().getWidth(); - double ysum=0; - for (int k=0; k<i; k++) { - if (domainRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) - ysum+= domainRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); - } - p.y = (i+1)* interDomainH + ysum; - d.setP(p); - - } - } - xsum = 0; - } - } - - public void computeDomainPositionsModified() { - for (int i=0; i< numberofRowsofDomains; i++){ - for (int j=0; j<numberofColsofDomains; j++){ - if (domainRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) { - Domain d = domainRowCol.get(String.valueOf(i)+ String.valueOf(j)); - Position p = new Position(); - Map<String,Container> enclosedContainers = d.getContainerRowCol(); - for (Map.Entry<String, Container> entry : enclosedContainers.entrySet()) { - if (entry.getKey().equals("00")) { - double containerX = entry.getValue().getP().getX(); - p.x = containerX; - double ysum=0; - for (int k=0; k<i; k++) { - if (domainRowCol.containsKey(String.valueOf(k)+ String.valueOf(j))) - ysum+= domainRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight(); - } - p.y = (i+1)* interDomainH + ysum; - d.setP(p); - break; - } - } - } - } - } - - - } - public Layout collapseDomainModified(String domainsToCollapse) { - - if(domainsToCollapse == null || domainsToCollapse.isEmpty()) - return null; - - Map<String,Domain> updatedRC = new HashMap<String, Domain>(); - - for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { - updatedRC.put(copyEntry.getKey(), copyEntry.getValue()); - System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); - } - - Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC); - - Map<String, Domain> collapsedDomainMap = getCollapsedDomains(); - - List<Domain> collapsedDomainNewL = getCollapsedDomainsNewList(); - - - if (collapsedDomainNewL.size() == 0) { - for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { - originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue()); - } - } - - - 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()); - - } - 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> 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; - for (Map.Entry<String,Domain> cd : updatedRC.entrySet()) { - - Domain d = cd.getValue(); - double accountPlus = accountForPlusSpaceBefore(d); - d.setDomainToLayoutWd(currDistFromLftM+accountPlus); - d.computeConatinerPositions(); - for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { - Container c = entry1.getValue(); - c.computeSize(); - c.computeElementPositions(); - if (c.getContainerRowCol() != null) { - for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { - Container inner = entryInner.getValue(); - inner.computeElementPositions(); - } - } - } - currDistFromLftM += d.computeSize().getWidth()+2; - - } - - - - - //nline - // Insert method invocation - updatePlusPosition(collapsedDomainNewL, updatedRC); - - //order changed - setCollapsedDomains(collapsedDomainMap); - setCollapsedDomainsNewList(collapsedDomainNewL); - - - computeDomainPositionsModified(); - return this; - } - - - - public Layout collapseDomainNew(String domainsToCollapse) { - - if(domainsToCollapse == null || domainsToCollapse.isEmpty()) - return null; - - Map<String,Domain> updatedRC = new HashMap<String, Domain>(); - - for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { - updatedRC.put(copyEntry.getKey(), copyEntry.getValue()); - System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); - } - - Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC); - - Map<String, Domain> collapsedDomainMap = getCollapsedDomains(); - - List<Domain> collapsedDomainNewL = getCollapsedDomainsNewList(); - - - if (collapsedDomainNewL.size() == 0) { - for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { - originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue()); - } - } - - - 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()); - - } - 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> updateOthers : updatedRCSortedTrunc.entrySet()) { - char update[] = updateOthers.getKey().toCharArray(); - int charToupdate = Character.getNumericValue(update[1]); - --charToupdate; - String resultRowCol = String.valueOf(update[0])+String.valueOf(charToupdate); - updateOthers.getValue().setIndexChanged(true); - updatedRC.put(resultRowCol, updateOthers.getValue()); - updatedRC.remove(updateOthers.getKey()); - - } - setDomainRowCol(updatedRC); - - double currDistFromLftM = 11.0; - - boolean isDisplayed; - for (Map.Entry<String,Domain> orgEntry : originalDomainRowCol.entrySet()) { - isDisplayed = false; - for (Map.Entry<String,Domain> cd : updatedRC.entrySet()) { - if (cd.getValue().getName().equals(orgEntry.getValue().getName())) { - Domain d = cd.getValue(); - d.setDomainToLayoutWd(currDistFromLftM); - d.computeConatinerPositions(); - for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { - Container c = entry1.getValue(); - c.computeSize(); - c.computeElementPositions(); - if (c.getContainerRowCol() != null) { - for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { - Container inner = entryInner.getValue(); - inner.computeElementPositions(); - } - } - } - currDistFromLftM += d.computeSize().getWidth()+1; - isDisplayed = true; - break; - } - } - - if (!isDisplayed) { - Domain myCollapsed = orgEntry.getValue(); - myCollapsed.setNewXafterColl(currDistFromLftM); - myCollapsed.setYafterColl(myCollapsed.getP().getY()); - currDistFromLftM += 4; - } - } - - setCollapsedDomains(collapsedDomainMap); - setCollapsedDomainsNewList(collapsedDomainNewL); - - - computeDomainPositionsModified(); - return this; - - } - - - public Layout collapseDomain(String domainsToCollapse) { - - Map<String,Domain> updatedRC = new HashMap<String, Domain>(); - - for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { - updatedRC.put(copyEntry.getKey(), copyEntry.getValue()); - System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); - } - - Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC); - - Map<String, Domain> collapsedDomainMap = getCollapsedDomains(); - - if (collapsedDomainMap.size() == 0) { - for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) { - originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue()); - } - } - - - double prevDomXCordinate = 0.0; - 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()); - 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; - } - } - - setCollapsedDomains(collapsedDomainMap); - - for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) { - updatedRCSortedTrunc.put(copyEntry.getKey(), copyEntry.getValue()); - System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue()); - } - - for (Map.Entry<String, Domain> rmv : updatedRCSorted.entrySet()) { - if (Character.getNumericValue(rmv.getKey().toCharArray()[1]) <= colToDelete) { - updatedRCSortedTrunc.remove(rmv.getKey()); - } - } - - for (Map.Entry<String, Domain> 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 (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); - } - 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(); - } - } - } - } - computeDomainPositions(); - return this; - - } - - public Layout uncollapseDomainModified(String domainToUnCollapse) { - Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol); - Map<String, Domain> updateDomains = new TreeMap<String,Domain>(); - Map<String, Domain> collapsedDomainList = getCollapsedDomains(); - Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList); - - List<Domain> domainstoUpd = new ArrayList<Domain>(); - - int colToUnCollapse = 99; - - Domain domainToInsert = null; - - if (collapsedDomains.size() == 0) { - for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) { - Domain dm = unindexDomain.getValue(); - dm.setIndexChanged(false); - } - } - - - for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) { - if (entry.getValue().getName().equals(domainToUnCollapse)) { - colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]); - domainToInsert = entry.getValue(); - collapsedDomainList.remove(entry.getKey()); - break; - } - } - - domainstoUpd.add(domainToInsert); - - for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet()) - System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName()); - - int lastKeyCol = -1; - for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) { - int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]); - if (currcol < colToUnCollapse) { - for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) { - if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) { - updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue()); - lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]); - break; - } - } - } else { - String newKey = "0"+String.valueOf(lastKeyCol+1); - if (currcol == colToUnCollapse) { - updateDomains.put(newKey, domainToInsert); - ++lastKeyCol; - } else { - for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) { - if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) { - updateDomains.put(newKey, currDomainsEnt.getValue()); - domainstoUpd.add(currDomainsEnt.getValue()); - ++lastKeyCol; - 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 = 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(); - else - newX = domainstoUpd.get(i).getP().getX()+32; - - if (d.getName().equals("Datacenter")) - newX+= 2; - d.setDomainToLayoutWd(newX); - 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(); - } - } - } - } - - 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) { - int colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]); - for (Map.Entry<String, Domain> curr : currentDomainsSorted.entrySet()) { - if (Character.getNumericValue(curr.getKey().toCharArray()[1]) < colToUnCollapse) { - updateDomains.put(curr.getKey(),curr.getValue()); - } else { - updateDomains.put("0"+String.valueOf(Integer.parseInt(curr.getKey())+1),curr.getValue()); - domainstoUpd.add(curr.getValue()); - } - } - } - updateDomains.put(entry.getKey(), entry.getValue()); - collapsedDomainList.remove(entry.getKey()); - break; - - } - } - setNumberofColsofDomains(getNumberofColsofDomains()+1); - setDomainRowCol(updateDomains); - setCollapsedDomains(collapsedDomainList); - - for (Map.Entry<String, Domain> e : updateDomains.entrySet()) - System.out.println("Updatedomains key value"+e.getKey()+":"+e.getValue().getName()); - - - for (int i = 0; i < domainstoUpd.size(); i++) { - Domain d = domainstoUpd.get(i); - double newX = 0.0; - if (i+1 < domainstoUpd.size()) - newX = domainstoUpd.get(i+1).getP().getX(); - else - newX = domainstoUpd.get(i).getP().getX()+38; - - if (d.getName().equals("Datacenter")) - newX+= 5; - d.setDomainToLayoutWd(newX); - 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(); - } - } - } - } - - 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(); - List<Domain> domainstoUpd = new ArrayList<Domain>(); - - //nline - List<Domain> collapsedDomainNewLL = getCollapsedDomainsNewList(); - - int colToUnCollapse = 99; - - Domain domainToInsert = null; - - //nline - if (collapsedDomainNewLL.size() == 0) { - for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) { - Domain dm = unindexDomain.getValue(); - dm.setIndexChanged(false); - } - } - - - for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) { - if (entry.getValue().getName().equals(domainToUnCollapse)) { - colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]); - domainToInsert = entry.getValue(); - collapsedDomainList.remove(entry.getKey()); - //nline - collapsedDomainNewLL.remove(entry.getValue()); - break; - } - } - - domainstoUpd.add(domainToInsert); - - for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet()) - System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName()); - - int lastKeyCol = -1; - for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) { - int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]); - if (currcol < colToUnCollapse) { - for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) { - if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) { - updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue()); - lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]); - break; - } - } - } else { - String newKey = "0"+String.valueOf(lastKeyCol+1); - if (currcol == colToUnCollapse) { - updateDomains.put(newKey, domainToInsert); - ++lastKeyCol; - } else { - for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) { - if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) { - updateDomains.put(newKey, currDomainsEnt.getValue()); - domainstoUpd.add(currDomainsEnt.getValue()); - ++lastKeyCol; - break; - } - } - } - - } - } - - setNumberofColsofDomains(getNumberofColsofDomains()+1); - setDomainRowCol(updateDomains); - - for (Map.Entry<String, Domain> e : updateDomains.entrySet()) - System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName()); - - - - double currDistFromLftMargin = 11.0; - for (Map.Entry<String,Domain> cd : updateDomains.entrySet()) { - Domain d = cd.getValue(); - double accountPlus = accountForPlusSpaceBefore(d); - d.setDomainToLayoutWd(currDistFromLftMargin+accountPlus); - d.computeConatinerPositions(); - for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { - Container c = entry1.getValue(); - c.computeSize(); - c.computeElementPositions(); - if (c.getContainerRowCol() != null) { - for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { - Container inner = entryInner.getValue(); - inner.computeElementPositions(); - } - } - } - currDistFromLftMargin += d.computeSize().getWidth()+2; - - } - - //nline - updatePlusPosition(collapsedDomainNewLL, updateDomains); - - //order changed - setCollapsedDomains(collapsedDomainList); - - //nline - setCollapsedDomainsNewList(collapsedDomainNewLL); - - - computeDomainPositionsModified(); - return this; - - } - - public Layout uncollapseDomainNew1(String domainToUnCollapse) { - - if(domainToUnCollapse == null || domainToUnCollapse.isEmpty()) - return null; - - Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol); - Map<String, Domain> updateDomains = new TreeMap<String,Domain>(); - Map<String, Domain> collapsedDomainList = getCollapsedDomains(); - List<Domain> domainstoUpd = new ArrayList<Domain>(); - - //nline - List<Domain> collapsedDomainNewLL = getCollapsedDomainsNewList(); - - int colToUnCollapse = 99; - - Domain domainToInsert = null; - - //nline - if (collapsedDomainNewLL.size() == 0) { - for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) { - Domain dm = unindexDomain.getValue(); - dm.setIndexChanged(false); - } - } - - - for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) { - if (entry.getValue().getName().equals(domainToUnCollapse)) { - colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]); - domainToInsert = entry.getValue(); - collapsedDomainList.remove(entry.getKey()); - //nline - collapsedDomainNewLL.remove(entry.getValue()); - break; - } - } - - domainstoUpd.add(domainToInsert); - - for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet()) - System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName()); - - int lastKeyCol = -1; - for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) { - int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]); - if (currcol < colToUnCollapse) { - for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) { - if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) { - updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue()); - lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]); - break; - } - } - } else { - String newKey = "0"+String.valueOf(lastKeyCol+1); - if (currcol == colToUnCollapse) { - updateDomains.put(newKey, domainToInsert); - ++lastKeyCol; - } else { - for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) { - if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) { - updateDomains.put(newKey, currDomainsEnt.getValue()); - domainstoUpd.add(currDomainsEnt.getValue()); - ++lastKeyCol; - break; - } - } - } - - } - } - - setNumberofColsofDomains(getNumberofColsofDomains()+1); - setDomainRowCol(updateDomains); - - for (Map.Entry<String, Domain> e : updateDomains.entrySet()) - System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName()); - - - - - double currDistFromLftM = 11.0; - - boolean isDisplayed; - for (Map.Entry<String,Domain> orgEntry : originalDomainRowCol.entrySet()) { - isDisplayed = false; - for (Map.Entry<String,Domain> cd : updateDomains.entrySet()) { - if (cd.getValue().getName().equals(orgEntry.getValue().getName())) { - Domain d = cd.getValue(); - d.setDomainToLayoutWd(currDistFromLftM); - d.computeConatinerPositions(); - for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) { - Container c = entry1.getValue(); - c.computeSize(); - c.computeElementPositions(); - if (c.getContainerRowCol() != null) { - for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) { - Container inner = entryInner.getValue(); - inner.computeElementPositions(); - } - } - } - currDistFromLftM += d.computeSize().getWidth()+1; - isDisplayed = true; - break; - } - } - - if (!isDisplayed) { - Domain myCollapsed = orgEntry.getValue(); - myCollapsed.setNewXafterColl(currDistFromLftM); - currDistFromLftM += 4; - } - } - - - //order changed - setCollapsedDomains(collapsedDomainList); - - //nline - setCollapsedDomainsNewList(collapsedDomainNewLL); - - - computeDomainPositionsModified(); - return this; - - } - - private void updatePlusPosition(List<Domain> collapsedDNewL, Map<String, Domain> displayedDomainMap) { - List<Domain> copyCollapseList = new ArrayList<Domain>(); - - for (Domain copyCollapse : collapsedDNewL) { - copyCollapseList.add(copyCollapse); - } - - int orgColofCollapsed = -1; - int orgColofDisplayed = -1; - int orgColofDisplayedOtherPlus = -1; - for (Domain plus : collapsedDNewL) { - double distOfCollFrmLft = 0.0; - for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) { - if (colCheck.getValue().getName().equals(plus.getName())) { - orgColofCollapsed = Character.getNumericValue(colCheck.getKey().toCharArray()[1]); - break; - } - } - for (Map.Entry<String, Domain> displayedEntry : displayedDomainMap.entrySet()) { - - for (Map.Entry<String, Domain> colCheck1 : originalDomainRowCol.entrySet()) { - if (colCheck1.getValue().getName().equals(displayedEntry.getValue().getName())) { - orgColofDisplayed = Character.getNumericValue(colCheck1.getKey().toCharArray()[1]); - break; - } - } - if (orgColofDisplayed < orgColofCollapsed) { - distOfCollFrmLft+= displayedEntry.getValue().computeSize().getWidth(); - - } - - } - - for (Domain collp : copyCollapseList) { - if (!collp.getName().equals(plus.getName())) { - for (Map.Entry<String, Domain> colCheck2 : originalDomainRowCol.entrySet()) { - if (colCheck2.getValue().getName().equals(collp.getName())) { - orgColofDisplayedOtherPlus = Character.getNumericValue(colCheck2.getKey().toCharArray()[1]); - break; - } - } - if (orgColofDisplayedOtherPlus < orgColofCollapsed) { - distOfCollFrmLft+=3.0; - } - } - } - - plus.setNewXafterColl(distOfCollFrmLft+1.5); - - - } - } - - - private double accountForPlusSpaceBefore(Domain d) { - - int orgColofCollapsed = 0; - int orgColofDisplayed = 0; - double distFromLftM = 0.0; - - for (Map.Entry<String, Domain> colCheckk : originalDomainRowCol.entrySet()) { - if (colCheckk.getValue().getName().equals(d.getName())) { - orgColofDisplayed = Character.getNumericValue(colCheckk.getKey().toCharArray()[1]); - break; - } - } - - for (Domain collapsed : getCollapsedDomainsNewList()) { - for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) { - if (colCheck.getValue().getName().equals(collapsed.getName())) { - orgColofCollapsed = Character.getNumericValue(colCheck.getKey().toCharArray()[1]); - break; - } - } - - if (orgColofCollapsed < orgColofDisplayed) { - distFromLftM+= 2; - } - } - return distFromLftM; - - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/NameValueId.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/NameValueId.java deleted file mode 100644 index 52d03c5f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/NameValueId.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -import java.io.Serializable; - - -public class NameValueId implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - private String lab; - private String val; - - public NameValueId() { - } - - public NameValueId(String value, String label) { - setVal(value); - setLab(label); - } - - - public String getLab() { - return lab; - } - - - public String getVal() { - return val; - } - - - public void setLab(String label) { - this.lab = label; - } - - - public void setVal(String value) { - this.val = value; - } - - - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (o == null) { - return false; - } - - if (!(o instanceof NameValueId)) { - return false; - } - - final NameValueId nameValueId = (NameValueId)o; - - if (!getVal().equals(nameValueId.getVal())) { - return false; - } - - if (!getLab().equals(nameValueId.getLab())) { - return false; - } - - return true; - } - - - public int hashCode() { - return getVal().hashCode(); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Position.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Position.java deleted file mode 100644 index db137c80..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Position.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -public class Position { - double x; - double y; - - public double getX() { - return x; - } - public void setX(double x) { - this.x = x; - } - public double getY() { - return y; - } - public void setY(double y) { - this.y = y; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Size.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Size.java deleted file mode 100644 index 4ebfb962..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/domain/support/Size.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.domain.support; - -public class Size { - private double width; - private double height; - - public double getWidth() { - return width; - } - public void setWidth(double width) { - this.width = width; - } - public double getHeight() { - return height; - } - public void setHeight(double height) { - this.height = height; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleService.java deleted file mode 100644 index c556aa13..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleService.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.drools; - -public interface DroolsRuleService { - - public void init(String... params); - public String getResultsString(); - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleServiceImpl.java deleted file mode 100644 index 7328c472..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/drools/DroolsRuleServiceImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.drools; - - -/** - * - * This is POC test class to execute sample rules - */ -public class DroolsRuleServiceImpl implements DroolsRuleService{ - - - private String state; - private String resultsString; - - public DroolsRuleServiceImpl() { - - } - - public void init(String... params) { - this.state = params[0]; - } - - - - public String getState() { - return state; - } - - public String accessLabel() { - return "Drools POC Test"; - } - - public String getResultsString() { - return resultsString; - } - - public void setResultsString(String resultsString) { - this.resultsString = resultsString; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/FusionExceptionResolver.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/FusionExceptionResolver.java deleted file mode 100644 index f756d760..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/FusionExceptionResolver.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.exception; - -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.servlet.ModelAndView; - -@ControllerAdvice -public class FusionExceptionResolver { - - @ExceptionHandler(UrlAccessRestrictedException.class) - public ModelAndView handleUrlAccessException(UrlAccessRestrictedException ex) { - ModelAndView model = new ModelAndView("error"); - model.addObject("errMsg", ex.getMessage()); - return model; - - } - @ExceptionHandler(SessionExpiredException.class) - public ModelAndView handleSessionException(SessionExpiredException ex) { - ModelAndView model = new ModelAndView("error"); - model.addObject("errMsg", ex.getMessage()); - return model; - } - @ExceptionHandler(Exception.class) - public ModelAndView handleAllException(Exception ex) { - ModelAndView model = new ModelAndView("error"); - model.addObject("errMsg", ex.getMessage()); - return model; - - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/SessionExpiredException.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/SessionExpiredException.java deleted file mode 100644 index ba8f76bd..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/SessionExpiredException.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.exception; - -import org.openecomp.portalsdk.core.exception.support.FusionRuntimeException; - -public class SessionExpiredException extends FusionRuntimeException { - /** - * - */ - private static final long serialVersionUID = 1L; - public static final String MESSAGE = "Your session has expired. Please login again."; - - public SessionExpiredException() { - super(MESSAGE); - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/UrlAccessRestrictedException.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/UrlAccessRestrictedException.java deleted file mode 100644 index 39fe264a..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/UrlAccessRestrictedException.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.exception; - -import org.openecomp.portalsdk.core.exception.support.FusionRuntimeException; - -public class UrlAccessRestrictedException extends FusionRuntimeException { - /** - * - */ - private static final long serialVersionUID = 1L; - public static final String MESSAGE = "Authorization Denied"; - - public UrlAccessRestrictedException() { - super(MESSAGE); - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionException.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionException.java deleted file mode 100644 index 135fc3e3..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionException.java +++ /dev/null @@ -1,24 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.exception.support; - -import org.openecomp.portalsdk.core.FusionObject; - -public interface FusionException extends FusionObject {} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionRuntimeException.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionRuntimeException.java deleted file mode 100644 index f7ca61fa..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/exception/support/FusionRuntimeException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.exception.support; - -public class FusionRuntimeException extends RuntimeException implements FusionException { - /** - * - */ - private static final long serialVersionUID = 1L; - - public FusionRuntimeException() { - this(""); - } - - public FusionRuntimeException(String message) { - super(message); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/interceptor/ResourceInterceptor.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/interceptor/ResourceInterceptor.java deleted file mode 100644 index 24088cdb..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/interceptor/ResourceInterceptor.java +++ /dev/null @@ -1,164 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.interceptor; - -import java.net.HttpURLConnection; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.portalsdk.core.controller.FusionBaseController; -import org.openecomp.portalsdk.core.domain.App; -import org.openecomp.portalsdk.core.exception.UrlAccessRestrictedException; -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.openecomp.portalsdk.core.service.LoginService; -import org.openecomp.portalsdk.core.service.WebServiceCallService; -import org.openecomp.portalsdk.core.util.CipherUtil; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -public class ResourceInterceptor extends HandlerInterceptorAdapter { - public static final String APP_METADATA = "APP.METADATA"; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ResourceInterceptor.class); - - @Autowired - private DataAccessService dataAccessService; - @Autowired - private LoginService loginService; - @Autowired - private WebServiceCallService webServiceCallService; - - private AbstractCacheManager cacheManager; - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - String uri = request.getRequestURI(); - String url = uri.substring(uri.indexOf("/", 1) + 1); - logger.info(EELFLoggerDelegate.debugLogger, "Url - " + url); - logger.info(EELFLoggerDelegate.debugLogger, "lastIndexOf - " + uri.substring(uri.lastIndexOf("/") + 1)); - if (handler instanceof HandlerMethod) { - HandlerMethod method = (HandlerMethod) handler; - FusionBaseController controller = (FusionBaseController) method.getBean(); - if (!controller.isAccessible()) { - if (controller.isRESTfulCall()) { - // check user authentication for RESTful calls - String secretKey = null; - try { - if (!webServiceCallService.verifyRESTCredential(secretKey, request.getHeader("username"), - request.getHeader("password"))) { - logger.error(EELFLoggerDelegate.errorLogger, "Error accesing RESTful service. Un-authorized",AlarmSeverityEnum.MINOR); - throw new UrlAccessRestrictedException(); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Error authenticating RESTful service :" + e,AlarmSeverityEnum.MINOR); - ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); - return false; - } - } - if (!UserUtils.isUrlAccessible(request, url)) { - logger.error(EELFLoggerDelegate.errorLogger, "Error accesing URL. Un-authorized",AlarmSeverityEnum.MINOR); - throw new UrlAccessRestrictedException(); - } - } - } - - logger.debug("successfully authorized rest call"); - logger.info(EELFLoggerDelegate.debugLogger, "successfully authorized rest call"); - handleSessionUpdates(request); - logger.debug("handled session updates for synchronization"); - logger.info(EELFLoggerDelegate.debugLogger, "handled session updates for synchronization"); - return super.preHandle(request, response, handler); - } - - /** - * - * @param request - */ - protected void handleSessionUpdates(HttpServletRequest request) { - - App app = null; - Object appObj = getCacheManager().getObject(APP_METADATA); - if (appObj == null) { - app = findApp(); - getCacheManager().putObject(APP_METADATA, app); - - } else { - app = (App) appObj; - } - - String ecompRestURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); - String decreptedPwd = ""; - try { - decreptedPwd = CipherUtil.decrypt(app.getAppPassword(), - SystemProperties.getProperty(SystemProperties.Decryption_Key)); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Could not decrypt Password" + e.getMessage(),AlarmSeverityEnum.MINOR); - } - - PortalTimeoutHandler.handleSessionUpdatesNative(request, app.getUsername(), decreptedPwd, - PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), ecompRestURL, null); - } - - public App findApp() { - List<?> list = null; - StringBuffer criteria = new StringBuffer(); - criteria.append(" where id = 1"); - list = getDataAccessService().getList(App.class, criteria.toString(), null, null); - return (list == null || list.size() == 0) ? null : (App) list.get(0); - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - public LoginService getLoginService() { - return loginService; - } - - public void setLoginService(LoginService loginService) { - this.loginService = loginService; - } - - @Autowired - public void setCacheManager(AbstractCacheManager cacheManager) { - this.cacheManager = cacheManager; - } - - public AbstractCacheManager getCacheManager() { - return cacheManager; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/interceptor/SessionTimeoutInterceptor.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/interceptor/SessionTimeoutInterceptor.java deleted file mode 100644 index e28ce866..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/interceptor/SessionTimeoutInterceptor.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.interceptor; - -import java.net.URLEncoder; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.openecomp.portalsdk.core.controller.FusionBaseController; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.exception.SessionExpiredException; -import org.openecomp.portalsdk.core.listener.CollaborateListBindingListener; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.web.support.AppUtils; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; - -public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionTimeoutInterceptor.class); - - public SessionTimeoutInterceptor() { - } - - /** - * Checks all requests for valid session information. If not found, - * redirects to a controller that will establish a valid session. - */ - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - if (handler instanceof HandlerMethod) { - HandlerMethod method = (HandlerMethod) handler; - FusionBaseController controller = (FusionBaseController) method.getBean(); - if (!controller.isAccessible() && !controller.isRESTfulCall()) { - try { - // getSession() throws SessionExpiredException - HttpSession session = AppUtils.getSession(request); - User user = UserUtils.getUserSession(request); - // check if user is logging out - if (request.getRequestURI().indexOf("logout.htm") > -1) { - session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME); - throw new SessionExpiredException(); - } else if (user == null) { - // Jump to the redirection code - throw new Exception("preHandle: user not found in session"); - } else { - // session binding listener will add this value to the - // map, and with session replication the listener will - // fire in all tomcat instances - session.setAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME, - new CollaborateListBindingListener(user.getOrgUserId())); - } - } catch (Exception ex) { - // get the path within the webapp that the user requested (no host name etc.) - final String forwardUrl = request.getRequestURI().substring(request.getContextPath().length() + 1) - + (request.getQueryString() == null ? "" : "?" + request.getQueryString()); - final String forwardUrlParm = "forwardURL=" + URLEncoder.encode(forwardUrl, "UTF-8"); - final String singleSignonPrefix = "/single_signon.htm?"; - if (ex instanceof SessionExpiredException) { - // Session is expired; send to portal. - // Redirect to an absolute path in the webapp; e.g., "/context/single_signon.htm" - final String redirectUrl = request.getContextPath() + singleSignonPrefix + "redirectToPortal=Yes&" + forwardUrlParm; - logger.debug(EELFLoggerDelegate.debugLogger, "preHandle: session is expired, redirecting to {}", - redirectUrl); - response.sendRedirect(redirectUrl); - return false; - } else { - // Other issue; do not send to portal. - // Redirect to an absolute path in the webapp; e.g., "/context/single_signon.htm" - final String redirectUrl = request.getContextPath() + singleSignonPrefix + forwardUrlParm; - logger.debug(EELFLoggerDelegate.debugLogger, "preHandle: took exception {}, redirecting to {}", - ex.getMessage(), redirectUrl); - response.sendRedirect(redirectUrl); - return false; - } - } - } - } - - return super.preHandle(request, response, handler); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/interfaces/SecurityInterface.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/interfaces/SecurityInterface.java deleted file mode 100644 index b40c4713..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/interfaces/SecurityInterface.java +++ /dev/null @@ -1,24 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.interfaces; - -public interface SecurityInterface { - public boolean isAccessible(); -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/listener/ApplicationContextListener.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/listener/ApplicationContextListener.java deleted file mode 100644 index 10e2b2d9..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/listener/ApplicationContextListener.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.listener; - -import javax.servlet.ServletContext; -import javax.servlet.annotation.WebListener; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.stereotype.Component; - -@WebListener -@Component -public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> { - - @Autowired - ServletContext context; - - - public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) { - -// String contextPath = context.getContextPath(); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/listener/CollaborateListBindingListener.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/listener/CollaborateListBindingListener.java deleted file mode 100644 index 9306aaf1..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/listener/CollaborateListBindingListener.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.listener; - -import java.io.Serializable; - -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; - -import org.openecomp.portalsdk.core.domain.support.CollaborateList; - -public class CollaborateListBindingListener implements HttpSessionBindingListener, Serializable { - - private static final long serialVersionUID = 1L; - private String userName; - public static final String SESSION_ATTR_NAME = "CollaborateListSessionAttrName"; - - public CollaborateListBindingListener(String _userName) { - userName = _userName; - } - - @Override - public void valueBound(HttpSessionBindingEvent event) { - final CollaborateListBindingListener value = ((CollaborateListBindingListener) event.getValue()); - CollaborateList.addUserName(value.getUserName()); - - } - - @Override - public void valueUnbound(HttpSessionBindingEvent event) { - final CollaborateListBindingListener value = ((CollaborateListBindingListener) event.getValue()); - if (value != null) - CollaborateList.delUserName(value.getUserName()); - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/listener/UserSessionListener.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/listener/UserSessionListener.java deleted file mode 100644 index adc84775..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/listener/UserSessionListener.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.listener; - -import javax.servlet.annotation.WebListener; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; - -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; - - -@WebListener -public class UserSessionListener implements HttpSessionListener{ - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserSessionListener.class); - - public void sessionCreated(HttpSessionEvent event){ - - } - - /** - * Removes sessions from the context scoped HashMap when they expire - * or are invalidated. - */ - public void sessionDestroyed(HttpSessionEvent event){ - try { - HttpSession session = event.getSession(); - session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME); - - // Object user = session.getAttribute(SystemProperties.getProperty("user.attribute.name")); - - //if( user != null) - // { - session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME); - //CollaborateList.getInstance().delUserName(user.getOrgUserId()); - // } - - } - catch(Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "sessionDestroyed" + e.getMessage(),AlarmSeverityEnum.MINOR); - } - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/AuditLog.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/AuditLog.java deleted file mode 100644 index 5a1a8640..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/AuditLog.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.aspect; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - - -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface AuditLog { - String value() default ""; -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAdvice.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAdvice.java deleted file mode 100644 index 5264c70b..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAdvice.java +++ /dev/null @@ -1,193 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.aspect; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.portalsdk.core.logging.format.AuditLogFormatter; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.AppService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; - -import com.att.eelf.configuration.Configuration; - -@org.springframework.context.annotation.Configuration -public class EELFLoggerAdvice { - - @Autowired - AppService appService; - - EELFLoggerDelegate adviceLogger = EELFLoggerDelegate.getLogger(EELFLoggerAdvice.class); - - //DateTime Format according to the ECOMP Application Logging Guidelines. - private static final SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - public Object[] before(SecurityEventTypeEnum securityEventType, Object[] args, Object[] passOnArgs) { - try { - String className = ""; - if (passOnArgs[0]!=null) { - className = passOnArgs[0].toString(); - } - - String methodName = ""; - if (passOnArgs[1]!=null) { - methodName = passOnArgs[1].toString(); - } - - String appName = appService.getDefaultAppName(); - if (appName==null || appName=="") { - appName = SystemProperties.SDK_NAME; - } - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className); - - //Initialize Request defaults only for controller methods. - MDC.put(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC()); - MDC.put(SystemProperties.TARGET_ENTITY, appName + "_BE"); - MDC.put(SystemProperties.TARGET_SERVICE_NAME, methodName); - if (securityEventType!=null) { - MDC.put(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC()); - HttpServletRequest req = null; - if (args[0]!=null && args[0] instanceof HttpServletRequest ) { - req = (HttpServletRequest)args[0]; - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(req, appName); - } - } - logger.debug(EELFLoggerDelegate.debugLogger, (methodName +" was invoked.")); - } catch(Exception e) { - adviceLogger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in EELFLoggerAdvice.before() method. Details: " + e.getMessage()); - } - - return new Object[] {""}; - } - - public void after(SecurityEventTypeEnum securityEventType, String result, Object[] args, Object[] returnArgs, Object[] passOnArgs) { - try { - String className = ""; - if (passOnArgs[0]!=null) { - className = passOnArgs[0].toString(); - } - - String methodName = ""; - if (passOnArgs[1]!=null) { - methodName = passOnArgs[1].toString(); - } - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className); - - String appName = appService.getDefaultAppName(); - if (appName==null || appName=="") { - appName = SystemProperties.SDK_NAME; - } - - if (MDC.get(SystemProperties.TARGET_SERVICE_NAME) == null || MDC.get(SystemProperties.TARGET_SERVICE_NAME) == "") { - MDC.put(SystemProperties.TARGET_SERVICE_NAME, methodName); - } - - if (MDC.get(SystemProperties.TARGET_ENTITY) == null || MDC.get(SystemProperties.TARGET_ENTITY) == "") { - MDC.put(SystemProperties.TARGET_ENTITY, appName + "_BE"); - } - - MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, MDC.get(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP)); - MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, getCurrentDateTimeUTC()); - this.calculateDateTimeDifference(MDC.get(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP), MDC.get(SystemProperties.METRICSLOG_END_TIMESTAMP)); - - logger.info(EELFLoggerDelegate.metricsLogger, methodName + " operation is completed."); - logger.debug(EELFLoggerDelegate.debugLogger, "Finished executing " + methodName + "."); - - if (securityEventType!=null) { - - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, MDC.get(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP)); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, getCurrentDateTimeUTC()); - this.calculateDateTimeDifference(MDC.get(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP), MDC.get(SystemProperties.AUDITLOG_END_TIMESTAMP)); - - this.logSecurityMessage(logger, securityEventType, result, methodName); - - //clear when finishes audit logging - MDC.remove(Configuration.MDC_KEY_REQUEST_ID); - MDC.remove(SystemProperties.PARTNER_NAME); - MDC.remove(SystemProperties.MDC_LOGIN_ID); - MDC.remove(SystemProperties.PROTOCOL); - MDC.remove(SystemProperties.FULL_URL); - MDC.remove(Configuration.MDC_SERVICE_NAME); - MDC.remove(SystemProperties.RESPONSE_CODE); - MDC.remove(SystemProperties.STATUS_CODE); - MDC.remove(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP); - MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP); - MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP); - } - - MDC.remove(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP); - MDC.remove(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP); - MDC.remove(SystemProperties.METRICSLOG_END_TIMESTAMP); - MDC.remove(SystemProperties.MDC_TIMER); - MDC.remove(SystemProperties.TARGET_ENTITY); - MDC.remove(SystemProperties.TARGET_SERVICE_NAME); - } catch(Exception e) { - adviceLogger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in EELFLoggerAdvice.after() method. Details: " + e.getMessage()); - } - } - - private void logSecurityMessage(EELFLoggerDelegate logger, SecurityEventTypeEnum securityEventType, String result, String restMethod) { - StringBuilder additionalInfoAppender = new StringBuilder(); - String auditMessage = ""; - - additionalInfoAppender.append(String.format("%s request was received.", restMethod)); - - //Status code - MDC.put(SystemProperties.STATUS_CODE, result); - - String fullURL = MDC.get(SystemProperties.FULL_URL); - if (fullURL!=null && fullURL!="") { - additionalInfoAppender.append(" Request-URL:" + MDC.get(SystemProperties.FULL_URL)); - } - - auditMessage = AuditLogFormatter.getInstance().createMessage( MDC.get(SystemProperties.PROTOCOL), - securityEventType.name(), - MDC.get(SystemProperties.MDC_LOGIN_ID), - additionalInfoAppender.toString()); - - logger.info(EELFLoggerDelegate.auditLogger, auditMessage); - } - - private String getCurrentDateTimeUTC() { - String currentDateTime = ecompLogDateFormat.format(new Date()); - return currentDateTime; - } - - private void calculateDateTimeDifference(String beginDateTime, String endDateTime) { - if (beginDateTime!=null && endDateTime!=null) { - try { - Date beginDate = ecompLogDateFormat.parse(beginDateTime); - Date endDate = ecompLogDateFormat.parse(endDateTime); - String timeDifference = String.format("%d ms", endDate.getTime() - beginDate.getTime()); - MDC.put(SystemProperties.MDC_TIMER, timeDifference); - } catch(Exception e) { - adviceLogger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in EELFLoggerAdvice.calculateDateTimeDifference() method. Details: " + e.getMessage()); - } - } - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAspect.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAspect.java deleted file mode 100644 index 3138d21a..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/EELFLoggerAspect.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.aspect; - -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Pointcut; -import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; -import org.springframework.beans.factory.annotation.Autowired; - - -@Aspect -@org.springframework.context.annotation.Configuration -public class EELFLoggerAspect { - - @Autowired - EELFLoggerAdvice advice; - - /* - * Point-cut expression to handle all INCOMING_REST_MESSAGES - */ - @Pointcut("execution(public * org.openecomp.portalsdk.core.controller.*.*(..))") - public void incomingAuditMessages() {} - - @Around("incomingAuditMessages() && @annotation(auditLog)") - public Object logAuditMethodAround(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable { - return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); - } - - @Around("incomingAuditMessages() && @within(auditLog)") - public Object logAuditMethodClassAround(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable { - return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); - } - - /* - * Point cut expression to capture metrics logging - */ - @Pointcut("execution(public * *(..))") - public void publicMethod() {} - - @Around("publicMethod() && @within(metricsLog)") - public Object logMetricsClassAround(ProceedingJoinPoint joinPoint, MetricsLog metricsLog) throws Throwable { - return this.logAroundMethod(joinPoint, null); - } - - @Around("publicMethod() && @annotation(metricsLog)") - public Object logMetricsMethodAround(ProceedingJoinPoint joinPoint, MetricsLog metricsLog) throws Throwable { - return this.logAroundMethod(joinPoint, null); - } - - private Object logAroundMethod(ProceedingJoinPoint joinPoint, SecurityEventTypeEnum securityEventType) throws Throwable { - //Before - Object[] passOnArgs = new Object[] {joinPoint.getSignature().getDeclaringType().getName(),joinPoint.getSignature().getName()}; - Object[] returnArgs = advice.before(securityEventType, joinPoint.getArgs(), passOnArgs); - - //Execute the actual method - Object result = null; - String restStatus = "COMPLETE"; - try { - result = joinPoint.proceed(); - } catch(Exception e) { - restStatus = "ERROR"; - } - - //After - advice.after(securityEventType, restStatus, joinPoint.getArgs(), returnArgs, passOnArgs); - - return result; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/MetricsLog.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/MetricsLog.java deleted file mode 100644 index f795ffb1..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/aspect/MetricsLog.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.aspect; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - - -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface MetricsLog { - String value() default ""; -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/AlarmSeverityEnum.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/AlarmSeverityEnum.java deleted file mode 100644 index 360d8d81..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/AlarmSeverityEnum.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.format; - -public enum AlarmSeverityEnum { - CRITICAL, - MAJOR, - MINOR, - INFORMATIONAL, - NONE, -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/AppMessagesEnum.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/AppMessagesEnum.java deleted file mode 100644 index a6924ba0..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/AppMessagesEnum.java +++ /dev/null @@ -1,249 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.format; - -public enum AppMessagesEnum { - /* - 100-199 Security/Permission Related - - Authentication problems (from external client, to external server) - - Certification errors - - - - 200-299 Availability/Timeout Related - - connectivity error - - connection timeout - - 300-399 Data Access/Integrity Related - - Data in graph in invalid(E.g. no creator is found for service) - - Artifact is missing in ES, but exists in graph. - - 400-499 Schema Interface Type/Validation - - received Pay-load checksum is invalid - - received JSON is not valid - - 500-599 Business/Flow Processing Related - - check out to service is not allowed - - Roll-back is done - - failed to generate heat file - - - 600-899 Reserved - do not use - - 900-999 Unknown Errors - - Unexpected exception - */ - - BeUebAuthenticationError(ErrorCodesEnum.BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR100E", "An Authentication failure occurred during access to UEB server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), - - BeRestApiAuthenticationError(ErrorCodesEnum.BERESTAPIAUTHENTICATIONERROR, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR101E", "Rejected an incoming REST API request due to invalid credentials", "", "Please check application credentials defined in Database or properties files."), - - InternalAuthenticationInfo(ErrorCodesEnum.INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, - "ERR199I", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), - - InternalAuthenticationWarning(ErrorCodesEnum.INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, - "ERR199W", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), - - InternalAuthenticationError(ErrorCodesEnum.INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR199E", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), - - InternalAuthenticationFatal(ErrorCodesEnum.INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL, - "ERR199F", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), - - BeHealthCheckError(ErrorCodesEnum.BeHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, - "ERR200E", "ECOMP-PORTAL Back-end probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster", "", "Please check the logs for more information."), - - BeHealthCheckMySqlError(ErrorCodesEnum.BEHEALTHCHECKMYSQLERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, - "ERR201E", "ECOMP-PORTAL Back-end probably lost connectivity to MySQL DB", "", "Check connectivity to MYSQL is configured correctly under system.properties file."), - - BeHealthCheckUebClusterError(ErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, - "ERR203E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "", "Check connectivity to UEB cluster which is configured under portal.properties file."), - - FeHealthCheckError(ErrorCodesEnum.FEHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, - "ERR204E", "Unable to connect to a valid ECOMP-PORTAL Back-end Server.", "", "Please check connectivity from this FE instance towards BE or BE Load Balancer."), - - BeHealthCheckRecovery(ErrorCodesEnum.BEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, - "ERR205I", "ECOMP-PORTAL Back-end Recovery to either one of the following components: MySQL DB, UEB Cluster", "", "Please check logs for more specific information about the problem."), - - BeHealthCheckMySqlRecovery(ErrorCodesEnum.BEHEALTHCHECKMYSQLRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, - "ERR206I", "ECOMP-PORTAL Back-end connection recovery to MySQL DB", "", "Please check logs for more specific information about the problem."), - - BeHealthCheckUebClusterRecovery(ErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, - "ERR208I", "ECOMP-PORTAL Back-end connection recovery to UEB Cluster", "", "Please check logs for more specific information about the problem."), - - FeHealthCheckRecovery(ErrorCodesEnum.FEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, - "ERR209I", "Connectivity to ECOMP-PORTAL Front-end Server is recovered", "", "Please check logs for more specific information about the problem."), - - BeUebConnectionError(ErrorCodesEnum.BEUEBCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR210E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), - - BeUebUnkownHostError(ErrorCodesEnum.BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR211E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Cannot reach host: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), - - BeUebRegisterOnboardingAppError(ErrorCodesEnum.BEUEBREGISTERONBOARDINGAPPERROR, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR212E", "Failed to register the On-boarding application with UEB Communication server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), - - BeHttpConnectionError(ErrorCodesEnum.BEHTTPCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR213E", "It could be that communication to an external application might resulted an exception or failed to reach the external application", - "Details: {0}.", "Please check logs for more information."), - - InternalConnectionInfo(ErrorCodesEnum.INTERNALCONNECTIONINFO_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, - "ERR299I", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), - - InternalConnectionWarning(ErrorCodesEnum.INTERNALCONNECTIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, - "ERR299W", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), - - InternalConnectionError(ErrorCodesEnum.INTERNALCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR299E", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), - - InternalConnectionFatal(ErrorCodesEnum.INTERNALCONNECTIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL, - "ERR299F", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), - - BeUebObjectNotFoundError(ErrorCodesEnum.BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR303E", "Error occurred during access to U-EB Server.", "Data not found: {0}.", "An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic."), - - BeUserMissingError(ErrorCodesEnum.BEUSERMISSINGERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR310E", "User is not found", "", "User {0} must be added to the corresponding application with proper user roles."), - - BeUserInactiveWarning(ErrorCodesEnum.BEUSERINACTIVEWARNING_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, - "ERR313W", "User is found but in-active", "", "User {0} must be added to the corresponding application with proper user roles."), - - BeUserAdminPrivilegesInfo(ErrorCodesEnum.BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, - "ERR314W", "User is found but don't have administrative privileges", "", "User {0} should be given administrator role for the corresponding application to perform the necessary actions."), - - BeInvalidJsonInput(ErrorCodesEnum.BEINVALIDJSONINPUT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR405E", "Failed to convert JSON input to object", "", "Please check logs for more information."), - - BeIncorrectHttpStatusError(ErrorCodesEnum.BEINCORRECTHTTPSTATUSERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR407E", "Communication to an external application is resulted in with Incorrect Http response code", "", "Please check logs for more information."), - - BeInitializationError(ErrorCodesEnum.BEINITIALIZATIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, - "ERR500E", "ECOMP-PORTAL Back-end was not initialized properly", "", "Please check logs for more information."), - - BeUebSystemError(ErrorCodesEnum.BEUEBSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR502E", "Error occurred during access to U-EB Server", "Details: {0}.", "An error occurred in {1} distribution mechanism. Please check the logs for more information."), - - BeDaoSystemError(ErrorCodesEnum.BEDAOSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, - "ERR505E", "Performing DDL or DML operations on database might have failed", "", "Please check MySQL DB health or look at the logs for more details."), - - BeSystemError(ErrorCodesEnum.BESYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, - "ERR506E", "Unexpected error during operation", "", "Please check logs for more information."), - - BeExecuteRollbackError(ErrorCodesEnum.BEEXECUTEROLLBACKERROR, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR507E", "Roll-back operation towards database has failed", "", "Please check MYSQL DB health or look at the logs for more details."), - - FeHttpLoggingError(ErrorCodesEnum.FEHTTPLOGGINGERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.ERROR, - "ERR517E", "Error when logging FE HTTP request/response", "", "Please check MYSQL DB health or look at the logs for more details."), - - FePortalServletError(ErrorCodesEnum.FEPORTALSERVLETERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR518E", "Error when trying to access FE Portal page.", "", "Please check logs for more information."), - - BeDaoCloseSessionError(ErrorCodesEnum.BEDAOCLOSESESSIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR519E", "Close local session operation with database failed", "", "Please check MYSQL DB health or look at the logs form more details."), - - BeRestApiGeneralError(ErrorCodesEnum.BERESTAPIGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, - "ERR900E", "Unexpected error during ECOMP-PORTAL Back-end REST API execution", "", "Please check error log for more information."), - - FeHealthCheckGeneralError(ErrorCodesEnum.FEHEALTHCHECKGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, - "ERR901E", "General error during FE Health Check", "", "Please check error log for more information."), - - InternalUnexpectedInfo(ErrorCodesEnum.INTERNALUNEXPECTEDINFO_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, - "ERR999I", "Unexpected error", "Details: {0}.", "Please check logs for more information."), - - InternalUnexpectedWarning(ErrorCodesEnum.INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, - "ERR999W", "Unexpected error", "Details: {0}.", "Please check logs for more information."), - - InternalUnexpectedError(ErrorCodesEnum.INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR999E", "Unexpected error", "Details: {0}.", "Please check logs for more information."), - - InternalUnexpectedFatal(ErrorCodesEnum.INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL, - "ERR999F", "Unexpected error", "Details: {0}.", "Please check logs for more information."), - - ; - - ErrorTypeEnum eType; - AlarmSeverityEnum alarmSeverity; - ErrorCodesEnum messageCode; - ErrorSeverityEnum errorSeverity; - String errorCode; - String errorDescription; - String details; - String resolution; - - AppMessagesEnum(ErrorCodesEnum messageCode, ErrorTypeEnum eType, AlarmSeverityEnum alarmSeverity, ErrorSeverityEnum errorSeverity, String errorCode, String errorDescription, - String details, String resolution) { - this.messageCode = messageCode; - this.eType = eType; - this.alarmSeverity = alarmSeverity; - this.errorSeverity = errorSeverity; - this.errorCode = errorCode; - this.errorDescription = errorDescription; - this.details = details; - this.resolution = resolution; - } - - public String getDetails() { - return this.details; - } - - public String getResolution() { - return this.resolution; - } - public String getErrorCode() { - return this.errorCode; - } - - public String getErrorDescription() { - return this.errorDescription; - } - - public ErrorSeverityEnum getErrorSeverity() { - return this.errorSeverity; - } - - public void setErrorSeverity(ErrorSeverityEnum errorSeverity) { - this.errorSeverity = errorSeverity; - } - - public ErrorCodesEnum getMessageCode() { - return messageCode; - } - - public void setMessageCode(ErrorCodesEnum messageCode) { - this.messageCode = messageCode; - } - - public AlarmSeverityEnum getAlarmSeverity() { - return alarmSeverity; - } - - public void setAlarmSeverity(AlarmSeverityEnum alarmSeverity) { - this.alarmSeverity = alarmSeverity; - } - - public ErrorTypeEnum getErrorType() { - return eType; - } - - public void setErrorType(ErrorTypeEnum eType) { - this.eType = eType; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ApplicationCodes.properties b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ApplicationCodes.properties deleted file mode 100644 index efd9ac24..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ApplicationCodes.properties +++ /dev/null @@ -1,221 +0,0 @@ -### -# ================================================================================ -# eCOMP Portal SDK -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ================================================================================ -### -######################################################################## -#Resource key=Error Code|Message text|Resolution text |Description text -####### -#Newlines can be utilized to add some clarity ensuring continuing line -#has atleast one leading space -#ResourceKey=\ -# ERR0000E\ -# Sample error msg txt\ -# Sample resolution msg\ -# Sample description txt -# -###### -#Error code classification category -#100 Permission errors -#200 Availability errors/Timeouts -#300 Data errors -#400 Schema Interface type/validation errors -#500 Business process errors -#900 Unknown errors -# -######################################################################## - -#Health check -BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT=\ - ERR100E|\ - Authentication problem towards U-EB server. Reason: {0}.|\ - An Authentication failure occurred during access to UEB server. Please check that UEB keys are configured correctly under fusion.properties file.| - -BERESTAPIAUTHENTICATIONERROR =\ - ERR101E|\ - Rejected an incoming REST API request to {0} from {1} due to invalid credentials.|\ - Please check application credentials defined in Database or portal.properties file.| - -INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT=\ - ERR199I|\ - Internal authentication problem. Description: {0}.| - -INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT=\ - ERR199W|\ - Internal authentication problem. Description: {0}.| - -INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT=\ - ERR199E|\ - Internal authentication problem. Description: {0}.| - -INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT=\ - ERR199F|\ - Internal authentication problem. Description: {0}.| - -BEHEALTHCHECKERROR=\ - ERR200E|\ - {0} probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster. Please check the logs for more information.| - -BEHEALTHCHECKMYSQLERROR=\ - ERR201E|\ - {0} probably lost connectivity to MySQL DB. Please check the logs for more information.|\ - Check connectivity to MYSQL is configured correctly under system.properties file.| - -BEHEALTHCHECKUEBCLUSTERERROR=\ - ERR203E|\ - {0} probably lost connectivity to UEB Cluster. Please check the logs for more information.|\ - Check connectivity to UEB cluster which is configured under portal.properties file.| - -BEHEALTHCHECKRECOVERY=\ - ERR205I|\ - {0} Recovery to either one of the following components: MySQL DB, UEB Cluster.| - -BEHEALTHCHECKMYSQLRECOVERY=\ - ERR206I|\ - {0} connection recovery to MySQL DB.| - -BEHEALTHCHECKUEBCLUSTERRECOVERY=\ - ERR208I|\ - {0} connection recovery to UEB Cluster.| - -FEHEALTHCHECKRECOVERY=\ - ERR209I|\ - Connectivity to {0} Server is recovered.| - -#UEB communication -BEUEBCONNECTIONERROR_ONE_ARGUMENT=\ - ERR210E|\ - Connection problem towards U-EB server. Reason: {0}.|\ - Please check that that parameter uebServers in portal.properties points to a valid UEB Cluster.| - -BEUEBSYSTEMERROR=\ - ERR502E|\ - Error occurred during access to U-EB Server. Operation: {0}.|\ - An error occurred in {1} distribution mechanism. Please check the logs for more information.| - -BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT=\ - ERR211E|\ - Connection problem towards U-EB server. Cannot reach host {0}.|\ - Please check that that parameter uebServers in portal.properties points to a valid UEB Cluster.| - -#Onboarding apps -BEUEBREGISTERONBOARDINGAPPERROR=\ - ERR212E|\ - Unable to register the On-boarding application with the U-EB server. Reason: {0}.|\ - Please check that that parameter uebServers in system.properties points to a valid UEB Cluster.| - -#HTTP communication -BEHTTPCONNECTIONERROR_ONE_ARGUMENT=\ - ERR213E|\ - HTTP connection to an external application is failed. Reason: {0}.|\ - Please check the logs for more information.| - -INTERNALCONNECTIONINFO_ONE_ARGUMENT=\ - ERR299I|\ - Internal Connection problem. Description: {0}.| - -INTERNALCONNECTIONWARNING_ONE_ARGUMENT=\ - ERR299W|\ - Internal Connection problem. Description: {0}.| - -INTERNALCONNECTIONERROR_ONE_ARGUMENT=\ - ERR299E|\ - Internal Connection problem. Description: {0}.| - -INTERNALCONNECTIONFATAL_ONE_ARGUMENT=\ - ERR299F|\ - Internal Connection problem. Description: {0}.| - -BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT=\ - ERR303E|\ - Error occurred during access to U-EB Server. Data not found: {0}.|\ - An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic.| - -#Login error codes -BEUSERMISSINGERROR_ONE_ARGUMENT=\ - ERR310E|\ - User {0} requested is not found.| - -BEUSERINACTIVEWARNING_ONE_ARGUMENT=\ - ERR313W|\ - User {0} is found but inactive.| - -BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT=\ - ERR314W|\ - User {0} is found but don't have administrative privileges.| - -BEINVALIDJSONINPUT=\ - ERR405E|\ - Failed to convert JSON input to object.|\ - Please check error logs for more information.| - -BEINCORRECTHTTPSTATUSERROR=\ - ERR407E|\ - Incorrect HttpResponse Received.|\ - Please check error & metrics logs for more information.| - -BEINITIALIZATIONERROR=\ - ERR500E|\ - BE was not initialized properly.| - -BEDAOSYSTEMERROR=\ - ERR505E|\ - Operation towards database failed.|\ - Please check MySQL DB health or look at the logs for more details.| - -BESYSTEMERROR=\ - ERR506E|\ - Unexpected error during operation.| - -BEEXECUTEROLLBACKERROR=\ - ERR507E|\ - Roll-back operation towards database failed.|\ - Please check MYSQL DB health or look at the logs for more details.| - -FEHTTPLOGGINGERROR=\ - ERR517E|\ - Error when logging FE HTTP request/response.| - -BEDAOCLOSESESSIONERROR=\ - ERR519E|\ - Close local session operation with database failed.|\ - Please check MYSQL DB health or look at the logs form more details.| - -BERESTAPIGENERALERROR=\ - ERR900E|\ - Unexpected error during BE REST API execution.|\ - Please check error log for more information.| - -FEHEALTHCHECKGENERALERROR=\ - ERR901E|\ - General error during FE Health Check.| - -INTERNALUNEXPECTEDINFO_ONE_ARGUMENT=\ - ERR999I|\ - Unexpected error. Description: {0}.| - -INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT=\ - ERR999W|\ - Unexpected error. Description: {0}.| - -INTERNALUNEXPECTEDERROR_ONE_ARGUMENT=\ - ERR999E|\ - Unexpected error. Description: {0}.| - -INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT=\ - ERR999F|\ - Unexpected error. Description: {0}.| diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/AuditLogFormatter.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/AuditLogFormatter.java deleted file mode 100644 index 2cb336e2..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/AuditLogFormatter.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.format; - -import java.text.MessageFormat; -import java.util.Map; - -import org.openecomp.portalsdk.core.util.SystemProperties; - -public class AuditLogFormatter { - //Singleton - private static AuditLogFormatter instance = new AuditLogFormatter(); - - public static AuditLogFormatter getInstance() { - - return instance; - } - - public String createMessage(String protocol,String set, - String loginId, String message) { - - Object[] securityMessageArgs = prepareFormatArgs( - protocol, - set, - loginId, - message ); - - return MessageFormat.format(SystemProperties.SECURITY_LOG_TEMPLATE, securityMessageArgs); - } - - /** - * A method for normalizing the security log field - returns - * the @Param defaultValue in case the entry is null or empty. - * If the @param entry is not empty, a single quotation is added to it. - * - * @param entry the entry - * @param defaultValue The default value in case the entry is empty - * @return String (formatted) - */ - private String formatEntry(Object entry, String defaultValue) { - return (entry!=null && !entry.toString().isEmpty()) ? addSingleQuotes(entry.toString()): defaultValue; - - } - - private String addSingleQuotes(String s) { - if (null!=s && !s.isEmpty()) { - s = SystemProperties.SINGLE_QUOTE+s+SystemProperties.SINGLE_QUOTE; - } - return s; - } - - - /** - * This method prepares an Object array of arguments that would be passed - * to the MessageFormat.format() method, to format the security log. - * - * @param protocol - * @param set - * @param loginId - * @param accessingClient - * @param isSuccess - * @param message - * @return - */ - private Object[] prepareFormatArgs(String protocol,String set, - String loginId, String message) { - - Object[] messageFormatArgs = { - formatEntry(protocol, SystemProperties.NA), - formatEntry(set, SystemProperties.NA), - formatEntry(loginId, SystemProperties.UNKNOWN), - message - }; - return messageFormatArgs; - } - - - public String createMessage(Map<String, String> logArgsMap) { - - Object[] securityMessageArgs = prepareFormatArgs( - logArgsMap.get(SystemProperties.PROTOCOL), - logArgsMap.get(SystemProperties.SECURIRY_EVENT_TYPE), - logArgsMap.get(SystemProperties.LOGIN_ID), - logArgsMap.get(SystemProperties.ADDITIONAL_INFO) - ); - - return MessageFormat.format(SystemProperties.SECURITY_LOG_TEMPLATE, securityMessageArgs); - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorCodesEnum.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorCodesEnum.java deleted file mode 100644 index 59fe2bb7..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorCodesEnum.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.format; - -import com.att.eelf.i18n.EELFResolvableErrorEnum; -//import com.att.eelf.i18n.EELFResourceManager; - -public enum ErrorCodesEnum implements EELFResolvableErrorEnum { - BERESTAPIAUTHENTICATIONERROR, - BEHTTPCONNECTIONERROR_ONE_ARGUMENT, - BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT, - - INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT, - INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT, - INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT, - INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT, - - BEHEALTHCHECKRECOVERY, - BEHEALTHCHECKMYSQLRECOVERY, - BEHEALTHCHECKUEBCLUSTERRECOVERY, - FEHEALTHCHECKRECOVERY, - BeHEALTHCHECKERROR, - - BEHEALTHCHECKMYSQLERROR, - BEHEALTHCHECKUEBCLUSTERERROR, - FEHEALTHCHECKERROR, - BEUEBCONNECTIONERROR_ONE_ARGUMENT, - BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT, - BEUEBREGISTERONBOARDINGAPPERROR, - - INTERNALCONNECTIONINFO_ONE_ARGUMENT, - INTERNALCONNECTIONWARNING_ONE_ARGUMENT, - INTERNALCONNECTIONERROR_ONE_ARGUMENT, - INTERNALCONNECTIONFATAL_ONE_ARGUMENT, - - BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT, - BEUSERMISSINGERROR_ONE_ARGUMENT, - - BEUSERINACTIVEWARNING_ONE_ARGUMENT, - BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT, - - BEINVALIDJSONINPUT, - BEINCORRECTHTTPSTATUSERROR, - - BEINITIALIZATIONERROR, - BEUEBSYSTEMERROR, - BEDAOSYSTEMERROR, - BESYSTEMERROR, - BEEXECUTEROLLBACKERROR, - - FEHTTPLOGGINGERROR, - FEPORTALSERVLETERROR, - BEDAOCLOSESESSIONERROR, - - BERESTAPIGENERALERROR, - FEHEALTHCHECKGENERALERROR, - - INTERNALUNEXPECTEDINFO_ONE_ARGUMENT, - INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, - INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, - INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, - - ; - - /** - * Static initializer to ensure the resource bundles for this class are loaded... - * Here this application loads messages from three bundles - */ - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorSeverityEnum.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorSeverityEnum.java deleted file mode 100644 index 5908fda9..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorSeverityEnum.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.format; - -public enum ErrorSeverityEnum { - INFO, - WARN, - ERROR, - FATAL, -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorTypeEnum.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorTypeEnum.java deleted file mode 100644 index 8ce2d4dc..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/format/ErrorTypeEnum.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.format; - -public enum ErrorTypeEnum { - RECOVERY, - CONFIG_ERROR, - SYSTEM_ERROR, - DATA_ERROR, - CONNECTION_PROBLEM, - AUTHENTICATION_PROBLEM -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/logic/EELFLoggerDelegate.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/logic/EELFLoggerDelegate.java deleted file mode 100644 index 7cf5ee40..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/logging/logic/EELFLoggerDelegate.java +++ /dev/null @@ -1,323 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.logging.logic; - -import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY; -import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID; -import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; -import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; -import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; -import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; - -import java.net.InetAddress; -import java.text.MessageFormat; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.format.AppMessagesEnum; -import org.openecomp.portalsdk.core.logging.format.ErrorSeverityEnum; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.slf4j.MDC; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.att.eelf.configuration.SLF4jWrapper; - -public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger { - - public static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); - public static EELFLogger applicationLogger = EELFManager.getInstance().getApplicationLogger(); - public static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - public static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - public static EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); - private String className; - private static ConcurrentMap<String, EELFLoggerDelegate> classMap = new ConcurrentHashMap<String, EELFLoggerDelegate>(); - - public EELFLoggerDelegate(String _className) { - super(_className); - className = _className; - } - - public static EELFLoggerDelegate getLogger(Class<?> clazz) { - - String className = clazz.getName(); - EELFLoggerDelegate delegate = classMap.get(className); - if (delegate == null) { - delegate = new EELFLoggerDelegate(className); - classMap.put(className, delegate); - } - - return delegate; - - } - - public static EELFLoggerDelegate getLogger(String className) { - if (className==null || className=="") { - className = EELFLoggerDelegate.class.getName(); - } - EELFLoggerDelegate delegate = classMap.get(className); - if (delegate == null) { - delegate = new EELFLoggerDelegate(className); - classMap.put(className, delegate); - } - - return delegate; - } - - public void debug(EELFLogger logger, String msg) { - if (logger.isDebugEnabled()) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.debug(msg); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - } - - public void debug(EELFLogger logger, String msg, Object... arguments) { - if (logger.isDebugEnabled()) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.debug(msg, arguments); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - } - - public void debug(EELFLogger logger, String msg, Throwable th) { - if (logger.isDebugEnabled()) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.debug(msg, th); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - } - - // does not solve the superfluous overhead of string append - public void info(EELFLogger logger, String msg) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.info(msg); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - - public void info(EELFLogger logger, String msg, Object... arguments) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.info(msg, arguments); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - - public void info(EELFLogger logger, String msg, Throwable th) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.info(msg, th); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - - public void warn(EELFLogger logger, String msg) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.warn(msg); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - - public void warn(EELFLogger logger, String msg, Object... arguments) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.warn(msg, arguments); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - - public void warn(EELFLogger logger, String msg, Throwable th) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.warn(msg, th); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - - public void error(EELFLogger logger, String msg) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.error(msg); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - - public void error(EELFLogger logger, String msg, Object... arguments) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.warn(msg, arguments); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - - public void error(EELFLogger logger, String msg, Throwable th) { - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.warn(msg, th); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - - public void error(EELFLogger logger, String msg, AlarmSeverityEnum severtiy) { - MDC.put(MDC_ALERT_SEVERITY, severtiy.name()); - MDC.put(SystemProperties.MDC_CLASS_NAME, className); - logger.error(msg); - MDC.remove(MDC_ALERT_SEVERITY); - MDC.remove(SystemProperties.MDC_CLASS_NAME); - } - - public void init() { - // Initialize the logger context - setGlobalLoggingContext(); - - String msg = "############################ Logging is started. ############################"; - info(applicationLogger, msg); - error(errorLogger, msg); - info(auditLogger, msg); - info(metricsLogger, msg); - debug(debugLogger, msg); - info(errorLogger, "Successfully initialized the Global logger context."); - } - - public void logEcompError(AppMessagesEnum epMessageEnum, String... param) { - try { - AlarmSeverityEnum alarmSeverityEnum = epMessageEnum.getAlarmSeverity(); - ErrorSeverityEnum errorSeverityEnum = epMessageEnum.getErrorSeverity(); - - MDC.put(MDC_ALERT_SEVERITY, alarmSeverityEnum.name()); - MDC.put("ErrorCode", epMessageEnum.getErrorCode()); - MDC.put("ErrorDescription", epMessageEnum.getErrorDescription()); - - String resolution = this.formatMessage(epMessageEnum.getDetails() + " " + epMessageEnum.getResolution(), (Object[]) param); - if (errorSeverityEnum == ErrorSeverityEnum.WARN) { - errorLogger.warn(resolution); - } else if(errorSeverityEnum == ErrorSeverityEnum.INFO) { - errorLogger.info(resolution); - } else { - errorLogger.error(resolution); - } - } catch(Exception e) { - errorLogger.error("Failed to log the error code. Details: " + UserUtils.getStackTrace(e)); - } finally { - MDC.remove("ErrorCode"); - MDC.remove("ErrorDescription"); - MDC.remove(MDC_ALERT_SEVERITY); - } - } - - private String formatMessage(String message, Object...args) { - StringBuilder sbFormattedMessage = new StringBuilder(); - if (args!=null && args.length>0 && message!=null && message != "") { - MessageFormat mf = new MessageFormat(message); - sbFormattedMessage.append(mf.format(args)); - } else { - sbFormattedMessage.append(message); - } - - return sbFormattedMessage.toString(); - } - - /** - * Loads all the default logging fields into the MDC context. - */ - private void setGlobalLoggingContext() { - MDC.put(MDC_SERVICE_INSTANCE_ID, ""); - MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.toString()); - try { - MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); - MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); - MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID)); - } catch (Exception e) { - } - } - - public static void mdcPut(String key, String value) { - MDC.put(key, value); - } - - public static String mdcGet(String key) { - return MDC.get(key); - } - - public static void mdcRemove(String key) { - MDC.remove(key); - } - - /** - * Loads the RequestId/TransactionId into the MDC which it should be receiving - * with an each incoming REST API request. Also, configures few other request - * based logging fields into the MDC context. - * @param req - */ - public void setRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req, String appName) { - //Load the default fields - setGlobalLoggingContext(); - - //Load the request based fields - if (req!=null) { - //Load the Request into MDC context. - String requestId = UserUtils.getRequestId(req); - MDC.put(MDC_KEY_REQUEST_ID, requestId); - - //Load user agent into MDC context, if available. - String accessingClient = "Unknown"; - accessingClient = req.getHeader(SystemProperties.USERAGENT_NAME); - if (accessingClient!=null && accessingClient!="" && - (accessingClient.contains("Mozilla") || accessingClient.contains("Chrome") || accessingClient.contains("Safari"))) { - accessingClient = appName + "_FE"; - } - MDC.put(SystemProperties.PARTNER_NAME, accessingClient); - - //Protocol, Rest URL & Rest Path - String restURL = ""; - MDC.put(SystemProperties.FULL_URL, SystemProperties.UNKNOWN); - MDC.put(SystemProperties.PROTOCOL, SystemProperties.HTTP); - restURL = UserUtils.getFullURL(req); - if (restURL!=null && restURL!="") { - MDC.put(SystemProperties.FULL_URL, restURL); - if (restURL.toLowerCase().contains("https")) { - MDC.put(SystemProperties.PROTOCOL, SystemProperties.HTTPS); - } - } - - //Rest Path - MDC.put(MDC_SERVICE_NAME, req.getServletPath()); - - //Client IPAddress i.e. IPAddress of the remote host who is making this request. - String clientIPAddress = ""; - clientIPAddress = req.getHeader("X-FORWARDED-FOR"); - if (clientIPAddress == null) { - clientIPAddress = req.getRemoteAddr(); - } - MDC.put(SystemProperties.CLIENT_IP_ADDRESS, clientIPAddress); - - //Load loginId into MDC context. - MDC.put(SystemProperties.MDC_LOGIN_ID, "Unknown"); - String loginId = ""; - try { - loginId = UserUtils.getUserIdFromCookie(req); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if (loginId == null || loginId == "") { - User user = UserUtils.getUserSession(req); - if (user != null) { - loginId = user.getLoginId(); - } - } - - if (loginId!=null && loginId!="") { - MDC.put(SystemProperties.MDC_LOGIN_ID, loginId); - } - } - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/menu/MenuBuilder.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/menu/MenuBuilder.java deleted file mode 100644 index aac57025..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/menu/MenuBuilder.java +++ /dev/null @@ -1,164 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.menu; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.portalsdk.core.FusionObject; -import org.openecomp.portalsdk.core.domain.MenuData; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; - -@SuppressWarnings("rawtypes") -public class MenuBuilder implements FusionObject { - - @Autowired - private DataAccessService dataAccessService; - - public MenuBuilder() { - } - - - @SuppressWarnings("unchecked") - public Set getMenu(String menuSetName, DataAccessService dataAccessService) { - - Set menu = null; - MenuData root = null; - - HashMap params = new HashMap(); - - params.put("menu_set_cd", menuSetName); - - // execute a query of the latest configuration of the FN_MENU table for the given menu_set_cd. - List menuItems = dataAccessService.executeNamedQuery(SystemProperties.getProperty(SystemProperties.MENU_QUERY_NAME), params, null); - - Iterator i = menuItems.iterator(); - if (i.hasNext()) { - root = (MenuData)i.next(); - menu = root.getChildMenus(); - } - - return menu; - } - - @SuppressWarnings("unchecked") - public Set getMenu(String menuSetName) { - - Set menu = null; - MenuData root = null; - - HashMap params = new HashMap(); - - params.put("menu_set_cd", menuSetName); - - // execute a query of the latest configuration of the FN_MENU table for the given menu_set_cd. - List menuItems = getDataAccessService().executeNamedQuery(SystemProperties.getProperty(SystemProperties.MENU_QUERY_NAME), params, null); - - Iterator i = menuItems.iterator(); - if (i.hasNext()) { - root = (MenuData)i.next(); - menu = root.getChildMenus(); - } - - return menu; - } - - public static Set filterMenu(Set menus, HttpServletRequest request) { - Iterator j = menus.iterator(); - - while (j.hasNext()) { - MenuData menuItem = (MenuData)j.next(); - - if (!UserUtils.isAccessible(request, menuItem.getFunctionCd())) { - // remove the menu if the user doesn't have access to it - j.remove(); - } - else { - // if an accessible menu has a child menu, let's filter that recursively - - Set childMenus = menuItem.getChildMenus(); - if (childMenus != null && childMenus.size() > 0) { - filterMenu(childMenus, request); - } - - } - } - - return menus; - } - - - public static String getUrlHtml(MenuData menuData) { - String html = ""; - - if (menuData.getExternalUrl() != null && menuData.getExternalUrl().length() > 0) { - html = menuData.getExternalUrl(); - } - else if (menuData.getServlet() != null && menuData.getServlet().length() > 0) { - html = "/" + menuData.getServlet(); - } - else if (menuData.getAction() != null && menuData.getAction().length() > 0) { - html = "/" + menuData.getAction(); - } - - return html; - } - - - public static String getTargetHtml(MenuData menuData) { - String html = ""; - - if (menuData.getTarget() != null && menuData.getTarget().length() > 0) { - html = "target=\"" + menuData.getTarget() + "\""; - } - - return html; - } - - - public static String getQueryStringHtml(MenuData menuData) { - String html = ""; - - if (menuData.getQueryString() != null && menuData.getQueryString().length() > 0) { - html = "?" + menuData.getQueryString(); - } - - return html; - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - -} - - diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/menu/MenuProperties.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/menu/MenuProperties.java deleted file mode 100644 index 007a7f30..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/menu/MenuProperties.java +++ /dev/null @@ -1,114 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.menu; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Properties; - -import javax.servlet.ServletContext; - -import org.openecomp.portalsdk.core.util.SystemProperties; - - -/* - MenuProperties contains a list of constants used during the creation, - privilege screening, and rendering of the application menu. -*/ -public class MenuProperties { - private MenuProperties() { - // cannot instantiate - } - - @SuppressWarnings("rawtypes") - private static HashMap menuProperties = new HashMap(); - - // keys used to reference values in the menu.properties file - public static final String WIDTH = "width"; - public static final String LEFT_POSITION = "left_position"; - public static final String TOP_POSITION = "top_position"; - public static final String FONT_COLOR = "font_color"; - public static final String MOUSEOVER_FONT_COLOR = "mouseover_font_color"; - public static final String BACKGROUND_COLOR = "background_color"; - public static final String MOUSEOVER_BACKGROUND_COLOR = "mouseover_background_color"; - public static final String BORDER_COLOR = "border_color"; - public static final String SEPARATOR_COLOR = "separator_color"; - public static final String IMAGE_SRC = "image_src"; - public static final String IMAGE_SRC_LEFT = "image_src_left"; - public static final String IMAGE_SRC_OVER = "image_src_over"; - public static final String IMAGE_SRC_LEFT_OVER = "image_src_left_over"; - public static final String EVALUATE_UPON_TREE_SHOW = "evaluate_upon_tree_show"; - public static final String EVALUATE_UPON_TREE_HIDE = "evaluate_upon_tree_hide"; - public static final String TOP_IS_PERMANENT = "top_is_permanent"; - public static final String TOP_IS_HORIZONTAL = "top_is_horizontal"; - public static final String TREE_IS_HORIZONTAL = "tree_is_horizontal"; - public static final String POSITION_UNDER = "position_under"; - public static final String TOP_MORE_IMAGES_VISIBLE = "top_more_images_visible"; - public static final String TREE_MORE_IMAGES_VISIBLE = "tree_more_images_visible"; - public static final String RIGHT_TO_LEFT = "right_to_left"; - public static final String DISPLAY_ON_CLICK = "display_on_click"; - public static final String TOP_IS_VARIABLE_WIDTH = "top_is_variable_width"; - public static final String TREE_IS_VARIABLE_WIDTH = "tree_is_variable_width"; - public static final String TOP_KEEP_IN_WINDOW_X = "top_keep_in_window_x"; - public static final String TOP_KEEP_IN_WINDOW_Y = "top_keep_in_window_y"; - public static final String MENU_ID_ADMIN = "menu_id_admin"; - public static final String MENU_ID_LOGOUT = "menu_id_logout"; - public static final String MENU_FRAME = "menu_frame"; - public static final String MAIN_FRAME = "main_frame"; - public static final String NESTED_MAIN_FRAME = "nested_main_frame"; - public static final String ROLE_FUNCTIONS_TAG = "role_functions_tag"; - - public static final String MAX_DISPLAYABLE_ADMIN_MENU_SORT_ORDER = "max_displayable_admin_menu_sort_order"; - public static final String MENU_PROPERTIES_FILENAME_KEY = "menu_properties_filename"; - public static final String DEFAULT_SERVLET_NAME = "dispatcher"; - public static final String DEFAULT_TARGET = "_self"; - - public static final String TOP_MENU_CLASS = "top_menu_class"; - public static final String TOP_MENU_LINK_CLASS = "top_menu_link_class"; - - public static final String ON_MOUSE_OUT_TRAILER = "on_mouse_out_trailer"; - public static final String ON_MOUSE_OVER_TRAILER = "on_mouse_over_trailer"; - public static final String ON_CLICK_TRAILER = "on_click_trailer"; - - public static final String MENU_ID_PREFIX = "menu_id_prefix"; - - - @SuppressWarnings("unchecked") -public static void loadFromFile(ServletContext servletContext, String filename, String menuSetName) throws IOException { - Properties p = new Properties(); - - if (filename == null) { - filename = SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_PROPERTIES_NAME); - } - - p.load(servletContext.getResourceAsStream(SystemProperties.getProperty(SystemProperties.MENU_PROPERTIES_FILE_LOCATION) + filename)); - menuProperties.put(menuSetName, p); - } // loadMenuProperties - - public static String getProperty(String key) { - return getProperty(key, SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME)); - } - - public static String getProperty(String key, String menuSetName) { - Properties p = (Properties)menuProperties.get(menuSetName); - return p.getProperty(key); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/AbstractCacheManager.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/AbstractCacheManager.java deleted file mode 100644 index 6fb56d9d..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/AbstractCacheManager.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.objectcache; - -import java.io.IOException; - -import org.openecomp.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 void putObject(String key, Object objectToCache) { - // TODO Auto-generated method stub - } - - public boolean isObjectInCache(String key) { - // TODO Auto-generated method stub - return false; - } - - public void removeObject(String key) { - // TODO Auto-generated method stub - } - - public void clearCache() { - // TODO Auto-generated method stub - } - - public void configure() throws IOException { - // TODO Auto-generated method stub - - } -} - diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java deleted file mode 100644 index 0695876f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.objectcache.jcs; - -import org.apache.jcs.engine.control.event.behavior.IElementEvent; -import org.apache.jcs.engine.control.event.behavior.IElementEventConstants; -import org.apache.jcs.engine.control.event.behavior.IElementEventHandler; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; - -public class JCSCacheEventHandler implements IElementEventHandler, IElementEventConstants { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JCSCacheEventHandler.class); - - public JCSCacheEventHandler() { - super(); - } - - public void handleElementEvent(IElementEvent event) { - // Handle code for various event notifications on cached elements by JCS. - switch (event.getElementEvent()) { - case ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND: - logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND occurred for element " + event); - break; - case ELEMENT_EVENT_EXCEEDED_MAXLIFE_ONREQUEST: - logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_MAXLIFE_ONREQUEST occurred for element " + event); - break; - case ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND: - logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND occurred for element " + event); - break; - case ELEMENT_EVENT_EXCEEDED_IDLETIME_ONREQUEST: - logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_IDLETIME_ONREQUEST occurred for element " + event); - break; - case ELEMENT_EVENT_SPOOLED_DISK_AVAILABLE: - logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_DISK_AVAILABLE occurred for element " + event); - break; - case ELEMENT_EVENT_SPOOLED_DISK_NOT_AVAILABLE: - logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_DISK_NOT_AVAILABLE occurred for element " + event); - break; - case ELEMENT_EVENT_SPOOLED_NOT_ALLOWED: - logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_NOT_ALLOWED occurred for element " + event); - } - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheManager.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheManager.java deleted file mode 100644 index 39b3f0cb..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/jcs/JCSCacheManager.java +++ /dev/null @@ -1,186 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.objectcache.jcs; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.Vector; - -import javax.annotation.PostConstruct; -import javax.servlet.ServletContext; - -import org.apache.jcs.JCS; -import org.apache.jcs.access.exception.CacheException; -import org.apache.jcs.engine.CacheConstants; -import org.apache.jcs.engine.behavior.IElementAttributes; -import org.apache.jcs.engine.control.CompositeCacheManager; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.web.context.ServletContextAware; - -public abstract class JCSCacheManager extends AbstractCacheManager implements CacheConstants, ServletContextAware { - - public static String LOOKUP_OBJECT_CACHE_NAME = "lookUpObjectCache"; - public static String JCS_CONFIG_FILE_PATH = "cache_config_file_path"; - public static String CACHE_LOAD_ON_STARTUP = "cache_load_on_startup"; - public static String CACHE_PROPERTY_VALUE_TRUE = "true"; - public static String CACHE_CONTROL_SWITCH_ON = "1"; - public static String CACHE_CONTROL_SWITCH_OFF = "0"; - public static String CACHE_CONTROL_SWITCH = "cache_switch"; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JCSCacheManager.class); - - private static JCS lookUpCache; - private ServletContext servletContext; - - private Properties cacheConfigProperties = null; - private final Vector<String> jscManagedCacheList = new Vector<String>(); - - private DataAccessService dataAccessService; - - public JCSCacheManager() { - super(); - jscManagedCacheList.add(LOOKUP_OBJECT_CACHE_NAME); - } - - @PostConstruct - public void configure() throws IOException { - super.configure(); - - String jcsConfigFilePath = SystemProperties.getProperty(JCS_CONFIG_FILE_PATH); - // getProperty throws if the key is missing; but check anyhow. - if (jcsConfigFilePath == null || jcsConfigFilePath.length() == 0) - throw new IOException("configure: failed to get value for config property " + JCS_CONFIG_FILE_PATH); - InputStream jcsConfigInputStream = getServletContext().getResourceAsStream(jcsConfigFilePath); - if (jcsConfigInputStream == null) - throw new IOException("configure: failed to open stream for config property " + JCS_CONFIG_FILE_PATH - + " with name " + jcsConfigFilePath); - logger.debug(EELFLoggerDelegate.debugLogger, - "configure: loading cache properties from classpath resource {} ", jcsConfigFilePath); - Properties p = new Properties(); - p.load(jcsConfigInputStream); - jcsConfigInputStream.close(); - - CompositeCacheManager ccm = CompositeCacheManager.getUnconfiguredInstance(); - ccm.configure(p); - setCacheConfigProperties(p); - - try { - initializeLookUpCache(); - } catch (CacheException ce) { - throw new IOException("configure: failed to initialize lookup cache", ce); - } - - } - - private void initializeLookUpCache() throws CacheException { - lookUpCache = JCS.getInstance(LOOKUP_OBJECT_CACHE_NAME); - - JCSCacheEventHandler eventHandler = new JCSCacheEventHandler(); - IElementAttributes elementAttributes = lookUpCache.getDefaultElementAttributes(); - - elementAttributes.addElementEventHandler(eventHandler); - - lookUpCache.setDefaultElementAttributes(elementAttributes); - - if (CACHE_PROPERTY_VALUE_TRUE.equalsIgnoreCase(SystemProperties.getProperty(CACHE_LOAD_ON_STARTUP))) { - loadDataOnStartUp(); - } - } - - public Object getObject(String key) { - if (CACHE_CONTROL_SWITCH_ON.equalsIgnoreCase(SystemProperties.getProperty(CACHE_CONTROL_SWITCH))) { - if (lookUpCache == null) - return null; - else - return lookUpCache.get(key); - } else - return null; - } - - public void putObject(String key, Object objectToCache) { - try { - if (CACHE_CONTROL_SWITCH_ON.equalsIgnoreCase(SystemProperties.getProperty(CACHE_CONTROL_SWITCH))) { - if (lookUpCache != null) { - lookUpCache.put(key, objectToCache); - } - } - } catch (CacheException ce) { - logger.error(EELFLoggerDelegate.errorLogger, "putObject: failed to put the object with key " + key, ce); - } - } - - public void clearCache(String region) { - try { - if (region.equals(LOOKUP_OBJECT_CACHE_NAME)) - lookUpCache.clear(); - } catch (CacheException ce) { - logger.error(EELFLoggerDelegate.errorLogger, - "clearCache: failed to clear the cache for the region " + region, ce); - } - } - - public void clearCache() { - clearCache(LOOKUP_OBJECT_CACHE_NAME); - } - - private void loadDataOnStartUp() { - loadLookUpCache(); - } - - public abstract void loadLookUpCache(); - - public void refreshLookUpCache() { - clearCache(LOOKUP_OBJECT_CACHE_NAME); - loadLookUpCache(); - } - - public Properties getCacheConfigProperties() { - return cacheConfigProperties; - } - - public void setCacheConfigProperties(Properties cacheConfigProperties) { - this.cacheConfigProperties = cacheConfigProperties; - } - - public Vector<String> getJscManagedCacheList() { - return jscManagedCacheList; - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - public ServletContext getServletContext() { - return servletContext; - } - - public void setServletContext(ServletContext servletContext) { - this.servletContext = servletContext; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/support/FusionCacheManager.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/support/FusionCacheManager.java deleted file mode 100644 index 01cc9ce0..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/objectcache/support/FusionCacheManager.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.objectcache.support; - -import java.io.IOException; - -import org.openecomp.portalsdk.core.FusionObject; - -public interface FusionCacheManager extends FusionObject { - - Object getObject(String key); - void putObject(String key, Object objectToCache); - boolean isObjectInCache(String key); - - void removeObject(String key); - void clearCache(); - void configure() throws IOException; -} - diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/client/AppContextManager.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/client/AppContextManager.java deleted file mode 100644 index 0e564457..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/client/AppContextManager.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.onboarding.client; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.stereotype.Component; - -/** - * - * - * Use this class to get access to ApplicationContext for classes who were not created by Spring. - */ - - -@Component -public class AppContextManager implements ApplicationContextAware{ - private static ApplicationContext _appCtx; - - @Override - public void setApplicationContext(ApplicationContext ctx){ - _appCtx = ctx; - } - - public static ApplicationContext getAppContext(){ - return _appCtx; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/client/OnBoardingApiServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/client/OnBoardingApiServiceImpl.java deleted file mode 100644 index 1d71afd6..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/client/OnBoardingApiServiceImpl.java +++ /dev/null @@ -1,316 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.onboarding.client; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.domain.UserApp; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIException; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler; -import org.openecomp.portalsdk.core.restful.domain.EcompRole; -import org.openecomp.portalsdk.core.restful.domain.EcompUser; -import org.openecomp.portalsdk.core.service.RoleService; -import org.openecomp.portalsdk.core.service.UserProfileService; -import org.openecomp.portalsdk.core.service.WebServiceCallService; -import org.openecomp.portalsdk.core.util.JSONUtil; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.slf4j.MDC; -import org.springframework.context.ApplicationContext; - -/** - * Implements the REST API interface to answer requests made by Portal app about - * users and active sessions. - * - * Since an instance of this class will be instantiated by the OnBoarding - * servlet from the ecompFW library, we cannot use Spring injections here. This - * 'injection' is done indirectly using AppContextManager class. - * - - */ -@SuppressWarnings("rawtypes") -public class OnBoardingApiServiceImpl implements IPortalRestAPIService { - RoleService roleService; - UserProfileService userProfileService; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(OnBoardingApiServiceImpl.class); - - public OnBoardingApiServiceImpl() { - // Defend against null-pointer exception during server startup - // that was caused by a spurious Spring annotation on this class. - ApplicationContext appContext = AppContextManager.getAppContext(); - if (appContext == null) - throw new RuntimeException("OnBoardingApiServiceImpl ctor failed to get appContext"); - roleService = appContext.getBean(RoleService.class); - userProfileService = appContext.getBean(UserProfileService.class); - } - - private void setCurrentAttributes(User user, EcompUser userJson) { - - user.setEmail(userJson.getEmail()); - user.setFirstName(userJson.getFirstName()); - user.setHrid(userJson.getHrid()); - user.setJobTitle(userJson.getJobTitle()); - user.setLastName(userJson.getLastName()); - user.setLoginId(userJson.getLoginId()); - user.setOrgManagerUserId(userJson.getOrgManagerUserId()); - user.setMiddleInitial(userJson.getMiddleInitial()); - user.setOrgCode(userJson.getOrgCode()); - user.setOrgId(userJson.getOrgId()); - user.setPhone(userJson.getPhone()); - user.setOrgUserId(userJson.getOrgUserId()); - user.setActive(userJson.isActive()); - // user.setRoles(new TreeSet(userJson.getRoles())); - } - - @Override - public void pushUser(EcompUser userJson) throws PortalAPIException { - - if (logger.isDebugEnabled()) - logger.debug(EELFLoggerDelegate.debugLogger, "pushUser was invoked: " + userJson); - User user = new User(); - String response = ""; - try { - // Set input attributes to the object obout to be saved - setCurrentAttributes(user, userJson); - user.setRoles(new TreeSet<Role>()); - user.setUserApps(new TreeSet()); - user.setPseudoRoles(new TreeSet()); - userProfileService.saveUser(user); - logger.debug(EELFLoggerDelegate.debugLogger, "push user success."); - response = "push user success."; - response = JSONUtil.convertResponseToJSON(response); - } catch (Exception e) { - response = "OnboardingApiService.pushUser failed"; - logger.error(EELFLoggerDelegate.errorLogger, response, e); - throw new PortalAPIException(response, e); - } finally { - MDC.remove(SystemProperties.MDC_TIMER); - } - } - - @Override - public void editUser(String loginId, EcompUser userJson) throws PortalAPIException { - - if (logger.isDebugEnabled()) - logger.debug(EELFLoggerDelegate.debugLogger, "OnboardingApi editUser was invoked with loginID " + loginId + ", JSON: " + userJson); - User editUser = new User(); - String response = ""; - try { - setCurrentAttributes(editUser, userJson); - if (editUser.getOrgUserId() != null) { - editUser.setLoginId(editUser.getOrgUserId()); - } - User domainUser = userProfileService.getUserByLoginId(loginId); - if (domainUser != null) - domainUser = JSONUtil.mapToDomainUser(domainUser, editUser); - else - domainUser = editUser; - userProfileService.saveUser(domainUser); - logger.debug(EELFLoggerDelegate.debugLogger, "edit user success."); - response = "edit user success."; - response = JSONUtil.convertResponseToJSON(response); - } catch (Exception e) { - response = "OnboardingApiService.editUser failed"; - logger.error(EELFLoggerDelegate.errorLogger, response, e); - throw new PortalAPIException(response, e); - } finally { - MDC.remove(SystemProperties.MDC_TIMER); - } - - // return response; - } - - @Override - public EcompUser getUser(String loginId) throws PortalAPIException { - try { - if (logger.isDebugEnabled()) - logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: " + loginId); - User user = userProfileService.getUserByLoginId(loginId); - if (user == null) { - logger.info(EELFLoggerDelegate.debugLogger, "User + " + loginId + " doesn't exist"); - return null; - // Unforunately, Portal is not ready to accept proper error - // response yet .. - // commenting throw clauses until portal is ready - // throw new PortalAPIException("User + " + loginId + " doesn't - // exist"); - } else - return UserUtils.convertToEcompUser(user); - } catch (Exception e) { - String response = "OnboardingApiService.getUser failed"; - logger.error(EELFLoggerDelegate.errorLogger, response, e); - return null; - // Unforunately, Portal is not ready to accept proper error response - // yet .. commenting throw clauses until portal is ready - // throw new PortalAPIException(response, e); - } - - } - - @Override - public List<EcompUser> getUsers() throws PortalAPIException { - try { - List<User> users = userProfileService.findAllActive(); - List<EcompUser> ecompUsers = new ArrayList<EcompUser>(); - for (User user : users) - ecompUsers.add(UserUtils.convertToEcompUser(user)); - return ecompUsers; - } catch (Exception e) { - String response = "OnboardingApiService.getUsers failed"; - logger.error(EELFLoggerDelegate.errorLogger, response, e); - throw new PortalAPIException(response, e); - } - } - - @Override - public List<EcompRole> getAvailableRoles() throws PortalAPIException { - try { - List<Role> roles = roleService.getActiveRoles(); - List<EcompRole> ecompRoles = new ArrayList<EcompRole>(); - for (Role role : roles) - ecompRoles.add(UserUtils.convertToEcompRole(role)); - return ecompRoles; - } catch (Exception e) { - String response = "OnboardingApiService.getAvailableRoles failed"; - logger.error(EELFLoggerDelegate.errorLogger, response, e); - throw new PortalAPIException(response, e); - } - } - - @Override - public void pushUserRole(String loginId, List<EcompRole> rolesJson) throws PortalAPIException { - String response = ""; - try { - logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: " + loginId); - logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## rolesJson: " + rolesJson); - User user = userProfileService.getUserByLoginId(loginId); - /* - * List<EcompRole> ecompRoles = mapper.readValue(rolesJson, - * TypeFactory.defaultInstance().constructCollectionType(List.class, - * EcompRole.class)); - */ - SortedSet<Role> roles = new TreeSet<Role>(); - for (EcompRole role : rolesJson) { - roles.add(roleService.getRole(role.getId())); - } - // Replace existing roles with new ones - replaceExistingRoles(roles, user); - - logger.debug(EELFLoggerDelegate.debugLogger, "push user role success."); - response = "push user role success."; - response = JSONUtil.convertResponseToJSON(response); - - } catch (Exception e) { - response = "OnboardingApiService.pushUserRole failed"; - logger.error(EELFLoggerDelegate.errorLogger, response, e); - throw new PortalAPIException(response, e); - } finally { - MDC.remove(SystemProperties.MDC_TIMER); - } - - } - - @Override - public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException { - if (logger.isDebugEnabled()) - logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: " + loginId); - List<EcompRole> ecompRoles = new ArrayList<EcompRole>(); - try { - User user = userProfileService.getUserByLoginId(loginId); - SortedSet<Role> currentRoles = null; - if (user != null) { - currentRoles = user.getRoles(); - if (currentRoles != null) - for (Role role : currentRoles) - ecompRoles.add(UserUtils.convertToEcompRole(role)); - } - return ecompRoles; - } catch (Exception e) { - String response = "OnboardingApiService.getUserRoles failed"; - logger.error(EELFLoggerDelegate.errorLogger, response, e); - throw new PortalAPIException(response, e); - } - } - - @SuppressWarnings("unchecked") - private void replaceExistingRoles(SortedSet<Role> roles, User user) { - // 1. remove existing roles - Set<UserApp> userApps = user.getUserApps(); - Iterator appsItr = userApps.iterator(); - while (appsItr.hasNext()) { - UserApp tempUserApp = (UserApp) appsItr.next(); - boolean roleFound = false; - for (Role role : roles) { - if (tempUserApp.getRole().getId().equals(role.getId())) { - roleFound = true; - break; - } - } - if (!roleFound) - appsItr.remove(); - } - user.setUserApps(userApps); - userProfileService.saveUser(user); - - // 2. add new roles - user.setRoles(roles); - userProfileService.saveUser(user); - } - - @Override - public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException { - WebServiceCallService securityService = AppContextManager.getAppContext().getBean(WebServiceCallService.class); - try { - String appUser = request.getHeader("username"); - String password = request.getHeader("password"); - // System.out.println("username = " + appUser); - // System.out.println("password = " + password); - boolean flag = securityService.verifyRESTCredential(null, appUser, password); - // System.out.println("username = " + appUser); - // System.out.println("password = " + password); - return flag; - - } catch (Exception e) { - String response = "OnboardingApiService.isAppAuthenticated failed"; - logger.error(EELFLoggerDelegate.errorLogger, response, e); - throw new PortalAPIException(response, e); - } - } - - public String getSessionTimeOuts() throws Exception { - return PortalTimeoutHandler.gatherSessionExtensions(); - } - - public void updateSessionTimeOuts(String sessionMap) throws Exception { - PortalTimeoutHandler.updateSessionExtensions(sessionMap); - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/session/TestClass.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/session/TestClass.java deleted file mode 100644 index 6bbf8c1d..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/session/TestClass.java +++ /dev/null @@ -1,24 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.onboarding.session; - -public class TestClass { - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/sso/TestClass.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/sso/TestClass.java deleted file mode 100644 index ccd903a9..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/onboarding/sso/TestClass.java +++ /dev/null @@ -1,24 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.onboarding.sso; - -public class TestClass { - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/restful/client/HttpStatusAndResponse.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/restful/client/HttpStatusAndResponse.java deleted file mode 100644 index a8242234..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/restful/client/HttpStatusAndResponse.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.restful.client; - -/** - * Holds the status code and body that result from accessing an HTTP URL. - */ -public class HttpStatusAndResponse { - - private int statusCode; - private String response; - - public HttpStatusAndResponse(int status, String resp) { - this.statusCode = status; - this.response = resp; - } - - public int getStatusCode() { - return statusCode; - } - - public String getResponse() { - return response; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/restful/client/PortalRestClientBase.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/restful/client/PortalRestClientBase.java deleted file mode 100644 index a7c517ec..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/restful/client/PortalRestClientBase.java +++ /dev/null @@ -1,171 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.restful.client; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import javax.servlet.http.HttpServletResponse; - -import org.apache.http.Consts; -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.openecomp.portalsdk.core.domain.App; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; -import org.openecomp.portalsdk.core.service.AppService; -import org.openecomp.portalsdk.core.util.CipherUtil; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -/** - * Provides a basic client to access a REST endpoint at the Portal via get or - * post. Usage caveats: - * <OL> - * <LI>Must be auto-wired by Spring, because this in turn auto-wires a - * data-access service to read application credentials from the FN_APP table. - * <LI>If HTTP access is used and the server uses a self-signed certificate, the - * local trust store must be extended appropriately. The HTTP client throws - * exceptions if the JVM cannot validate the server certificate. - * </OL> - */ -@Component -public class PortalRestClientBase { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalRestClientBase.class); - - @Autowired - AppService appService; - - /** - * Constructs and sends a GET request for the URI, with REST application - * credentials in the header as the Portal expects. - * - * @param uri - * URI of the service - * @return Result of the get; null if an error happens - * @throws URISyntaxException - * @throws IOException - * @throws ClientProtocolException - */ - public HttpStatusAndResponse getRestWithCredentials(final URI uri) throws Exception { - - String uebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); - App app = appService.getDefaultApp(); - if (uebKey == null || app == null || app.getUsername() == null || app.getAppPassword() == null) - throw new Exception("Missing one or more required properties and/or database entries"); - String decryptedPassword = CipherUtil.decrypt(app.getAppPassword()); - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet httpGet = new HttpGet(uri); - httpGet.setHeader("uebkey", uebKey); - httpGet.setHeader("username", app.getUsername()); - httpGet.setHeader("password", decryptedPassword); - - String responseJson = null; - CloseableHttpResponse response = null; - try { - logger.info(EELFLoggerDelegate.debugLogger, "GET from " + uri); - response = httpClient.execute(httpGet); - logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine()); - if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) - logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine().toString()); - HttpEntity entity = response.getEntity(); - if (entity == null) { - logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!"); - } else { - // entity content length is never set. - // this naively tries to read everything. - responseJson = EntityUtils.toString(entity); - logger.info(EELFLoggerDelegate.debugLogger, responseJson); - EntityUtils.consume(entity); - } - } finally { - if (response != null) - response.close(); - } - if (response == null) - return null; - return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson); - } - - /** - * Constructs and sends a POST request using the specified body, with REST - * application credentials in the header as the Portal expects. - * - * @param uri - * REST endpoint - * @param json - * Content to post - * @return Result of the post; null if an error happens - * @throws Exception - */ - public HttpStatusAndResponse postRestWithCredentials(final URI uri, final String json) throws Exception { - - String uebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); - App app = appService.getDefaultApp(); - if (uebKey == null || app == null || app.getUsername() == null || app.getAppPassword() == null) - throw new Exception("Missing one or more required properties and/or database entries"); - - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost httpPost = new HttpPost(uri); - httpPost.setHeader("uebkey", uebKey); - httpPost.setHeader("username", app.getUsername()); - httpPost.setHeader("password", app.getAppPassword()); - - StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8)); - httpPost.setEntity(postEntity); - - String responseJson = null; - CloseableHttpResponse response = null; - try { - logger.info(EELFLoggerDelegate.debugLogger, "POST to " + uri); - response = httpClient.execute(httpPost); - logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine()); - if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) - throw new Exception("Status is " + response.getStatusLine().toString()); - - HttpEntity entity = response.getEntity(); - if (entity == null) { - logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!"); - } else { - // entity content length is never set. - // this naively tries to read everything. - responseJson = EntityUtils.toString(entity); - logger.info(EELFLoggerDelegate.debugLogger, responseJson); - EntityUtils.consume(entity); - } - } finally { - if (response != null) - response.close(); - } - return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/restful/client/SharedContextRestClient.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/restful/client/SharedContextRestClient.java deleted file mode 100644 index f017a7df..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/restful/client/SharedContextRestClient.java +++ /dev/null @@ -1,330 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.restful.client; - -import java.net.URI; -import java.util.HashMap; -import java.util.List; - -import org.apache.http.client.utils.URIBuilder; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; -import org.openecomp.portalsdk.core.restful.domain.SharedContext; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * Provides convenience methods to use the shared-context service at Portal. - * This hides all JSON; instead it accepts and returns Java objects. - * Usage caveats (repeated from superclass): - * <OL> - * <LI>Must be auto-wired by Spring, because this in turn auto-wires a data - * access service to read application credentials from the FN_APP table. - * <LI>If HTTP access is used and the server uses a self-signed certificate, the - * local trust store must be extended appropriately. The HTTP client throws - * exceptions if the JVM cannot validate the server certificate. - * </OL> - */ -@Component -public class SharedContextRestClient extends PortalRestClientBase { - - @Autowired - SystemProperties systemProperties; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestClient.class); - - /** - * Reusable JSON (de)serializer - */ - private final ObjectMapper mapper = new ObjectMapper(); - - /** - * Gets the shared-context value for the specified context ID and key. - * - * @param contextId - * An Ecomp Portal session ID - * @param key - * Key for the shared-context entry; e.g., "lastName" - * @return SharedContext object; null if not found. - * @throws Exception - */ - public SharedContext getContextValue(String contextId, String key) throws Exception { - HttpStatusAndResponse hsr = getContext("get", contextId, key); - logger.info(EELFLoggerDelegate.debugLogger, "getSharedContext: resp is " + hsr); - if (hsr == null) { - logger.error(EELFLoggerDelegate.applicationLogger, "getContextValue: unexpected null response"); - return null; - } - SharedContext jsonObj = null; - try { - jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); - } catch (JsonMappingException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "getContextValue: failed to map response onto object" + ex.getMessage()); - } catch (JsonParseException ex) { - logger.info(EELFLoggerDelegate.applicationLogger, "getContextValue: failed to parse response" + ex.getMessage()); - } - if (jsonObj != null && jsonObj.getResponse() != null) - return null; - return jsonObj; - } - - /** - * Gets user information for the specified context ID. - * - * @param contextId - * An Ecomp Portal session ID - * @return List of SharedContext objects corresponding to the following - * keys: USER_FIRST_NAME, USER_LAST_NAME, USER_EMAIL and - * USER_ORGUSERID; empty if none were found; null if an error happens. - * @throws Exception - */ - public List<SharedContext> getUserContext(String contextId) throws Exception { - HttpStatusAndResponse hsr = getContext("get_user", contextId, null); - logger.info(EELFLoggerDelegate.debugLogger, "getUserContext: resp is " + hsr); - if (hsr == null) { - logger.error(EELFLoggerDelegate.applicationLogger, "getUserContext: unexpected null response"); - return null; - } - List<SharedContext> jsonList = null; - try { - TypeReference<List<SharedContext>> typeRef = new TypeReference<List<SharedContext>>() { - }; - jsonList = mapper.readValue(hsr.getResponse(), typeRef); - } catch (JsonMappingException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "getUserContext: failed to map response onto object" + ex.getMessage()); - } catch (JsonParseException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "getUserContext: failed to parse response" + ex.getMessage()); - } - return jsonList; - } - - /** - * Checks whether a shared-context entry exists for the specified context ID - * and key. - * - * @param contextId - * An Ecomp Portal session ID - * @param key - * Key for the shared-context entry; e.g., "lastName" - * @return True if the object exists, false otherwise; null on error. - * @throws Exception - */ - public Boolean checkSharedContext(String contextId, String key) throws Exception { - HttpStatusAndResponse hsr = getContext("check", contextId, key); - logger.info(EELFLoggerDelegate.debugLogger, "checkSharedContext: resp is " + hsr); - if (hsr == null) { - logger.error(EELFLoggerDelegate.applicationLogger, "checkSharedContext: unexpected null response"); - return null; - } - String response = null; - try { - SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); - response = jsonObj.getResponse(); - } catch (JsonMappingException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "checkSharedContext: failed to map response onto object" + ex.getMessage()); - } catch (JsonParseException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "checkSharedContext: failed to parse response" + ex.getMessage()); - } - if (response == null) - return null; - return ("exists".equals(response)); - } - - /** - * Removes a shared-context entry with the specified context ID and key. - * - * @param contextId - * An Ecomp Portal session ID - * @param key - * Key for the shared-context entry; e.g., "lastName" - * @return True if the entry was removed, false otherwise; null on error. - * @throws Exception - */ - public Boolean removeSharedContext(String contextId, String key) throws Exception { - HttpStatusAndResponse hsr = getContext("remove", contextId, key); - logger.info(EELFLoggerDelegate.debugLogger, "removeSharedContext: resp is " + hsr); - if (hsr == null) { - logger.error(EELFLoggerDelegate.applicationLogger, "removeSharedContext: unexpected null response"); - return null; - } - SharedContext jsonObj = null; - try { - jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); - } catch (JsonMappingException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "removeSharedContext: failed to map response onto object" + ex.getMessage()); - } catch (JsonParseException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "removeSharedContext: failed to parse response" + ex.getMessage()); - } - if (jsonObj == null) - return null; - String response = jsonObj.getResponse(); - return ("removed".equals(response)); - } - - /** - * Clears the shared context for the specified context ID; i.e., removes all - * key-value pairs. - * - * @param contextId - * An Ecomp Portal session ID - * @return Number of key-value pairs removed; -1 if not found or any - * problems occur. - * @throws Exception - */ - public int clearSharedContext(String contextId) throws Exception { - HttpStatusAndResponse hsr = getContext("remove", contextId, null); - logger.info(EELFLoggerDelegate.debugLogger, "clearSharedContext: resp is " + hsr); - if (hsr == null) { - logger.error(EELFLoggerDelegate.applicationLogger, "clearSharedContext: unexpected null response"); - return -1; - } - SharedContext jsonObj = null; - try { - jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); - } catch (JsonMappingException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "clearSharedContext: failed to map response onto object" + ex.getMessage()); - } catch (JsonParseException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "clearSharedContext: failed to parse response" + ex.getMessage()); - } - if (jsonObj == null) - return -1; - String response = jsonObj.getResponse(); - if (response == null) - return -1; - return Integer.parseInt(response); - } - - /** - * Creates a shared-context entry. - * - * @param contextId - * An Ecomp Portal session ID - * @param key - * Key for the shared-context entry; e.g., "lastName" - * @param value - * Value for the entry - * @throws Exception - * @return True if the object previously existed, false otherwise; null if - * any problem happened. - */ - public Boolean setSharedContext(String contextId, String key, String value) throws Exception { - String body = buildContext(contextId, key, value); - HttpStatusAndResponse hsr = postContext("set", body); - logger.info(EELFLoggerDelegate.debugLogger, "setSharedContext: resp is " + hsr); - if (hsr == null) { - logger.error(EELFLoggerDelegate.applicationLogger, "setSharedContext: unexpected null response"); - return null; - } - SharedContext jsonObj = null; - try { - jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class); - } catch (JsonMappingException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "setSharedContext: failed to map response onto object" + ex.getMessage()); - } catch (JsonParseException ex) { - logger.error(EELFLoggerDelegate.applicationLogger, "setSharedContext: failed to parse response" + ex.getMessage()); - } - if (jsonObj == null) - return null; - String response = jsonObj.getResponse(); - return ("replaced".equals(response)); - } - - /** - * Builds the full URL with the specified parameters, then calls the method - * that adds credentials and GETs. - * - * @param requestPath - * @param contextId - * @param contextKey - * @return HttpStatusAndResponse object; may be null. - * @throws Exception - */ - @SuppressWarnings("unused") - private HttpStatusAndResponse getContext(String requestPath, String contextId, String contextKey) throws Exception{ - String restUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL); - String portalDomain = restUrl.substring(0, restUrl.lastIndexOf('/')); - String contextRestUrl = portalDomain + "/context"; - if (contextRestUrl == null) - throw new Exception("getContext: failed to get property " + SystemProperties.ECOMP_SHARED_CONTEXT_REST_URL); - URIBuilder uriBuilder = new URIBuilder(contextRestUrl + "/" + requestPath); - uriBuilder.addParameter("context_id", contextId); - if (contextKey != null) - uriBuilder.addParameter("ckey", contextKey); - final URI uri = uriBuilder.build(); - return getRestWithCredentials(uri); - } - - /** - * Builds the full URL, then calls the method that adds credentials and - * POSTs. - * - * @param requestPath - * @param contextId - * @param contextKey - * @return HttpStatusAndResponse object; may be null. - * @throws Exception - */ - private HttpStatusAndResponse postContext(String requestPath, String json) throws Exception { - String contextRestUrl = SystemProperties.getProperty(SystemProperties.ECOMP_SHARED_CONTEXT_REST_URL); - if (contextRestUrl == null) - throw new Exception("postContext: failed to get property " + SystemProperties.ECOMP_SHARED_CONTEXT_REST_URL); - URIBuilder uriBuilder = new URIBuilder(contextRestUrl + "/" + requestPath); - URI uri = uriBuilder.build(); - return postRestWithCredentials(uri, json); - } - - /** - * Builds a JSON block with a single shared-context entry. - * - * @param cxid - * Context ID - * @param ckey - * Context Key - * @param cvalue - * Context value - * @return JSON block - */ - private String buildContext(String cxid, String ckey, String cvalue) throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> stringMap = new HashMap<String, String>(); - stringMap.put("context_id", cxid); - stringMap.put("ckey", ckey); - stringMap.put("cvalue", cvalue); - String json = mapper.writeValueAsString(stringMap); - return json; - } - - // Simple test scaffold - public static void main(String[] args) throws Exception { - - SharedContextRestClient client = new SharedContextRestClient(); - SharedContext get = client.getContextValue("abc", "123"); - System.out.println("Get yields " + get.toString()); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/scheduler/CoreRegister.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/scheduler/CoreRegister.java deleted file mode 100644 index 5f81308f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/scheduler/CoreRegister.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.scheduler; - -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.quartz.CronTrigger; -import org.quartz.Trigger; -import org.springframework.context.annotation.DependsOn; -import org.springframework.stereotype.Component; - -@Component -@DependsOn({"systemProperties"}) -public class CoreRegister { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CoreRegister.class); - Trigger trigger[] = new Trigger[1]; - - - - //@Autowired - //private SessionMgtRegistry sessionMgtRegistry; - - protected List<Trigger> scheduleTriggers = new ArrayList<Trigger>(); - - - public void registerTriggers() { - // we can use this method to add any schedules to the core - - /* - try { - if(SystemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON) != null) - getScheduleTriggers().add(sessionMgtRegistry.getTrigger()); - - } catch(IllegalStateException ies) { - logger.info("Session Timout Cron not available"); - } - */ - - } - - protected void addTrigger(final String cron, final CronTrigger cronRegistryTrigger) { - // if the property value is not available; the cron will not be added and can be ignored. its safe to ignore the exceptions - - try { - - if(SystemProperties.getProperty(cron) != null) { - getScheduleTriggers().add(cronRegistryTrigger); - } - - } catch(IllegalStateException ies) { - logger.error(EELFLoggerDelegate.errorLogger, "Log Cron not available", AlarmSeverityEnum.MAJOR); - } - } - - - - - public List<Trigger> getScheduleTriggers() { - return scheduleTriggers; - } - - - - public void setScheduleTriggers(List<Trigger> scheduleTriggers) { - this.scheduleTriggers = scheduleTriggers; - } - - - - - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/scheduler/CronRegistry.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/scheduler/CronRegistry.java deleted file mode 100644 index fdfda984..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/scheduler/CronRegistry.java +++ /dev/null @@ -1,124 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.scheduler; - -import java.text.ParseException; -import java.util.Map; - -import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.quartz.CronTrigger; -import org.springframework.scheduling.quartz.CronTriggerFactoryBean; -import org.springframework.scheduling.quartz.JobDetailFactoryBean; -import org.springframework.scheduling.quartz.QuartzJobBean; - -import com.mchange.v2.c3p0.ComboPooledDataSource; - -public abstract class CronRegistry { - - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CronRegistry.class); - protected JobDetailFactoryBean jobDetailFactory; - protected CronTriggerFactoryBean cronTriggerFactory; - - private ComboPooledDataSource dataSource; - - public CronRegistry() { - try { - jobDetailFactoryBean(); - cronTriggerFactoryBean(); - } - catch(Exception e) { - logger.error(EELFLoggerDelegate.debugLogger, e.getMessage()); - } - } - - //@Autowired - public CronRegistry(ComboPooledDataSource dataSource) { - try { - this.dataSource = dataSource; - jobDetailFactoryBean(); - cronTriggerFactoryBean(); - } - catch(Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AlarmSeverityEnum.MAJOR); - } - } - - //@Autowired - public CronRegistry(Object... initializeObjects) { - try { - initializeObjects(initializeObjects); - jobDetailFactoryBean(); - cronTriggerFactoryBean(); - } - catch(Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, e.getMessage()); - } - } - - protected void initializeObjects(Object... initializeObjects) { - } - - public abstract JobDetailFactoryBean jobDetailFactoryBean() throws ParseException; - - protected JobDetailFactoryBean jobDetailFactoryBean(String groupName, String jobName, - Class<? extends QuartzJobBean> jobClass, Map<String, Object> map) { - - jobDetailFactory = new JobDetailFactoryBean(); - jobDetailFactory.setJobClass(jobClass); - jobDetailFactory.setJobDataAsMap(map); - jobDetailFactory.setGroup(groupName); - jobDetailFactory.setName(jobName); - jobDetailFactory.afterPropertiesSet(); - - return jobDetailFactory; - } - - public abstract CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException; - - protected CronTriggerFactoryBean cronTriggerFactoryBean(String groupName, String triggerName, String cronExpression) throws ParseException { - cronTriggerFactory = new CronTriggerFactoryBean(); - cronTriggerFactory.setJobDetail(jobDetailFactory.getObject()); - cronTriggerFactory.setStartDelay(3000); - cronTriggerFactory.setName(triggerName); - cronTriggerFactory.setGroup(groupName); - logger.info(EELFLoggerDelegate.applicationLogger, triggerName + " Scheduled: " + cronExpression); - cronTriggerFactory.setCronExpression( cronExpression); //"0 * * * * ? *" - cronTriggerFactory.afterPropertiesSet(); - return cronTriggerFactory; - } - - public CronTrigger getTrigger() { - return cronTriggerFactory.getObject(); - } - - - public void setDataSource(ComboPooledDataSource dataSource) { - this.dataSource = dataSource; - } - - - public ComboPooledDataSource getDataSource() { - return dataSource; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/scheduler/Registerable.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/scheduler/Registerable.java deleted file mode 100644 index e2e4c385..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/scheduler/Registerable.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.scheduler; - -import org.quartz.Trigger; - -public interface Registerable { - - public void registerTriggers(); - - public Trigger[] getTriggers(); - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AppService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AppService.java deleted file mode 100644 index 55180fd7..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AppService.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.List; - -import org.openecomp.portalsdk.core.domain.App; - -/** - * Defines methods to fetch App domain objects. - * - * Very thin interface; Portal defines a much richer interface. - */ -public interface AppService { - - /** - * Gets all apps defined in the table. - * - * @return List of apps. - */ - List<App> getApps(); - - /** - * Gets the app with the specified ID. - * - * @param appId - * @return App with the specified ID. - */ - App getApp(Long appId); - - /** - * Gets the singleton entry - applications should have exactly 1 row in the - * FN_APP table. - */ - App getDefaultApp(); - - /** - * Fetches the application name once from database - * and keep refers to the same name later on as required. - * @return Default Application Name - */ - String getDefaultAppName(); - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AppServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AppServiceImpl.java deleted file mode 100644 index 30e566a2..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AppServiceImpl.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.List; - -import org.openecomp.portalsdk.core.domain.App; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("appService") -@Transactional -public class AppServiceImpl implements AppService{ - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppServiceImpl.class); - - @Autowired - private DataAccessService dataAccessService; - - /** - * Loads the appName once from database and - * keep refers to it as required. - */ - private static String defaultAppName = ""; - - /* - * (non-Javadoc) - * @see org.openecomp.portalsdk.core.service.AppService#getApps() - */ - @SuppressWarnings("unchecked") - @Override - public List<App> getApps() { - return getDataAccessService().getList(App.class, null); - } - - /* - * (non-Javadoc) - * @see org.openecomp.portalsdk.core.service.AppService#getApp(long) - */ - @Override - public App getApp(Long appId) { - return (App)getDataAccessService().getDomainObject(App.class, appId, null); - } - - /* - * (non-Javadoc) - * @see org.openecomp.portalsdk.core.service.AppService#getApp() - */ - @Override - public App getDefaultApp() { - return getApp(1L); - } - - /** - * Gets the data access service. - * @return DataAccessService - */ - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - /** - * Sets the data access service. - * @param dataAccessService - */ - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - /** - * Fetches the application name once from database - * and keep refers to the same name later on as required. - * @return Default Application Name - */ - @Override - public String getDefaultAppName() { - if (AppServiceImpl.defaultAppName==null || AppServiceImpl.defaultAppName=="") { - App app = getApp(1L); - if (app!=null) { - AppServiceImpl.defaultAppName = app.getName(); - } else { - logger.warn(EELFLoggerDelegate.errorLogger, ("Unable to locate the app information from the database.")); - } - } - return AppServiceImpl.defaultAppName; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AuditService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AuditService.java deleted file mode 100644 index b632c92c..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AuditService.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.HashMap; - -import org.openecomp.portalsdk.core.domain.AuditLog; - -public interface AuditService { - /** - * - * Update log data in database - * - * @param auditLog - * @param additionalParams - */ - @SuppressWarnings("rawtypes") - void logActivity(AuditLog auditLog, HashMap additionalParams); -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AuditServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AuditServiceImpl.java deleted file mode 100644 index 8fbd550c..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/AuditServiceImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.HashMap; - -import org.openecomp.portalsdk.core.domain.AuditLog; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("auditService") -@Transactional -public class AuditServiceImpl implements AuditService { - public AuditServiceImpl() {} - - @Autowired - private DataAccessService dataAccessService; - - @SuppressWarnings("rawtypes") - public void logActivity(AuditLog auditLog, HashMap additionalParams) { - getDataAccessService().saveDomainObject(auditLog, additionalParams); - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/BroadcastService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/BroadcastService.java deleted file mode 100644 index 8d60e74b..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/BroadcastService.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.HashMap; -import java.util.Hashtable; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.portalsdk.core.domain.BroadcastMessage; - -@SuppressWarnings("rawtypes") -public interface BroadcastService { - HashMap getBcModel(HttpServletRequest request); - Hashtable getBroadcastMessages(); - void loadMessages(); - BroadcastMessage getBroadcastMessage(HttpServletRequest request); - void saveBroadcastMessage(BroadcastMessage broadcastMessage); - void removeBroadcastMessage(BroadcastMessage broadcastMessage); -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/BroadcastServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/BroadcastServiceImpl.java deleted file mode 100644 index def1c1a6..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/BroadcastServiceImpl.java +++ /dev/null @@ -1,248 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.Calendar; -import java.util.Collections; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.portalsdk.core.domain.BroadcastMessage; -import org.openecomp.portalsdk.core.domain.Lookup; -import org.openecomp.portalsdk.core.service.support.FusionService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.AppUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.ServletRequestBindingException; -import org.springframework.web.bind.ServletRequestUtils; - -@SuppressWarnings("rawtypes") -@Service("broadcastService") -@Transactional -public class BroadcastServiceImpl extends FusionService implements BroadcastService { - - public BroadcastServiceImpl() { - } - - @Autowired - private DataAccessService dataAccessService; - private static Hashtable broadcastMessages = new Hashtable(); - - @SuppressWarnings("unchecked") - public void loadMessages() { - List messageLocations = AppUtils.getLookupListNoCache("fn_lu_message_location", "message_location_id", "message_location_descr", "", "message_location_id"); - - for (int i=0; i < messageLocations.size(); i++) { - Lookup location = (Lookup)messageLocations.get(i); - String locationId = location.getValue(); - - broadcastMessages.put(locationId, getPersistedBroadcastMessages(locationId)); - } - } - - @SuppressWarnings("unchecked") - public HashMap getBcModel(HttpServletRequest request){ - HashMap bcModel = new HashMap(); - - List items = null; - int messageId = ServletRequestUtils.getIntParameter(request, "message_id", 0); - String task = ServletRequestUtils.getStringParameter(request, "task", "get"); - - // delete or toggle activation on the selected record (if applicable) - if (messageId != 0 && (task.equals("delete") || task.equals("toggleActive"))) { - BroadcastMessage message = (BroadcastMessage)getDataAccessService().getDomainObject(BroadcastMessage.class, new Long(messageId), null); - - if (task.equals("delete")) { - getDataAccessService().deleteDomainObject(message, null); - } - else if (task.equals("toggleActive")) { - HashMap additionalParams = new HashMap(); - additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request); - - message.setActive(new Boolean(!message.getActive().booleanValue())); - getDataAccessService().saveDomainObject(message, additionalParams); - } - loadMessages(); - } - - items = getDataAccessService().getList(BroadcastMessage.class, null); - Collections.sort(items); - bcModel.put("messagesList", packageMessages(items)); - - List locations = AppUtils.getLookupList("fn_lu_message_location", "message_location_id", "message_location_descr", "", "message_location_id"); - bcModel.put("messageLocations", locations); - - if ("true".equals(SystemProperties.getProperty(SystemProperties.CLUSTERED))) { - List sites = AppUtils.getLookupList("fn_lu_broadcast_site", "broadcast_site_cd", "broadcast_site_descr", "", "broadcast_site_descr"); - bcModel.put("broadcastSites", sites); - } - - return bcModel; - } - - @SuppressWarnings("unchecked") - private HashMap packageMessages(List messages) { - HashMap messagesList = new HashMap(); - Set locationMessages = null; - - Integer previousLocationId = null; - - for (int i=0; i < messages.size(); i++) { - BroadcastMessage message = (BroadcastMessage)messages.get(i); - - if (!message.getLocationId().equals(previousLocationId)) { - if (previousLocationId != null) { - messagesList.put(previousLocationId.toString(), locationMessages); - } - - locationMessages = new TreeSet(); - previousLocationId = message.getLocationId(); - } - - locationMessages.add(message); - } - - if (previousLocationId != null) { - messagesList.put(previousLocationId.toString(), locationMessages); - } - - return messagesList; - } - - - @SuppressWarnings("unchecked") - private List getPersistedBroadcastMessages(String locationId) { - - HashMap params = new HashMap(); - params.put("location_id", new Integer(locationId)); - Calendar calInstanceToday = Calendar.getInstance(); - calInstanceToday.set(Calendar.HOUR, 0); - calInstanceToday.set(Calendar.MINUTE, 0); - calInstanceToday.set(Calendar.SECOND, 0); - params.put("today_date", calInstanceToday.getTime()); - - return getDataAccessService().executeNamedQuery("broadcastMessages", params, null); - } - - public Hashtable getBroadcastMessages() { - return broadcastMessages; - } - - public static List getBroadcastMessages(String locationId) { - return (List)broadcastMessages.get(locationId); - } - - public static String displayMessages(String locationId) { - return displayServerMessages(locationId, null); - } - - public static String displayServerMessages(String locationId, String siteCd) { - StringBuffer html = new StringBuffer(); - - List messages = getBroadcastMessages(locationId); - - for (int i=0; i < messages.size(); i++) { - BroadcastMessage message = (BroadcastMessage)messages.get(i); - - if ((message.getSiteCd() == null) || ((message.getSiteCd() != null) && message.getSiteCd().equals(siteCd))) { - html.append("<li class=\"broadcastMessage\">") - .append(message.getMessageText()); - } - } - - if (html.length() > 0) { - html.insert(0, "<ul class=\"broadcastMessageList\">"); - html.append("</ul>"); - } - - return html.toString(); - } - - public static boolean hasMessages(String locationId) { - return hasServerMessages(locationId, null); - } - - public static boolean hasServerMessages(String locationId, String siteCd) { - List messages = getBroadcastMessages(locationId); - - boolean messagesExist = !((messages == null) || messages.size() == 0); - - if (siteCd == null) { - return messagesExist; - } - else { - for (int i=0; i < messages.size(); i++) { - BroadcastMessage message = (BroadcastMessage)messages.get(i); - - if ((message.getSiteCd() == null) || message.getSiteCd().equals(siteCd)) { - return true; - } - } - return false; - } - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - public BroadcastMessage getBroadcastMessage(HttpServletRequest request) { - long messageId = ServletRequestUtils.getLongParameter(request, "message_id", 0); - - BroadcastMessage message = new BroadcastMessage(); - if(messageId!=0) - message = (BroadcastMessage)getDataAccessService().getDomainObject(BroadcastMessage.class, new Long(messageId), null); - - if (message.getLocationId() == null) { - try { - message.setLocationId(new Integer(ServletRequestUtils.getStringParameter(request, "message_location_id"))); - } catch (NumberFormatException e) { - e.printStackTrace(); - } catch (ServletRequestBindingException e) { - e.printStackTrace(); - } - message.setActive(Boolean.TRUE); - } - - return message; - } - - @Override - public void saveBroadcastMessage(BroadcastMessage broadcastMessage) { - dataAccessService.saveDomainObject(broadcastMessage, null); - } - - @Override - public void removeBroadcastMessage(BroadcastMessage broadcastMessage) { - dataAccessService.deleteDomainObject(broadcastMessage, null); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/DataAccessService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/DataAccessService.java deleted file mode 100644 index 26892b88..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/DataAccessService.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - - -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.hibernate.FetchMode; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.ProjectionList; -import org.openecomp.portalsdk.core.domain.support.DomainVo; - -@SuppressWarnings("rawtypes") -public interface DataAccessService { - - // generic view, save, delete methods - DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams); - void deleteDomainObject(DomainVo domainObject, HashMap additionalParams); - void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams); - void saveDomainObject(DomainVo domainObject, HashMap additionalParams); - - // generic get list method(s) - List getList(Class domainClass, HashMap additionalParams); - List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams); - List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, HashMap additionalParams); - List<?> getList(Class<?> domainClass, ProjectionList projectionsList , List<Criterion> restrictionsList , List<Order> orderByList); - public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, List<Order> orderByList,HashMap<String,FetchMode> fetchModeMap); - - List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, HashMap additionalParams); - - // generic native-SQL execution methods - List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams); - List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex,HashMap additionalParams); - - // generic HQL execution methods - List executeQuery(String hql, HashMap additionalParams); - List executeQuery(String hql, Integer fromIndex, Integer toIndex, HashMap additionalParams); - - // generic named query execution methods - List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams); - List executeNamedQuery(String queryName, Map params, HashMap additionalParams); - List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, HashMap additionalParams); - - //with Where Clause for RAPTOR ZK - List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams); - List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params); - List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex, Integer toIndex, HashMap additionalParams); - List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams); - - // generic update query execution method - int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException; - - // generic named update query execution method - int executeNamedUpdateQuery(String queryName, Map params, HashMap additionalParams) throws RuntimeException; - - // synchronizes the local updates with the database (and vice versa) - void synchronize(HashMap additionalParams); - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/DataAccessServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/DataAccessServiceImpl.java deleted file mode 100644 index a4644b72..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/DataAccessServiceImpl.java +++ /dev/null @@ -1,592 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.hibernate.Criteria; -import org.hibernate.FetchMode; -import org.hibernate.Query; -import org.hibernate.SQLQuery; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.ProjectionList; -import org.openecomp.portalsdk.core.domain.Lookup; -import org.openecomp.portalsdk.core.domain.support.DomainVo; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.support.FusionService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -/** - * Provides implementations of methods in {@link DataAccessService}. - */ -@Transactional -public class DataAccessServiceImpl extends FusionService implements DataAccessService { - - @Autowired - private SessionFactory sessionFactory; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DataAccessServiceImpl.class); - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#getDomainObject(java.lang. - * Class, java.io.Serializable, java.util.HashMap) - */ - @Override - public DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams) { - DomainVo vo = null; - Session session = sessionFactory.getCurrentSession(); - logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString()); - vo = (DomainVo) session.get(domainClass, id); - - if (vo == null) { - try { - vo = (DomainVo) domainClass.newInstance(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "An error occured while instantiating a class of " + domainClass.getName() + e.getMessage()); - } - } - return vo; - } - - /* - * (non-Javadoc) - * - */ - @Override - public void deleteDomainObject(DomainVo domainObject, HashMap additionalParams) { - Session session = sessionFactory.getCurrentSession(); - session.delete(domainObject); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#deleteDomainObjects(java. - * lang.Class, java.lang.String, java.util.HashMap) - */ - @Override - public void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams) { - Session session = sessionFactory.getCurrentSession(); - - StringBuffer sql = new StringBuffer("delete from "); - - sql.append(domainClass.getName()).append(" where ").append(whereClause); - - session.createQuery(sql.toString()).executeUpdate(); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#saveDomainObject - */ - @Override - public void saveDomainObject(DomainVo vo, HashMap additionalParams) { - Integer userId = 1; - if (additionalParams != null) { - // look for a passed user id - // userId = (Integer)additionalParams.get(Parameters.PARAM_USERID); - Object uid = additionalParams.get(Parameters.PARAM_USERID); - if (uid instanceof Integer) { - userId = (Integer) uid; - } else if (uid instanceof Long) { - userId = ((Long) uid).intValue(); - } - // if (userId == null) { - // look for a passed request to get the user id from - // userId = new - // Integer(UserUtils.getUserId((HttpServletRequest)additionalParams.get(Parameters.PARAM_HTTP_REQUEST))); - // } - } - _update(vo, userId); - } - - /** - * Creates or updates the specified virtual object. Uses the specified user - * ID as the creator and modifier if a new object is created; uses ID only - * as modifier if an object already exists. - * - * @param vo - * @param userId - * Ignored if value is zero. - */ - protected final void _update(DomainVo vo, int userId) { - Date timestamp = new Date(); - - Session session = sessionFactory.getCurrentSession(); - - if (vo.getId() == null || vo.getId().intValue() == 0) { // add new - vo.setCreated(timestamp); - vo.setModified(timestamp); - - if (userId != 0 - && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) { - vo.setCreatedId(new Long(userId)); - vo.setModifiedId(new Long(userId)); - } - } else { // update existing - vo.setModified(timestamp); - - if (userId != 0 - && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) { - vo.setModifiedId(new Long(userId)); - } - } - - session.saveOrUpdate(vo); - } - - /** - * generic get list method - * - * @param domainClass - * @param filterClause - * @param fromIndex - * @param toIndex - * @param orderBy - * @return - */ - private List getListCommon(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex, - String orderBy) { - List list = null; - String className = domainClass.getName(); - Session session = sessionFactory.getCurrentSession(); - - if (logger.isInfoEnabled()) { - logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records" - + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "") - + "..."); - if (filterClause != null && filterClause.length() > 0) - logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause); - } - - list = session.createQuery("from " + className + Utilities.nvl(filterClause, "") - + ((orderBy != null) ? " order by " + orderBy : "")).list(); - list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list; - - if (orderBy == null && list != null) - Collections.sort(list); - - return list; - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class, - * java.util.HashMap) - */ - @Override - public List getList(Class domainClass, HashMap additionalParams) { - return getListCommon(domainClass, null, null, null, null); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class, - * java.lang.String, java.lang.String, java.util.HashMap) - */ - @Override - public List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams) { - return getListCommon(domainClass, filter, null, null, orderBy); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class, - * java.lang.String, int, int, java.lang.String, java.util.HashMap) - */ - @Override - public List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, - HashMap additionalParams) { - return getListCommon(domainClass, filter, new Integer(fromIndex), new Integer(toIndex), orderBy); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class, - * org.hibernate.criterion.ProjectionList, java.util.List, java.util.List) - */ - @Override - public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, - List<Order> orderByList) { - - Session session = sessionFactory.getCurrentSession(); - - Criteria criteria = session.createCriteria(domainClass); - - if (projectionsList != null) { - criteria.setProjection(projectionsList); - } - - if (restrictionsList != null && !restrictionsList.isEmpty()) { - for (Criterion criterion : restrictionsList) - criteria.add(criterion); - } - - if (orderByList != null && !orderByList.isEmpty()) { - for (Order order : orderByList) - criteria.addOrder(order); - } - /* - * if(fetchModeMap!=null){ Iterator<String> itr = - * fetchModeMap.keySet().iterator(); String key=null; - * while(itr.hasNext()){ key = itr.next(); - * criteria.setFetchMode(key,fetchModeMap.get(key)); } } - */ - return criteria.list(); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#getLookupList(java.lang. - * String, java.lang.String, java.lang.String, java.lang.String, - * java.lang.String, java.util.HashMap) - */ - @Override - public List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, - HashMap additionalParams) { - if (logger.isInfoEnabled()) - logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list..."); - String dbOrderByCol = dbOrderBy; - - Session session = sessionFactory.getCurrentSession(); - - // default the orderBy if null; - if (Utilities.nvl(dbOrderBy).length() == 0) { - dbOrderByCol = dbLabelCol; - dbOrderBy = dbLabelCol; - } else { - if (dbOrderBy.lastIndexOf(" ") > -1) { - dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" ")); - } - } - - StringBuffer sql = new StringBuffer(); - - sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ") - .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ") - .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ") - .append(dbOrderBy); - - List list = null; - try { - list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list(); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.debugLogger, "Failed to create SQL lookup query for [" + sql + "]" + e.getMessage()); - } - return list; - } - - /* - * methods accepting a Map of additional params to passed to the DAO (for - * extensibility, just in case) - */ - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeSQLQuery(java.lang. - * String, java.lang.Class, java.util.HashMap) - */ - @Override - public List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams) { - return executeSQLQuery(sql, domainClass, null, null, additionalParams); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeSQLQuery(java.lang. - * String, java.lang.Class, java.lang.Integer, java.lang.Integer, - * java.util.HashMap) - */ - @Override - public List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex, - HashMap additionalParams) { - Session session = sessionFactory.getCurrentSession(); - - SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass); - - if (fromIndex != null && toIndex != null) { - query.setFirstResult(fromIndex.intValue()); - int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; - query.setMaxResults(pageSize); - } - - return query.list(); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeQuery(java.lang. - * String, java.util.HashMap) - */ - @Override - public List executeQuery(String sql, HashMap additionalParams) { - return executeQuery(sql, null, null, additionalParams); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeQuery(java.lang. - * String, java.lang.Integer, java.lang.Integer, java.util.HashMap) - */ - @Override - public List executeQuery(String sql, Integer fromIndex, Integer toIndex, HashMap additionalParams) { - Session session = sessionFactory.getCurrentSession(); - - Query query = session.createQuery(sql); - - if (fromIndex != null && toIndex != null) { - query.setFirstResult(fromIndex.intValue()); - int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; - query.setMaxResults(pageSize); - } - - return query.list(); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang - * .String, java.lang.Integer, java.lang.Integer, java.util.HashMap) - */ - @Override - public List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams) { - return executeNamedQuery(queryName, null, fromIndex, toIndex, additionalParams); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang - * .String, java.util.Map, java.util.HashMap) - */ - @Override - public List executeNamedQuery(String queryName, Map params, HashMap additionalParams) { - return executeNamedQuery(queryName, params, null, null, additionalParams); - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang - * .String, java.util.Map, java.lang.Integer, java.lang.Integer, - * java.util.HashMap) - */ - @Override - public List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, - HashMap additionalParams) { - Session session = sessionFactory.getCurrentSession(); - Query query = session.getNamedQuery(queryName); - bindQueryParameters(query, params); - if (fromIndex != null && toIndex != null) { - query.setFirstResult(fromIndex.intValue()); - int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1; - query.setMaxResults(pageSize); - } - return query.list(); - } - - /** - * Stores parameters into the query using String keys from the map. Gives - * special treatment to map values of Collection and array type. - * - * @param query - * Query with parameters - * @param params - * Map of String to Object. - */ - private void bindQueryParameters(Query query, Map params) { - if (params != null) { - for (Iterator i = params.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); - - Object parameterValue = entry.getValue(); - - if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) { - query.setParameter((String) entry.getKey(), parameterValue); - } else if (parameterValue instanceof Collection) { - query.setParameterList((String) entry.getKey(), (Collection) parameterValue); - } else if (parameterValue instanceof Object[]) { - query.setParameterList((String) entry.getKey(), (Object[]) parameterValue); - } - } - } - } - - // With Where Clause & RAPTOR's ZK - - /* - * (non-Javadoc) - * - * @see org.openecomp.portalsdk.core.service.DataAccessService# - * executeNamedQueryWithOrderBy(java.lang.Class, java.lang.String, - * java.util.Map, java.lang.String, boolean, java.lang.Integer, - * java.lang.Integer, java.util.HashMap) - */ - @Override - public List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, boolean asc, - Integer fromIndex, Integer toIndex, HashMap additionalParams) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return null; - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedCountQuery(java - * .lang.Class, java.lang.String, java.lang.String, java.util.Map) - */ - @Override - public List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return null; - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang - * .Class, java.lang.String, java.lang.String, java.util.Map, - * java.lang.Integer, java.lang.Integer, java.util.HashMap) - */ - @Override - public List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex, - Integer toIndex, HashMap additionalParams) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return null; - } - - /* - * (non-Javadoc) - * - * @see org.openecomp.portalsdk.core.service.DataAccessService# - * executeNamedQueryWithOrderBy(java.lang.Class, java.lang.String, - * java.lang.String, java.util.Map, java.lang.String, boolean, - * java.lang.Integer, java.lang.Integer, java.util.HashMap) - */ - @Override - public List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, - String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return null; - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class, - * org.hibernate.criterion.ProjectionList, java.util.List, java.util.List, - * java.util.HashMap) - */ - @Override - public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, - List<Order> orderByList, HashMap<String, FetchMode> fetchModeMap) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return null; - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeUpdateQuery(java. - * lang.String, java.util.HashMap) - */ - @Override - public int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return 0; - } - - /* - * (non-Javadoc) - * - * @see - * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedUpdateQuery( - * java.lang.String, java.util.Map, java.util.HashMap) - */ - @Override - public int executeNamedUpdateQuery(String queryName, Map params, HashMap additionalParams) throws RuntimeException { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return 0; - } - - /* - * (non-Javadoc) - * - * @see org.openecomp.portalsdk.core.service.DataAccessService#synchronize(java.util. - * HashMap) - */ - @Override - public void synchronize(HashMap additionalParams) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ElementLinkService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ElementLinkService.java deleted file mode 100644 index 948b635f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ElementLinkService.java +++ /dev/null @@ -1,269 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.util.YamlUtils; - - - -public class ElementLinkService { - - - public String main1(String[] args) throws Exception{ - String filePath; - if(args[0].startsWith("custom")){ - filePath = SystemProperties.getProperty("customCallFlow_path"); - }else{ - 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] + ".yml"; - } - - if( args[1] != null) { - callFlowStep = args[1]; - } - } - - - ElementLinkService mapper = new ElementLinkService(); - - return mapper.createLinkFile(filePath, callFlowBusinessYml, callFlowStep); - } - - 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 = "C:\\Users\\statta\\git\\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")); - } - - @SuppressWarnings("unchecked") - protected String createLinkFile(String resourceFilePath, String callFLowBsFileName, String callFlowStep) throws Exception { - - Map<String, Object> callFlowBs = YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName); - - List<Map<String,Object>> callSteps = (List<Map<String,Object>>) callFlowBs.get("callSequenceSteps"); - String callFlowName = (String) callFlowBs.get("shortName"); - return addLinks( resourceFilePath, callFlowName, callSteps, callFlowStep); - - - } - - @SuppressWarnings("unchecked") - protected String createLinkFileAdditional(String resourceFilePath, String callFLowBsFileName, String callFlowStep) throws Exception { - - Map<String, Object> callFlowBs; - - try{ - callFlowBs = YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName); - - List<Map<String,Object>> callSteps = (List<Map<String,Object>>) callFlowBs.get("callSequenceSteps"); - String callFlowName = (String) callFlowBs.get("shortName"); - return addLinksAdditional( resourceFilePath, callFlowName, callSteps, callFlowStep); - - } catch (Exception e) { - - return ""; - } - - - } - - @SuppressWarnings("unchecked") - protected String addLinks(String filePath, String callFlowName, - List<Map<String, Object>> callSteps, String callFlowStep) throws IOException { - - Map<String,List<String>> checkDuplicateMap = new HashMap<String,List<String>>(); - - for(Map<String,Object> callStep : callSteps) { - - if(((String)callStep.get("name")).split(":")[0].trim().replace(" ", "_").equals(callFlowStep)) { - - List<Map<String,Object>> links = new ArrayList<Map<String,Object>>(); - - List<Map<String,Object>> subSteps = (List<Map<String,Object>>)callStep.get("subSteps"); - - for(Map<String,Object> subStep : subSteps) { - Map<String,Object> link = new HashMap<String,Object>(); - - String source = (String) subStep.get("source_tosca_id"); - String destination = (String) subStep.get("destination_tosca_id"); - - if((checkDuplicateMap.get(source) == null || checkDuplicateMap.get(source).isEmpty() || !checkDuplicateMap.get(source).contains(destination)) && !source.equals(destination)) { - if(checkDuplicateMap.get(destination) == null) { - List<String> toscaList = new ArrayList<String>(); - checkDuplicateMap.put(destination, toscaList); - } - - if(checkDuplicateMap.get(source) == null) { - List<String> toscaList = new ArrayList<String>(); - checkDuplicateMap.put(source, toscaList); - } - - - List<String> toscaSourceList = checkDuplicateMap.get(destination); - toscaSourceList.add(source); - - List<String> toscaDestinationList = checkDuplicateMap.get(source); - toscaDestinationList.add(destination); - - link.put("s", source); - link.put("d", destination); - links.add(link); - - } - - } - - Map<String,Object> callFlowUI = new HashMap<String,Object>(); - callFlowUI.put("linkList", links); - - return YamlUtils.returnYaml(callFlowUI); - - } - - - } - return ""; - } - - protected String addLinksAdditional(String filePath, String callFlowName, - List<Map<String, Object>> callSteps, String callFlowStep) throws IOException { - - - for(Map<String,Object> callStep : callSteps) { - - if(((String)callStep.get("name")).split(":")[0].trim().replace(" ", "_").equals(callFlowStep)) { - - Map<String,Object> callFlowUI = new HashMap<String,Object>(); - try{ - List<Map<String, Object>> links = addLinkVertices(callStep); - callFlowUI.put("linkList", links); } - catch(Exception e) {} - try{ - List<String> activeIds = addActiveNodes(callStep); - callFlowUI.put("activeIds", activeIds);} - catch(Exception e) {} - try{ - List<Map<String, Object>> disconnectLinks = addDisconnectLinks(callStep); - callFlowUI.put("disconnectLinks", disconnectLinks); } - catch(Exception e) {} - - return YamlUtils.returnYaml(callFlowUI); - } - } - - return ""; - } - - @SuppressWarnings("unchecked") - List<String> addActiveNodes(Map<String, Object> callStep) { - - List<String> activeIds = (List<String>)callStep.get("activeIds"); - - return activeIds; - } - - @SuppressWarnings("unchecked") - List<Map<String,Object>> addDisconnectLinks(Map<String, Object> callStep) { - - List<Map<String,Object>> disconnectLinks = (List<Map<String,Object>>)callStep.get("disconnectLinks"); - - return disconnectLinks; - } - - @SuppressWarnings("unchecked") - List<Map<String, Object>> addLinkVertices(Map<String, Object> callStep) { - List<Map<String,Object>> links = new ArrayList<Map<String,Object>>(); - - List<Map<String,Object>> vertices = (List<Map<String,Object>>)callStep.get("vertices"); - - for(int i=0; i< vertices.size()-1;i++) { - Map<String,Object> vertex = (Map<String,Object>) vertices.get(i); - Map<String,Object> vertexNext = (Map<String,Object>) vertices.get(i+1); - - Integer sourceX = (Integer) vertex.get("x"); - Integer sourceY = (Integer) vertex.get("y"); - String sourceD = (String) vertex.get("D"); - String sourceL = (vertex.get("L") != null) ? (String) vertex.get("L") : "-"; - - if(sourceX == -999) // there is a break in the linkage - continue; - - Integer destinationX = (Integer) vertexNext.get("x"); - Integer destinationY = (Integer) vertexNext.get("y"); - String destinationD = (String) vertexNext.get("D"); - - if(destinationX == -999) // there is a break in the linkage - continue; - - Map<String,Object> link = new HashMap<String,Object>(); - - link.put("s", sourceX + "," + sourceY +","+sourceD + "," + sourceL); - link.put("d", destinationX + "," + destinationY +"," + destinationD); - links.add(link); - } - return links; - } -} - - diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ElementMapService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ElementMapService.java deleted file mode 100644 index d88213f3..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ElementMapService.java +++ /dev/null @@ -1,915 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import org.apache.commons.lang.StringUtils; -import org.openecomp.portalsdk.core.domain.support.Container; -import org.openecomp.portalsdk.core.domain.support.Domain; -import org.openecomp.portalsdk.core.domain.support.Element; -import org.openecomp.portalsdk.core.domain.support.ElementDetails; -import org.openecomp.portalsdk.core.domain.support.Layout; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.util.YamlUtils; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.nodes.Tag; -import org.yaml.snakeyaml.representer.Representer; - -public class ElementMapService { - - public String convertToYAML(Layout layout) throws Exception{ - Map<String,Domain> resultDomain= layout.domainRowCol; - Map<String,List<Domain>> domainMap = new HashMap<String, List<Domain>>(); - List<Domain> domainList = new ArrayList<Domain>(); - String pathToImg = SystemProperties.getProperty("element_map_icon_path"); //"static/img/map/icons/"; - for (Domain d : resultDomain.values()) { - - d.setWidth(10*d.computeSize().getWidth()); - d.setHeight(10*d.computeSize().getHeight()); - d.setLeft(10*d.getP().getX()); - d.setTop(10*d.getP().getY()); - - - List<Container> containerList = new ArrayList<Container>(); - for (Container c : d.getContainerRowCol().values()) { - c.setWidth(10*c.computeSize().getWidth()); - c.setHeight(10*c.computeSize().getHeight()); - c.setLeft(10*c.getP().getX()); - c.setTop(10*c.getP().getY()); - Element ue = (Element)c.getElementRowCol().values().toArray()[0]; - if (ue.getName().equals("ue1") || ue.getName().equals("ue2") || ue.getName().equals("ue3") || - ue.getName().equals("ue4") || ue.getName().equals("ue5") || ue.getName().equals("ue6")) { - c.setVisibilityType("invisible"); - } - - if (c.getContainerRowCol() != null) { - List<Container> innerContainerList = new ArrayList<Container>(); - for (Container innerC : c.getContainerRowCol().values()) { - innerC.setName(innerC.getName()); - innerC.setWidth(10*innerC.computeSize().getWidth()); - innerC.setHeight(10*innerC.computeSize().getHeight()); - innerC.setLeft(10*innerC.getP().getX()); - innerC.setTop(10*innerC.getP().getY()); - - if (innerC.getElementRowCol() != null) { - List<Element> innerContainerEList = new ArrayList<Element>(); - for (Element ele : innerC.getElementRowCol().values()) { - ele.setWidth(10*ele.computeSize().getWidth()); - ele.setHeight(10*ele.computeSize().getHeight()); - ele.setLeft(10*ele.getP().getX()); - ele.setTop(10*ele.getP().getY()-10); - ele.setImgFileName(pathToImg+ele.getImgFileName()); - if (ele.getBorderType().equals("V")) - ele.setBorderType("dashed"); - else - ele.setBorderType("solid"); - - innerContainerEList.add(ele); - } - innerC.setElementList(innerContainerEList); - } - innerContainerList.add(innerC); - } - c.setInnerCList(innerContainerList); - } - - if (c.getElementRowCol() != null) { - List<Element> elementList = new ArrayList<Element>(); - for (Element e : c.getElementRowCol().values()) { - e.setWidth(10*e.computeSize().getWidth()); - e.setHeight(10*e.computeSize().getHeight()); - e.setLeft(10*e.getP().getX()); - e.setTop(10*e.getP().getY()-10); - e.setImgFileName(pathToImg+e.getImgFileName()); - - if (e.getBorderType().equals("V")) - e.setBorderType("dashed"); - else - e.setBorderType("solid"); - - if (e.getName().equals("ue1") || e.getName().equals("ue2") || e.getName().equals("ue3") - || e.getName().equals("ue4") || e.getName().equals("ue5") || e.getName().equals("ue6")) - e.setBgColor("white"); - elementList.add(e); - } - c.setElementList(elementList); - } - containerList.add(c); - } - d.setContainerList(containerList); - domainList.add(d); - - } - domainMap.put("domainList", domainList); - - List<Domain> collapsedDomains = new ArrayList<Domain>(); - - //nline - for (Domain collapsed : layout.getCollapsedDomainsNewList()) { - collapsed.setWidth(10*collapsed.computeSize().getWidth()); - collapsed.setHeight(10*collapsed.computeSize().getHeight()); - collapsed.setLeft(10*collapsed.getP().getX()); - collapsed.setTop(10*collapsed.getP().getY()); - //nline - collapsed.setNewXafterColl(10*collapsed.getNewXafterColl()); - collapsed.setYafterColl(10*collapsed.getYafterColl()); - collapsedDomains.add(collapsed); - } - - domainMap.put("collapsedDomainList", collapsedDomains); - - Representer representer = new Representer(); - representer.addClassTag(Domain.class, Tag.MAP); - - - Yaml yaml = new Yaml(representer); - String output = yaml.dump(domainMap); - - return output; - -} - - - - public static HashMap<String, Object> toscaElementsMap = new HashMap<String, Object>(); - public static HashMap<String,Element> elementMap = new HashMap<String, Element>(); - public static HashMap<String,Element> miscElementMap = new HashMap<String, Element>(); - public static HashMap<String,Container> outercontainers = new HashMap<String, Container>(); - public static HashMap<String,Container> innercontainers = new HashMap<String, Container>(); - public static HashMap<String,Domain> domainMap = new HashMap<String, Domain>(); - - - static String filePath = - SystemProperties.getProperty("element_map_file_path") ; - static String callFlowBusinessYml = "call_flow_sip_digest.yml"; - static String networkToscaYml = null;//"NetworkMap_topology_composition.yml"; - static String networkLayoutYml = null;// "network_map_layout.yml"; - - - @SuppressWarnings({ "unchecked", "unused" }) - public String main1(String args[]) throws Exception{ - - - if(args != null && args.length > 0 ) { - - if( args[2] != null) { - networkToscaYml = args[2] + ".yml"; - } - - if( args[3] != null) { - networkLayoutYml = args[3] + ".yml"; - } - } - - HashMap<String, Object> toscaYaml = (HashMap<String, Object>)YamlUtils.readYamlFile(filePath, networkToscaYml); //TrinityYAMLHelper.getToscaYaml(); - HashMap<String, Object> networkMapLayoutYaml = (HashMap<String, Object>)YamlUtils.readYamlFile(filePath, networkLayoutYml); //TrinityYAMLHelper.getNetworkMapLayoutYaml(); - - toscaElementsMap = new HashMap<String, Object>(); - elementMap = new HashMap<String, Element>(); - domainMap = new HashMap<String, Domain>(); - outercontainers = new HashMap<String, Container>(); - innercontainers = new HashMap<String, Container>(); - miscElementMap = new HashMap<String, Element>(); - - if(toscaYaml != null){ - for(String key : toscaYaml.keySet()){ - if("topology_template".equalsIgnoreCase(key) && toscaYaml.get(key) instanceof HashMap){ - HashMap<String, Object> toscaTopologyDetails = (HashMap<String, Object>) toscaYaml.get(key); - - for(String detailsKey: toscaTopologyDetails.keySet()){ - - if("node_templates".equalsIgnoreCase(detailsKey) && toscaTopologyDetails.get(detailsKey) instanceof HashMap){ - - toscaElementsMap = (HashMap<String, Object>) toscaTopologyDetails.get(detailsKey); - - for(String toscaElementKey: toscaElementsMap.keySet()){ - } - - } - } - } - - } - } - - if(networkMapLayoutYaml != null){ - if(networkMapLayoutYaml.containsKey("toscaNetworkMapElementStyleList") && networkMapLayoutYaml.get("toscaNetworkMapElementStyleList") instanceof ArrayList){ - - ArrayList<Object> elementlist = (ArrayList<Object>)networkMapLayoutYaml.get("toscaNetworkMapElementStyleList"); - String elementName; - String elementID; - String imgPath; - String row; - String column; - String mapKey; - int i=0; - - if(elementlist != null){ - for(Object eachElement: elementlist){ - if(eachElement != null && eachElement instanceof HashMap){ - HashMap<String, String> elementDetails = (HashMap<String, String>) eachElement; - if(elementDetails != null){ - elementName = "NA"+i; - elementID = "NA"+i; - imgPath = "NA"+i; - row = "0"; - column = "0"; - for(String detailsKey: elementDetails.keySet()){ - if ("tosca_id".equalsIgnoreCase(detailsKey)) elementName = elementDetails.get(detailsKey).toString(); - if ("id".equalsIgnoreCase(detailsKey)) { - elementID = String.valueOf(elementDetails.get(detailsKey)); - } - if ("row".equalsIgnoreCase(detailsKey)) { - row = String.valueOf(elementDetails.get(detailsKey)); - } - if ("column".equalsIgnoreCase(detailsKey)) { - column = String.valueOf(elementDetails.get(detailsKey)); - } - if ("icon".equalsIgnoreCase(detailsKey)) imgPath = elementDetails.get(detailsKey).toString(); - } - - if(elementMap.containsKey(elementName.concat("/").concat(row).concat(column))){ - if(elementMap.containsKey(elementName.concat("/").concat(String.valueOf(i)).concat(String.valueOf(i)))){ - mapKey = elementName; - } else mapKey = elementName.concat("/").concat(String.valueOf(i)).concat(String.valueOf(i)); - - } else mapKey = elementName.concat("/").concat(row).concat(column); - - elementMap.put(mapKey, fetchElementObject(elementID,elementName,imgPath)); - } - } - i++; - } - } - - for(String elementkey : elementMap.keySet()){ - Element c = (Element) elementMap.get(elementkey); - } - - if(!elementMap.isEmpty()){ - miscElementMap = new HashMap<String, Element>(elementMap); - } - } - - - if(networkMapLayoutYaml.containsKey("containerStyleList") && networkMapLayoutYaml.get("containerStyleList") instanceof ArrayList){ - - ArrayList<Object> containerstylelist = (ArrayList<Object>)networkMapLayoutYaml.get("containerStyleList"); - String containerName; - String containerID; - String domain; - String row; - String column; - String mapKey; - int i=0; - - if(containerstylelist != null){ - //Inner Containers - for(Object eachContainer: containerstylelist){ - if(eachContainer != null && eachContainer instanceof HashMap){ - HashMap<String, String> containerDetails = (HashMap<String, String>) eachContainer; - if(containerDetails != null){ - containerName = "NA"+i; - containerID = "NA"+i; - domain = "NA"+i; - row = "0"; - column = "0"; - - for(String detailsKey: containerDetails.keySet()){ - if ("logical_group_name".equalsIgnoreCase(detailsKey)) containerName = containerDetails.get(detailsKey).toString(); - if ("id".equalsIgnoreCase(detailsKey)) { - containerID = String.valueOf(containerDetails.get(detailsKey)); - } - if("domain".equalsIgnoreCase(detailsKey)){ - domain = containerDetails.get(detailsKey).toString(); - } - if ("row".equalsIgnoreCase(detailsKey)) { - row = String.valueOf(containerDetails.get(detailsKey)); - } - if ("column".equalsIgnoreCase(detailsKey)) { - column = String.valueOf(containerDetails.get(detailsKey)); - } - } - if(containerName.contains("/")){ - - if(innercontainers.containsKey((domain +":"+ containerName).concat("/").concat(row).concat(column))){ - if(elementMap.containsKey((domain +":"+ containerName).concat("/").concat(String.valueOf(i)).concat(String.valueOf(i)))){ - mapKey = (domain +":"+ containerName); - } else mapKey = (domain +":"+ containerName).concat("/").concat(String.valueOf(i)).concat(String.valueOf(i)); - - } else mapKey = (domain +":"+ containerName).concat("/").concat(row).concat(column); - - innercontainers.put(mapKey, fetchContainerObject(containerID,containerName.substring(containerName.indexOf("/")+1),true,containerName,domain)); - } - } - } - i++; - } - - //OuterContainers - i=0; - for(Object eachContainer: containerstylelist){ - if(eachContainer != null && eachContainer instanceof HashMap){ - HashMap<String, String> containerDetails = (HashMap<String, String>) eachContainer; - if(containerDetails != null){ - containerName = "NA"+i; - containerID = "NA"+i; - domain = "NA"+i; - row = "0"; - column = "0"; - - for(String detailsKey: containerDetails.keySet()){ - if ("logical_group_name".equalsIgnoreCase(detailsKey)) containerName = containerDetails.get(detailsKey).toString(); - if ("id".equalsIgnoreCase(detailsKey)) { - containerID = String.valueOf(containerDetails.get(detailsKey)); - } - if("domain".equalsIgnoreCase(detailsKey)){ - domain = containerDetails.get(detailsKey).toString(); - } - if ("row".equalsIgnoreCase(detailsKey)) { - row = String.valueOf(containerDetails.get(detailsKey)); - } - if ("column".equalsIgnoreCase(detailsKey)) { - column = String.valueOf(containerDetails.get(detailsKey)); - } - } - if(!containerName.contains("/")){ - if(outercontainers.containsKey((domain +":"+ containerName).concat("/").concat(row).concat(column))){ - if(outercontainers.containsKey((domain +":"+ containerName).concat("/").concat(String.valueOf(i)).concat(String.valueOf(i)))){ - mapKey = (domain +":"+ containerName); - } else mapKey = (domain +":"+ containerName).concat("/").concat(String.valueOf(i)).concat(String.valueOf(i)); - - } else mapKey = (domain +":"+ containerName).concat("/").concat(row).concat(column); - outercontainers.put(mapKey, fetchContainerObject(containerID,containerName,false,containerName,domain)); - } - - } - } - i++; - } - } - - for(String innerContainerkey : innercontainers.keySet()){ - Container c = (Container) innercontainers.get(innerContainerkey); - } - - for(String outerContainerkey : outercontainers.keySet()){ - Container c = (Container) outercontainers.get(outerContainerkey); - } - - } - - if(networkMapLayoutYaml.containsKey("domainList") && networkMapLayoutYaml.get("domainList") instanceof ArrayList){ - - ArrayList<Object> domainlist = (ArrayList<Object>)networkMapLayoutYaml.get("domainList"); - String domainName; - String domainID; - String row; - String column; - String mapKey; - int i=0; - - if(domainlist != null){ - - Double leftPosition = 7d; - HashMap<String,String> domainStagingMap = new HashMap<String, String>(); - - for(Object eachDomain: domainlist){ - if(eachDomain != null && eachDomain instanceof HashMap){ - HashMap<String, String> domainDetails = (HashMap<String, String>) eachDomain; - if(domainDetails != null){ - domainName = "NA"+i; - domainID = "NA"+i; - row = "0"; - column = "0"; - for(String detailsKey: domainDetails.keySet()){ - if ("name".equalsIgnoreCase(detailsKey)) domainName = domainDetails.get(detailsKey).toString(); - if ("id".equalsIgnoreCase(detailsKey)) { - domainID = String.valueOf(domainDetails.get(detailsKey)); - } - if ("row".equalsIgnoreCase(detailsKey)) { - row = String.valueOf(domainDetails.get(detailsKey)); - } - if ("column".equalsIgnoreCase(detailsKey)) { - column = String.valueOf(domainDetails.get(detailsKey)); - } - } - - if(domainStagingMap.containsKey(row.concat(column))){ - mapKey = domainName; - } else mapKey = row.concat(column); - - domainStagingMap.put(mapKey, domainID+"%"+domainName); - } - } - i++; - } - - if(domainStagingMap != null && !domainStagingMap.isEmpty()){ - for(String domainsKey: new TreeSet<String>(domainStagingMap.keySet())){ - String value = domainStagingMap.get(domainsKey); - if(value.contains("%")){ - domainMap.put(domainsKey, fetchDomainObject(value.substring(0,value.indexOf("%")),value.substring(value.indexOf("%")+1))); - } - } - } - } - - for(String domainkey : domainMap.keySet()){ - Domain c = (Domain) domainMap.get(domainkey); - } - - } - - - } - - Layout dynamicLayout = new Layout(domainMap, 2, 10, 1, 5); - - dynamicLayout.computeDomainPositionsModified(); - Map<String,Domain> resultDomain2= dynamicLayout.domainRowCol; - - for (String key : resultDomain2.keySet()) { - if (resultDomain2.get(key).getP() !=null) { - - } - } - - ElementMapService cm2 = new ElementMapService(); - try { - - if(args != null && args.length > 0 ) { - - if( args[0] != null) { - String collapsedDomains[] = args[0].split(","); - for(String collapsedDomain : collapsedDomains) - dynamicLayout.collapseDomainNew(collapsedDomain); - } - - if( args[1] != null) { - String expandedDomains[] = args[1].split(","); - for(String expandedDomain : expandedDomains) - dynamicLayout.uncollapseDomainNew1(expandedDomain); - } - - return cm2.convertToYAML(dynamicLayout); - - } - }catch (Exception e) { - - e.printStackTrace(); - } - - - return ""; - - - } - - private static int computeRows(Set<String> keys){ - int i = 0; - if(keys!= null && !keys.isEmpty()){ - for(String s: keys){ - String r = s.substring(0, 1); - if(StringUtils.isNumeric(r)){ - int j = Integer.parseInt(r); - if(i<= j){ - i=j; - } - - } - } - - return i+1; - } - - return 1; - } - - private static int computeColumns(Set<String> keys){ - int i = 0; - if(keys!= null && !keys.isEmpty()){ - for(String s: keys){ - String r = s.substring(1, 2); - if(StringUtils.isNumeric(r)){ - int j = Integer.parseInt(r); - if(i<= j){ - i=j; - } - - } - } - - return i+1; - } - - return 1; - } - - private static Container fetchContainerObject(String id, String name, boolean isInner, String logicalGroupName, String domain){ - Map<String,Element> containerElementsMap = new HashMap<String, Element>(); - - containerElementsMap = fetchElementsMapForContainer(name, isInner, logicalGroupName, domain); - int rows = 1; - int columns = 1; - - if(isInner){ - - if(containerElementsMap != null && !containerElementsMap.isEmpty()){ - rows = computeRows(containerElementsMap.keySet()); - columns = computeColumns(containerElementsMap.keySet()); - } - - Container thisContainer = new Container(id, name, rows, columns, 1, 4, 8, 12, 1, 2); - thisContainer.setElements(containerElementsMap); - - return thisContainer; - } else { - Map<String,Container> innerContainersMap = fetchInnerContainersMapForOuter(name, isInner, logicalGroupName,domain); - - if(innerContainersMap != null && !innerContainersMap.isEmpty()){ - if(containerElementsMap != null && !containerElementsMap.isEmpty()){ - Set<String> keys = new HashSet<String>(innerContainersMap.keySet()); - keys.addAll(containerElementsMap.keySet()); - rows = computeRows(keys); - columns = computeColumns(keys); - } else { - rows = computeRows(innerContainersMap.keySet()); - columns = computeColumns(innerContainersMap.keySet()); - } - } else if(containerElementsMap != null && !containerElementsMap.isEmpty()){ - rows = computeRows(containerElementsMap.keySet()); - columns = computeColumns(containerElementsMap.keySet()); - } - - Container thisContainer = new Container(id, name, rows, columns,2 , 6, 2, 5, 0, 0); - thisContainer.setElements(containerElementsMap); - thisContainer.setInnerContainer(innerContainersMap); - - - return thisContainer; - } - - } - - private static Domain fetchDomainObject(String id, String name){ - HashMap<String,Container> domainContainersMap = fetchContainersForDomain(name); - - int rows = 1; - int columns = 1; - if(domainContainersMap != null && !domainContainersMap.isEmpty()){ - rows = computeRows(domainContainersMap.keySet()); - columns = computeColumns(domainContainersMap.keySet()); - } - - double domainWidth = 11; - Domain thisDomain; - - if(domainMap != null && !domainMap.isEmpty()){ - int domainsCountSoFar = domainMap.size(); - switch(domainsCountSoFar){ - case 1: {domainWidth = 12.1; break;} - case 2: {domainWidth = 13.3; break;} - case 3: {domainWidth = 14.5; break;} - case 4: {domainWidth = 15.6; break;} - default: {domainWidth = 11; break;} - } - - for(String domainsKey: new TreeSet<String>(domainMap.keySet())){ - Domain eachDomain = domainMap.get(domainsKey); - domainWidth+= eachDomain.computeSize().getWidth(); - } - thisDomain = new Domain(id, name, 2, 2, domainWidth, 10, 3, rows, columns); - } else { - - thisDomain = new Domain(id, name, 2, 1, 11, 10, 3, rows, columns); - } - - thisDomain.setContainers(domainContainersMap); - - thisDomain.computeConatinerPositions(); - if(domainContainersMap!= null && !domainContainersMap.isEmpty()){ - for(Container thisContainer : domainContainersMap.values()){ - thisContainer.computeSize(); - thisContainer.computeElementPositions(); - Map<String,Element> resultElementMap = thisContainer.elementRowCol; - for (String key : resultElementMap.keySet()) { - if(resultElementMap.get(key) == null || resultElementMap.get(key).getP() == null) { - } - - } - - HashMap<String,Container> innerContainersMap = (HashMap<String, Container>) thisContainer.getContainerRowCol(); - if(innerContainersMap != null && !innerContainersMap.isEmpty()){ - for(Container thisInnerContainer : innerContainersMap.values()){ - thisInnerContainer.computeElementPositions(); - } - } - } - } - - return thisDomain; - } - - private static HashMap<String,Container> fetchContainersForDomain(String domain){ - HashMap<String,Container> domainContainersMap = new HashMap<String, Container>(); - - domainContainersMap = fetchFromOuterContainers(domain); - - return domainContainersMap; - - } - - @SuppressWarnings("unchecked") - private static Element fetchElementObject(String id, String name, String imgPath){ - String bgColor = "bgColor"; - String logical_group; - String display_longname; - String display_shortname; - String description; - String primary_function; - String key_interfaces; - String location; - String vendor; - String vendor_shortname; - String enclosingContainer; - String borderType; - String network_function; - - if(toscaElementsMap.containsKey(name)){ - - if(toscaElementsMap.get(name) != null && toscaElementsMap.get(name) instanceof HashMap){ - HashMap<String, Object> toscaElementDetails = (HashMap<String, Object>) toscaElementsMap.get(name); - - for(String detailsKey: toscaElementDetails.keySet()){ - if("properties".equalsIgnoreCase(detailsKey) && toscaElementDetails.get(detailsKey) instanceof HashMap){ - HashMap<String, String> elementDetails = (HashMap<String, String>) toscaElementDetails.get(detailsKey); - - if(elementDetails != null){ - logical_group = elementDetails.get("logical_group") == null? "" : elementDetails.get("logical_group").toString(); - display_longname = elementDetails.get("display_longname") == null? "" : elementDetails.get("display_longname").toString(); - display_shortname = elementDetails.get("display_shortname") == null? "" : elementDetails.get("display_shortname").toString(); - description = elementDetails.get("description") == null? "" : elementDetails.get("description").toString(); - primary_function = elementDetails.get("primary_function") == null? "" : elementDetails.get("primary_function").toString(); - key_interfaces = elementDetails.get("key_interfaces") == null? "" : elementDetails.get("key_interfaces").toString(); - location = elementDetails.get("location") == null? "" : elementDetails.get("location").toString(); - vendor = elementDetails.get("vendor") == null? "" : elementDetails.get("vendor").toString(); - vendor_shortname = elementDetails.get("vendor_shortname") == null? "" : elementDetails.get("vendor_shortname").toString(); - enclosingContainer = logical_group.replace("/", "-"); - network_function = elementDetails.get("network_function"); - borderType = elementDetails.get("network_function") == null? "P" : elementDetails.get("network_function").toString().toUpperCase(); - bgColor = elementDetails.get("background_color") == null? "bgColor" : elementDetails.get("background_color").toString(); - - ElementDetails details = new ElementDetails(logical_group,display_longname,description,primary_function, network_function, - key_interfaces,location,vendor,vendor_shortname,enclosingContainer); - - return new Element(name, display_shortname, imgPath, bgColor,borderType, details); - } - - } - } - - } - - } else { - return new Element(id,name); - } - - return new Element(id,name); - } - - @SuppressWarnings("unchecked") - private static String fetchDomainNameOfElement(String name){ - if(toscaElementsMap.containsKey(name)){ - - if(toscaElementsMap.get(name) != null && toscaElementsMap.get(name) instanceof HashMap){ - HashMap<String, Object> toscaElementDetails = (HashMap<String, Object>) toscaElementsMap.get(name); - - for(String detailsKey: toscaElementDetails.keySet()){ - if("properties".equalsIgnoreCase(detailsKey) && toscaElementDetails.get(detailsKey) instanceof HashMap){ - HashMap<String, String> elementDetails = (HashMap<String, String>) toscaElementDetails.get(detailsKey); - - if(elementDetails != null){ - return elementDetails.get("domain") == null? "" : elementDetails.get("domain").toString(); - } - - } - } - - } - - } else { - return ""; - } - - return ""; - } - - private static HashMap<String, Container> fetchInnerContainersMapForOuter(String name, boolean isInner, String logicalGroupName, String domain){ - return fetchInnerContainersMap(name,logicalGroupName,domain); - } - - private static HashMap<String, Element> fetchElementsMapForContainer(String name, boolean isInner, String logicalGroupName, String domain){ - return fetchElementsMap(logicalGroupName,domain); - } - - private static HashMap<String, Container> fetchInnerContainersMap(String name, String logicalGroupName, String domain){ - HashMap<String,Container> containersMap = new HashMap<String, Container>(); - String rowColumnKey = ""; - int count = 0; - - if(innercontainers!=null && !innercontainers.isEmpty()){ - for(String key : innercontainers.keySet()){ - - - Container eachContainer = innercontainers.get(key); - - if(key.toUpperCase().contains((domain+":"+name).toUpperCase())){ - if(key.contains("/")){ - rowColumnKey = key.substring(key.lastIndexOf("/")+1); - } - - if(rowColumnKey.isEmpty() || containersMap.containsKey(rowColumnKey)){ - count=0; - while(count<=9){ - if(containersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))){ - count++; - } else - { - rowColumnKey = String.valueOf(count).concat(String.valueOf(count)); - break; - } - } - - - } - - containersMap.put(rowColumnKey,eachContainer); - } - - - } - } - return containersMap.isEmpty()?null:containersMap; - - } - - private static HashMap<String, Container> fetchFromOuterContainers(String domain){ - HashMap<String,Container> thisContainersMap = new HashMap<String, Container>(); - String rowColumnKey = ""; - int count = 0; - - if(outercontainers!=null && !outercontainers.isEmpty()){ - for(String key : outercontainers.keySet()){ - Container eachContainer = outercontainers.get(key); - - if(key.toUpperCase().contains((domain+":").toUpperCase())){ - if(key.contains("/")){ - rowColumnKey = key.substring(key.lastIndexOf("/")+1); - } - - if(rowColumnKey.isEmpty() || thisContainersMap.containsKey(rowColumnKey)){ - count=0; - while(count<=9){ - if(thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))){ - count++; - } else - { - rowColumnKey = String.valueOf(count).concat(String.valueOf(count)); - break; - } - } - - - } - - thisContainersMap.put(rowColumnKey,eachContainer); - } - } - - } - - //Misc Elements Containers - - if(miscElementMap!=null && !miscElementMap.isEmpty()){ - for(String key : miscElementMap.keySet()){ - Element eachElement = miscElementMap.get(key); - String elementName = eachElement.getName(); - String domainName = fetchDomainNameOfElement(elementName); - - if(domain.equalsIgnoreCase(domainName)){ - Container eachContainer = new Container(domainName+":"+elementName, elementName, 1, 1, 3, 6, 2, 5, 0, 0); - count=0; - while(count<=9){ - if(thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))){ - count++; - } else - { - rowColumnKey = String.valueOf(count).concat(String.valueOf(count)); - break; - } - } - - thisContainersMap.put(rowColumnKey,eachContainer); - } - - - } - - } - - - return thisContainersMap.isEmpty()?null:thisContainersMap; - } - - - - @SuppressWarnings("unused") - private static HashMap<String,Container> addOuterContainersForMiscElements(String domain){ - HashMap<String,Container> containerElementsMap = new HashMap<String, Container>(); - if(miscElementMap!=null && !miscElementMap.isEmpty()){ - for(String key : miscElementMap.keySet()){ - Element eachElement = miscElementMap.get(key); - String elementName = eachElement.getName(); - String domainName = fetchDomainNameOfElement(elementName); - - if(domain.equalsIgnoreCase(domainName)){ - Container newContainer = new Container(domainName+":"+elementName, elementName, 1, 1, 3, 6, 2, 5, 0, 0); - containerElementsMap.put(domainName+":"+elementName, newContainer); - } - - - } - - } - return containerElementsMap.isEmpty()? null:containerElementsMap; - } - - private static HashMap<String, Element> fetchElementsMap(String logicalGroupName, String domain){ - HashMap<String,Element> innerElementMap = new HashMap<String, Element>(); - String rowColumnKey = ""; - int count = 0; - - if(elementMap!=null && !elementMap.isEmpty()){ - for(String key : elementMap.keySet()){ - Element eachElement = elementMap.get(key); - - String elementName = eachElement.getId(); - String elementLogicalGroup = eachElement.details == null ? "" : eachElement.details.logical_group; - if(elementLogicalGroup.equalsIgnoreCase(logicalGroupName) && domain.equalsIgnoreCase(fetchDomainNameOfElement(elementName))){ - if(key.contains("/")){ - rowColumnKey = key.substring(key.indexOf("/")+1); - } - - if(rowColumnKey.isEmpty() || innerElementMap.containsKey(rowColumnKey)){ - count=0; - while(count<=9){ - if(innerElementMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))){ - count++; - } else - { - rowColumnKey = String.valueOf(count).concat(String.valueOf(count)); - break; - } - } - - - } - - innerElementMap.put(rowColumnKey,eachElement); - miscElementMap.remove(key); - } - - } - } - - return innerElementMap.isEmpty()?null:innerElementMap; - } - - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/FnMenuService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/FnMenuService.java deleted file mode 100644 index 040c9d26..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/FnMenuService.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.openecomp.portalsdk.core.domain.Menu; -import org.openecomp.portalsdk.core.domain.MenuData; -import org.openecomp.portalsdk.core.domain.RoleFunction; - -/** - * Description: this java class is an interface of services for Admin to add/edit/delete menu items from FN_MENU - */ -public interface FnMenuService { - List<MenuData> getFnMenuItems(); - void saveFnMenuData(MenuData domainFnMenu); - void saveFnMenu(Menu domainFnMenu); - void removeMenuItem(MenuData domainFnMenu); - MenuData getMenuItemRow(Long id); - Menu getMenuItem(Long id); - List<Long> getParentId(String label); - @SuppressWarnings("rawtypes") - List<List> getParentList(); - List<RoleFunction> getFunctionCDList(); - void removeMenuItem(Menu domainFnMenu); - Map<String, List<MenuData>> setMenuDataStructure(List<List<MenuData>> childItemList, List<MenuData> parentList, Set<MenuData> menuResult) throws Exception; -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/FnMenuServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/FnMenuServiceImpl.java deleted file mode 100644 index b17be180..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/FnMenuServiceImpl.java +++ /dev/null @@ -1,145 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.openecomp.portalsdk.core.domain.Menu; -import org.openecomp.portalsdk.core.domain.MenuData; -import org.openecomp.portalsdk.core.domain.RoleFunction; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - * Description: this java class is an implementation of services for Admin to add/edit/delete menu items from FN_MENU - */ - -@Service("fnMenuService") -@Transactional -public class FnMenuServiceImpl implements FnMenuService{ - - @Autowired - private DataAccessService dataAccessService; - - @SuppressWarnings("unchecked") - public List<MenuData> getFnMenuItems() { - return getDataAccessService().getList(MenuData.class, null, "1", null); - - } - - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - - @Override - public void saveFnMenuData(MenuData domainFnMenu) { - // TODO Auto-generated method stub - getDataAccessService().saveDomainObject(domainFnMenu, null); - - } - - @SuppressWarnings("unchecked") - @Override - public List<Long> getParentId(String label) { - // TODO Auto-generated method stub - Map<String, String> params = new HashMap<String, String>(); - params.put("paramLabel", label); - return getDataAccessService().executeNamedQuery("IdForLabelList", params, null); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public List<List> getParentList() { - // TODO Auto-generated method stub - - return getDataAccessService().executeNamedQuery("parentList", null, null); - - } - - @SuppressWarnings("unchecked") - @Override - public List<RoleFunction> getFunctionCDList() { - // TODO Auto-generated method stub - - return getDataAccessService().executeNamedQuery("functionCDlist", null, null); - - } - - @Override - public void removeMenuItem(MenuData domainFnMenu) { - getDataAccessService().deleteDomainObject(domainFnMenu, null); - } - - @Override - public void removeMenuItem(Menu domainFnMenu) { - getDataAccessService().deleteDomainObject(domainFnMenu, null); - } - - public MenuData getMenuItemRow(Long id) { - return (MenuData)getDataAccessService().getDomainObject(MenuData.class, id, null); - } - - @Override - public Menu getMenuItem(Long id) { - return (Menu)getDataAccessService().getDomainObject(Menu.class, id, null); - } - - @Override - public void saveFnMenu(Menu domainFnMenu) { - // TODO Auto-generated method stub - getDataAccessService().saveDomainObject(domainFnMenu, null); - - } - @Override - public Map<String, List<MenuData>> setMenuDataStructure(List<List<MenuData>> childItemList, List<MenuData> parentList, Set<MenuData> menuResult) throws Exception{ - for(MenuData menu: menuResult){ - MenuData parentData = new MenuData(); - parentData.setLabel(menu.getLabel()); - parentData.setAction(menu.getAction()); - parentData.setImageSrc(menu.getImageSrc()); - parentList.add(parentData); - List<MenuData> tempList = new ArrayList<MenuData>(); - for(Object o:menu.getChildMenus()){ - MenuData m = (MenuData)o; - MenuData data = new MenuData(); - data.setLabel(m.getLabel()); - data.setAction(m.getAction()); - data.setImageSrc(m.getImageSrc()); - tempList.add(data); - } - childItemList.add(tempList); - } - return null; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LdapService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LdapService.java deleted file mode 100644 index 9c790eb2..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LdapService.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import org.openecomp.portalsdk.core.command.support.SearchResult; -import org.openecomp.portalsdk.core.domain.support.DomainVo; - - -public interface LdapService { - - // search POST for users based on the criteria selected in the Request - SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, int dataSize, int userId) throws Exception; - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LdapServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LdapServiceImpl.java deleted file mode 100644 index d1176c1c..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LdapServiceImpl.java +++ /dev/null @@ -1,269 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.SearchControls; - -import org.openecomp.portalsdk.core.command.support.SearchResult; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.domain.support.DomainVo; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.support.FusionService; -import org.openecomp.portalsdk.core.service.support.ServiceLocator; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("ldapService") -@Transactional -public class LdapServiceImpl extends FusionService implements LdapService { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LdapServiceImpl.class); - @Autowired - private ServiceLocator serviceLocator; - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, - int pageNo, int dataSize, int userId) throws Exception { - - // initialize the directory context to access POST - DirContext dirContext = serviceLocator.getDirContext(SystemProperties.getProperty(SystemProperties.POST_INITIAL_CONTEXT_FACTORY), - SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL), - SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL)); - - SearchResult searchResult = new SearchResult(); - - try { - - String[] postAttributes = {"nickname","givenName","initials","sn","employeeNumber","mail","telephoneNumber", - "departmentNumber","a1","street","roomNumber","l","st","postalCode","zip4","physicalDeliveryOfficeName","bc", - "friendlyCountryName","bd","bdname","bu","buname","jtname","mgrid","a2","compcode","compdesc", - "costcenter","silo","b2"}; - - SearchControls searchControls = new SearchControls(); - searchControls.setTimeLimit(5000); - searchControls.setReturningAttributes(postAttributes); - - StringBuffer filterClause = new StringBuffer("(&(objectClass=*)"); - - User user = (User)searchCriteria; - - if(Utilities.nvl(user.getFirstName()).length() > 0) { - filterClause.append("(givenName=").append(user.getFirstName()).append("*)"); - } - if(Utilities.nvl(user.getLastName()).length() > 0) { - filterClause.append("(sn=").append(user.getLastName()).append("*)"); - } - if(Utilities.nvl(user.getHrid()).length() > 0) { - filterClause.append("(employeeNumber=").append(user.getHrid()).append("*)"); - } - if(Utilities.nvl(user.getOrgManagerUserId()).length() > 0) { - filterClause.append("(mgrid=").append(user.getOrgManagerUserId()).append("*)"); - } - if(Utilities.nvl(user.getOrgCode()).length() > 0) { - filterClause.append("(departmentNumber=").append(user.getOrgCode()).append("*)"); - } - if(Utilities.nvl(user.getEmail()).length() > 0) { - filterClause.append("(mail=").append(user.getEmail()).append("*)"); - } - if(Utilities.nvl(user.getOrgUserId()).length() > 0) { - filterClause.append("(a1=").append(user.getOrgUserId()).append("*)"); - } - filterClause.append("(c3=N)"); // this has been added to filter CP09 entries on the LDAP server that are duplicates of existing individuals - filterClause.append(")"); - - List list = new ArrayList(); - if (!filterClause.toString().equals("(&(objectClass=*))")) { - NamingEnumeration e = dirContext.search(SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL) + "/" + - SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL), - filterClause.toString(), - searchControls); - - list = processResults(e); - } - - Collections.sort(list); - - searchResult = new SearchResult(list); - searchResult.setPageNo(pageNo); - if(dataSize >= 0) { - searchResult.setDataSize(dataSize); - } - else { - searchResult.setDataSize(list.size()); - } // else - - } - catch(NamingException ne) { - logger.error(EELFLoggerDelegate.errorLogger,ne.getMessage()); - } - finally { - dirContext.close(); - } - - return searchResult; - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private ArrayList processResults(NamingEnumeration e) throws NamingException { - ArrayList results = new ArrayList(); - int count = 0; - - while (e.hasMore()) { - javax.naming.directory.SearchResult searchResult = (javax.naming.directory.SearchResult)e.next(); - results.add(processAttributes(searchResult.getAttributes())); - count++; - - if(count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) { - break; - } - - } - - return results; - } - - - @SuppressWarnings("rawtypes") - private DomainVo processAttributes(Attributes resultAttributes) throws NamingException { - User user = new User(); - - try { - if (resultAttributes == null) { - System.out.println("This result has no attributes"); - } else { - for (NamingEnumeration e = resultAttributes.getAll(); e.hasMore();) { //why the nested loop? - Attribute attribute = (Attribute)e.next(); - for (NamingEnumeration ie = attribute.getAll(); ie.hasMore();) { - if (attribute.getID().equalsIgnoreCase("nickname")) { - user.setFirstName((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("initials")) { - user.setMiddleInitial((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("sn")) { - user.setLastName((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("employeeNumber")) { - user.setHrid((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("mail")) { - user.setEmail((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("telephoneNumber")) { - user.setPhone((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("departmentNumber")) { - user.setOrgCode((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("a1")) { - user.setOrgUserId((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("street")) { - user.setAddress1((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("roomNumber")) { - user.setAddress2((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("l")) { - user.setCity((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("st")) { - user.setState((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("postalCode")) { - user.setZipCode((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("zip4")) { - user.setZipCodeSuffix((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("physicalDeliveryOfficeName")) { - user.setLocationClli((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("bc")) { - user.setBusinessCountryCode((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("friendlyCountryName")) { - user.setBusinessCountryName((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("bd")) { - user.setDepartment((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("bdname")) { - user.setDepartmentName((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("jtname")) { - user.setJobTitle((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("mgrid")) { - user.setOrgManagerUserId((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("a2")) { - user.setCommandChain((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("compcode")) { - user.setCompanyCode((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("compdesc")) { - user.setCompany((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("bu")) { - user.setBusinessUnit((String)ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("buname")) { - user.setBusinessUnitName((String)ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("silo")) { - user.setSiloStatus((String)ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("costcenter")) { - user.setCostCenter((String)ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("b2")) { - user.setFinancialLocCode((String)ie.next()); - } - else { //we don't care about returned attribute, let's move on - ie.next(); - } - - } - } - } - } catch (NamingException e) { - logger.error(EELFLoggerDelegate.errorLogger, "An error occurred while processing the following user from POST with an ORGUSERID of " + user.getOrgUserId() + e.getMessage()); - } finally { - - } - return user; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LoginService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LoginService.java deleted file mode 100644 index 113833bf..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LoginService.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - - -import java.util.HashMap; - -import org.openecomp.portalsdk.core.command.LoginBean; - - -public interface LoginService { - - // validate user exists in the system - @SuppressWarnings("rawtypes") - LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams) throws Exception; - - @SuppressWarnings("rawtypes") - LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception; -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LoginServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LoginServiceImpl.java deleted file mode 100644 index 7da427ba..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/LoginServiceImpl.java +++ /dev/null @@ -1,190 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.openecomp.portalsdk.core.command.LoginBean; -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.menu.MenuBuilder; -import org.openecomp.portalsdk.core.service.support.FusionService; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.AppUtils; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("loginService") -@Transactional -public class LoginServiceImpl extends FusionService implements LoginService { - - @SuppressWarnings("unused") - private MenuBuilder menuBuilder; - - @Autowired - private DataAccessService dataAccessService; - - - @SuppressWarnings("rawtypes") - public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams ) throws Exception { - return findUser(bean, menuPropertiesFilename, additionalParams, true); - } - - @SuppressWarnings("rawtypes") - public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception { - User user = null; - User userCopy = null; - - if (bean.getUserid() != null && bean.getUserid() != null) { - user = (User)findUser(bean); - } - else { - if (matchPassword) - user = (User)findUser(bean.getLoginId(), bean.getLoginPwd()); - else - user = (User)findUserWithoutPwd(bean.getLoginId()); - } - - if (user != null) { - - // raise an error if the application is locked and the user does not have system administrator privileges - if (AppUtils.isApplicationLocked() && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) { - bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED); - } - - // raise an error if the user is inactive - if (!user.getActive()) { - bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE); - } - - 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; - } - - @SuppressWarnings("rawtypes") - private boolean userHasActiveRoles(User user) { - boolean hasActiveRole = false; - Iterator roles = user.getRoles().iterator(); - while (roles.hasNext()) { - Role role = (Role)roles.next(); - if (role.getActive()) { - hasActiveRole = true; - break; - } - } - return hasActiveRole; - } - - - @SuppressWarnings("rawtypes") - public User findUser(String loginId, String password) { - List list = null; - - StringBuffer criteria = new StringBuffer(); - criteria.append(" where login_id = '").append(loginId).append("'") - .append(" and login_pwd = '").append(password).append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); - - return (list == null || list.size() == 0) ? null : (User)list.get(0); - } - - @SuppressWarnings("rawtypes") - private User findUserWithoutPwd(String loginId) { - List list = null; - - StringBuffer criteria = new StringBuffer(); - criteria.append(" where login_id = '").append(loginId).append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); - - return (list == null || list.size() == 0) ? null : (User)list.get(0); - } - - - @SuppressWarnings("rawtypes") - public User findUser(LoginBean bean) { - List list = null; - - StringBuffer criteria = new StringBuffer(); - criteria.append(" where org_user_id = '").append(bean.getUserid()).append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); - - return (list == null || list.size() == 0) ? null : (User)list.get(0); - } - - - public MenuBuilder getMenuBuilder() { - return new MenuBuilder(); - } - - - public void setMenuBuilder(MenuBuilder menuBuilder) { - this.menuBuilder = menuBuilder; - } - - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsService.java deleted file mode 100644 index 596ebed2..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsService.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.List; - -import org.openecomp.portalsdk.core.command.PostDroolsBean; - -public interface PostDroolsService { - - String execute(String droolsFile, String className, String selectedRules); - - List<PostDroolsBean> fetchDroolBeans(); - - String retrieveClass(String droolsFile); - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsServiceImpl.java deleted file mode 100644 index 726d8973..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostDroolsServiceImpl.java +++ /dev/null @@ -1,179 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.io.File; -import java.io.IOException; -import java.nio.file.DirectoryIteratorException; -import java.nio.file.DirectoryStream; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.kie.api.io.ResourceType; -import org.kie.internal.KnowledgeBase; -import org.kie.internal.KnowledgeBaseFactory; -import org.kie.internal.builder.KnowledgeBuilder; -import org.kie.internal.builder.KnowledgeBuilderFactory; -import org.kie.internal.definition.KnowledgePackage; -import org.kie.internal.io.ResourceFactory; -import org.kie.internal.runtime.StatefulKnowledgeSession; -import org.openecomp.portalsdk.core.command.PostDroolsBean; -import org.openecomp.portalsdk.core.drools.DroolsRuleService; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import com.fasterxml.jackson.databind.ObjectMapper; - - -@Service("postDroolsService") -@Transactional -public class PostDroolsServiceImpl implements PostDroolsService{ - - static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostDroolsServiceImpl.class); - - @Override - public String execute(String droolsFile, String className, String selectedRules) { - logger.info(EELFLoggerDelegate.applicationLogger, "Executing Drools..."); - String resultsString = executeDemoRules(droolsFile, className, selectedRules); - return resultsString; - } - - - public List<PostDroolsBean> fetchDroolBeans() { - - List<PostDroolsBean> beanList = new ArrayList<PostDroolsBean>(); - Path path = FileSystems.getDefault().getPath(SystemProperties.getProperty(SystemProperties.FILES_PATH)); - try (DirectoryStream<Path> stream = Files.newDirectoryStream(path,"*.{drl}")) { - for (Path entry: stream) { - - PostDroolsBean postDroolsBean = new PostDroolsBean(); - String fileName = entry.getName(entry.getNameCount()-1).toString(); - postDroolsBean.setDroolsFile(fileName);//sample populated - postDroolsBean.setClassName(retrieveClass(fileName)); - //postDroolsBean.setSelectedRules("[\"NJ\",\"NY\",\"KY\"]"); - beanList.add(postDroolsBean); - } - } catch (DirectoryIteratorException ex) { - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage()); - } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); - } - return beanList; - } - - @Override - public String retrieveClass(String fileName) { - String resultsString = ""; - try { - // load up the knowledge base - final KnowledgeBuilder kbuilder = loadKBuilder(fileName); - final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages(); - return pkgs.iterator().next().getFactTypes().iterator().next().getFactClass().getName(); - - } catch (Throwable t) { - logger.error(EELFLoggerDelegate.errorLogger, t.getMessage()); - } - - return resultsString; - } - - protected static KnowledgeBuilder loadKBuilder(String fileName) { - final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - - // this will parse and compile in one step - kbuilder.add(ResourceFactory.newFileResource(SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + fileName), - ResourceType.DRL); - - if (kbuilder.hasErrors()) { - - logger.error(EELFLoggerDelegate.errorLogger, kbuilder.getErrors().toString()); - - throw new RuntimeException("Unable to compile \".drl\"."); - - } - return kbuilder; - } - - - @SuppressWarnings({ "deprecation", "unchecked" }) - public static String executeDemoRules(String fileName, String className, String ruleValue) { - String resultsString = ""; - try { - // load up the knowledge base - // KieServices ks = KieServices.Factory.get(); - // KieContainer kContainer = ks.getKieClasspathContainer(); - // KieSession kSession = kContainer.newKieSession("ksession-rules"); - - final KnowledgeBuilder kbuilder = loadKBuilder(fileName); - - // get the compiled packages (which are serializable) - - final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages(); - - // add the packages to a knowledgebase (deploy the knowledge - // packages). - - final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - - kbase.addKnowledgePackages(pkgs); - - final StatefulKnowledgeSession kSession = kbase.newStatefulKnowledgeSession(); - - ObjectMapper mapper = new ObjectMapper(); - if(ruleValue == null || ruleValue.equals("")) { - resultsString = "Please enter valid rule"; - return resultsString; - } - List<String> selectedRules = mapper.readValue(ruleValue, List.class); - List<String> ruleResponse = new ArrayList<String>(); - - for(String rule : selectedRules){ - Class<DroolsRuleService> clazz = (Class<DroolsRuleService>) Class.forName(className); - DroolsRuleService droolsIntroduction =clazz.newInstance(); - droolsIntroduction.init(rule); - kSession.insert(droolsIntroduction); - kSession.fireAllRules(); - ruleResponse.add(droolsIntroduction.getResultsString()); - } - - resultsString = mapper.writeValueAsString(ruleResponse); - -// kSession.insert(new DroolsRuleService("KY")); -// kSession.fireAllRules(); -// -// kSession.setGlobal("age", "25"); -// kSession.insert(new DroolsRuleService("NY")); -// kSession.fireAllRules(); - } catch (Throwable t) { - logger.error(EELFLoggerDelegate.errorLogger, t.getMessage()); - } - - return resultsString; - } - - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostSearchService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostSearchService.java deleted file mode 100644 index 55c9db3f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostSearchService.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.portalsdk.core.command.PostSearchBean; - -public interface PostSearchService { - - void process(HttpServletRequest request, PostSearchBean postSearch); - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostSearchServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostSearchServiceImpl.java deleted file mode 100644 index 2ecedbea..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/PostSearchServiceImpl.java +++ /dev/null @@ -1,203 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.portalsdk.core.FusionObject.Parameters; -import org.openecomp.portalsdk.core.command.PostSearchBean; -import org.openecomp.portalsdk.core.domain.Lookup; -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.FeedbackMessage; -import org.openecomp.portalsdk.core.web.support.MessagesList; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("postSearchService") -@Transactional -public class PostSearchServiceImpl implements PostSearchService{ - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostSearchServiceImpl.class); - - @Autowired - private DataAccessService dataAccessService; - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void process(HttpServletRequest request, PostSearchBean postSearch) { - HashMap additionalParams = new HashMap(); - additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request); - - if (postSearch.getSelected() != null) { - //sort the selected users for quick validation - - Arrays.sort(postSearch.getSelected()); - System.out.println("list - " + postSearch.getPostOrgUserId().length); - // import the users that have been selected - for(int i=0; i < postSearch.getPostOrgUserId().length; i++){ - if (Arrays.binarySearch(postSearch.getSelected(), postSearch.getPostOrgUserId()[i]) >= 0) { - logger.info(EELFLoggerDelegate.debugLogger, "Adding ORGUSERID - " + postSearch.getPostOrgUserId()[i]); - logger.info(EELFLoggerDelegate.auditLogger, "Import new user from webphone " + postSearch.getPostOrgUserId()[i]); - - User user = new User(); - user.setLastName(postSearch.getPostLastName()[i]); - user.setFirstName(postSearch.getPostFirstName()[i]); - - if (postSearch.getPostHrid() != null && postSearch.getPostHrid().length > 0) { - user.setHrid(postSearch.getPostHrid()[i]); - } - - if (postSearch.getPostPhone() != null && postSearch.getPostPhone().length > 0) { - user.setPhone(postSearch.getPostPhone()[i]); - } - - if (postSearch.getPostEmail() != null && postSearch.getPostEmail().length > 0) { - user.setEmail(postSearch.getPostEmail()[i]); - } - - if (postSearch.getPostOrgUserId() != null && postSearch.getPostOrgUserId().length > 0) { - user.setOrgUserId(postSearch.getPostOrgUserId()[i]); - user.setLoginId(postSearch.getPostOrgUserId()[i]); - } - - if (postSearch.getPostAddress1() != null && postSearch.getPostAddress1().length > 0) { - user.setAddress1(postSearch.getPostAddress1()[i]); - } - - if (postSearch.getPostAddress2() != null && postSearch.getPostAddress2().length > 0) { - user.setAddress2(postSearch.getPostAddress2()[i]); - } - - if (postSearch.getPostCity() != null && postSearch.getPostCity().length > 0) { - user.setCity(postSearch.getPostCity()[i]); - } - - if (postSearch.getPostState() != null && postSearch.getPostState().length > 0) { - user.setState(postSearch.getPostState()[i]); - } - - if (postSearch.getPostZipCode() != null && postSearch.getPostZipCode().length > 0) { - user.setZipCode(postSearch.getPostZipCode()[i]); - } - - if (postSearch.getPostLocationClli() != null && postSearch.getPostLocationClli().length > 0) { - user.setLocationClli(postSearch.getPostLocationClli()[i]); - } - - if (postSearch.getPostBusinessCountryCode() != null && postSearch.getPostBusinessCountryCode().length > 0) { - user.setBusinessCountryCode(postSearch.getPostBusinessCountryCode()[i]); - } - - if (postSearch.getPostBusinessCountryName() != null && postSearch.getPostBusinessCountryName().length > 0) { - - // find the country cd for the indicated country - List countries = dataAccessService.getLookupList("fn_lu_country", "country_cd", "country", "country = '" - + postSearch.getPostBusinessCountryName()[i] + "'", null, null); - - if (countries!=null&&countries.size() == 1) { - Lookup country = (Lookup)countries.get(0); - user.setCountry(country.getValue()); - } - else { - logger.info(EELFLoggerDelegate.debugLogger, "No countries or more than one country was found matching the country returned from WEBPHONE. " + - "Therefore, no country was set for this user."); - } - - } - - if (postSearch.getPostDepartment() != null && postSearch.getPostDepartment().length > 0) { - user.setDepartment(postSearch.getPostDepartment()[i]); - } - - if (postSearch.getPostDepartmentName() != null && postSearch.getPostDepartmentName().length > 0) { - user.setDepartmentName(postSearch.getPostDepartmentName()[i]); - } - - if (postSearch.getPostBusinessUnit() != null && postSearch.getPostBusinessUnit().length > 0) { - user.setBusinessUnit(postSearch.getPostBusinessUnit()[i]); - } - - if (postSearch.getPostBusinessUnitName() != null && postSearch.getPostBusinessUnitName().length > 0) { - user.setBusinessUnitName(postSearch.getPostBusinessUnitName()[i]); - } - - if (postSearch.getPostJobTitle() != null && postSearch.getPostJobTitle().length > 0) { - user.setJobTitle(postSearch.getPostJobTitle()[i]); - } - - if (postSearch.getPostOrgManagerUserId() != null && postSearch.getPostOrgManagerUserId().length > 0) { - user.setOrgManagerUserId(postSearch.getPostOrgManagerUserId()[i]); - } - - if (postSearch.getPostCommandChain() != null && postSearch.getPostCommandChain().length > 0) { - user.setCommandChain(postSearch.getPostCommandChain()[i]); - } - - if (postSearch.getPostCompanyCode() != null && postSearch.getPostCompanyCode().length > 0) { - user.setCompanyCode(postSearch.getPostCompanyCode()[i]); - } - - if (postSearch.getPostCompany() != null && postSearch.getPostCompany().length > 0) { - user.setCompany(postSearch.getPostCompany()[i]); - } - - if (postSearch.getPostCostCenter() != null && postSearch.getPostCostCenter().length > 0) { - user.setCostCenter(postSearch.getPostCostCenter()[i]); - } - - if (postSearch.getPostSiloStatus() != null && postSearch.getPostSiloStatus().length > 0) { - user.setSiloStatus(postSearch.getPostSiloStatus()[i]); - } - - if (postSearch.getPostFinancialLocCode() != null && postSearch.getPostFinancialLocCode().length > 0) { - user.setFinancialLocCode(postSearch.getPostFinancialLocCode()[i]); - } - - user.setActive(true); - - try { - dataAccessService.saveDomainObject(user, additionalParams); - - Role role = (Role)dataAccessService.getDomainObject(Role.class,Long.valueOf(SystemProperties.getProperty(SystemProperties.POST_DEFAULT_ROLE_ID)), null); - user.addRole(role); - } - catch (Exception e) { - MessagesList messages = new MessagesList(); - messages.addExceptionMessage(new FeedbackMessage("An error occurred while attempting to import " + user.getFirstName() + " " - + user.getLastName() + ": " + e.getMessage(), FeedbackMessage.MESSAGE_TYPE_ERROR)); - - } - } - } - - } - - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ProfileService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ProfileService.java deleted file mode 100644 index 61bd3b6e..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ProfileService.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.List; - -import org.openecomp.portalsdk.core.domain.Profile; -import org.openecomp.portalsdk.core.domain.User; - - -public interface ProfileService { - List<Profile> findAll(); - - Profile getProfile(int id); - - User getUser(String id); - - void saveUser(User user); -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ProfileServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ProfileServiceImpl.java deleted file mode 100644 index 3927d727..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/ProfileServiceImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.List; - -import org.openecomp.portalsdk.core.dao.ProfileDao; -import org.openecomp.portalsdk.core.domain.Profile; -import org.openecomp.portalsdk.core.domain.User; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("profileService") -@Transactional -public class ProfileServiceImpl implements ProfileService{ - - @Autowired - private ProfileDao profileDao; - - @Autowired - private DataAccessService dataAccessService; - - @SuppressWarnings("unchecked") - public List<Profile> findAll() { - return getDataAccessService().getList(Profile.class, null); - } - - public User getUser(String userId){ - return (User) getDataAccessService().getDomainObject(User.class, Long.parseLong(userId), null); - } - - public void saveUser(User user){ - - getDataAccessService().saveDomainObject(user, null); - } - - - public Profile getProfile(int id) { - return profileDao.getProfile(id); - } - - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/RoleService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/RoleService.java deleted file mode 100644 index 01367ecd..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/RoleService.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.List; - -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.RoleFunction; - - -public interface RoleService { - List<RoleFunction> getRoleFunctions(); - - List<Role> getAvailableChildRoles(Long roleId); - - Role getRole(Long id); - - void saveRole(Role domainRole); - - void deleteRole(Role domainRole); - - List<Role> getAvailableRoles(); - - List<Role> getActiveRoles(); - - RoleFunction getRoleFunction(String code); - - void saveRoleFunction(RoleFunction domainRoleFunction); - - void deleteRoleFunction(RoleFunction domainRoleFunction); - - void deleteDependcyRoleRecord(Long id); -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceImpl.java deleted file mode 100644 index e71e0c58..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceImpl.java +++ /dev/null @@ -1,171 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import javax.sql.DataSource; - -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.RoleFunction; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("roleService") -@Transactional -public class RoleServiceImpl implements RoleService{ - - @Autowired - private DataAccessService dataAccessService; - - DataSource dataSource; - - public DataSource getDataSource() { - return dataSource; - } - - - @Autowired - public void setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - } - - @SuppressWarnings("unchecked") - public List<RoleFunction> getRoleFunctions() { - //List msgDB = getDataAccessService().getList(Profile.class, null); - return getDataAccessService().getList(RoleFunction.class, null); - } - - @SuppressWarnings("unchecked") - public List<Role> getAvailableChildRoles(Long roleId) { - List<Role> availableChildRoles = (List<Role>)getDataAccessService().getList(Role.class,null); - if(roleId==null || roleId==0){ - return availableChildRoles; - } - - Role currentRole = (Role)getDataAccessService().getDomainObject(Role.class,roleId,null); - Set<Role> allParentRoles = new TreeSet<Role>(); - allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles); - - - Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator(); - while (availableChildRolesIterator.hasNext()) { - Role role = availableChildRolesIterator.next(); - if(!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)){ - availableChildRolesIterator.remove(); - } - } - return availableChildRoles; - } - - @SuppressWarnings("unchecked") - private Set<Role> getAllParentRolesAsList(Role role, Set<Role> allParentRoles) { - Set<Role> parentRoles = role.getParentRoles(); - allParentRoles.addAll(parentRoles); - Iterator<Role> parentRolesIterator = parentRoles.iterator(); - while (parentRolesIterator.hasNext()) { - getAllParentRolesAsList(parentRolesIterator.next(),allParentRoles); - } - return allParentRoles; - } - - public RoleFunction getRoleFunction(String code) { - return (RoleFunction)getDataAccessService().getDomainObject(RoleFunction.class, code, null); - } - - public void saveRoleFunction(RoleFunction domainRoleFunction) { - getDataAccessService().saveDomainObject(domainRoleFunction, null); - } - - public void deleteRoleFunction(RoleFunction domainRoleFunction) { - getDataAccessService().deleteDomainObject(domainRoleFunction, null); - } - - public Role getRole(Long id) { - return (Role)getDataAccessService().getDomainObject(Role.class, id, null); - } - - public void saveRole(Role domainRole) { - getDataAccessService().saveDomainObject(domainRole, null); - } - - public void deleteRole(Role domainRole) { - getDataAccessService().deleteDomainObject(domainRole, null); - } - - @SuppressWarnings("unchecked") - public List<Role> getAvailableRoles() { - return getDataAccessService().getList(Role.class, null); - } - - @SuppressWarnings("unchecked") - @Override - public List<Role> getActiveRoles() { - String filter = " where active_yn = 'Y' "; - return getDataAccessService().getList(Role.class, filter, null,null); - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - @Override - public void deleteDependcyRoleRecord(Long id) { - - Connection conn = null; - Statement stmt = null; - - try { - conn = getDataSource().getConnection(); - stmt = conn.createStatement(); - String sql = "delete from fn_user_role where role_id = '" + id + "'"; - stmt.executeUpdate(sql); - stmt.close(); - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (stmt != null) - stmt.close(); - } catch (SQLException se2) {} - try { - if (conn != null) - conn.close(); - } catch (SQLException se) { se.printStackTrace();} - } - - } - - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceNonSpringImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceNonSpringImpl.java deleted file mode 100644 index bd6796c1..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/RoleServiceNonSpringImpl.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; -/*package org.openecomp.portalsdk.core.service; - -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.RoleFunction; - -@Service("roleService") -@Transactional -public class RoleServiceNonSpringImpl implements RoleService{ - - @Autowired - private DataAccessService dataAccessService; - - @SuppressWarnings("unchecked") - public List<RoleFunction> getRoleFunctions() { - //List msgDB = getDataAccessService().getList(Profile.class, null); - return getDataAccessService().getList(RoleFunction.class, null); - } - - @SuppressWarnings("unchecked") - public List<Role> getAvailableChildRoles(Long roleId) { - List<Role> availableChildRoles = (List<Role>)getDataAccessService().getList(Role.class,null); - if(roleId==null || roleId==0){ - return availableChildRoles; - } - - Role currentRole = (Role)getDataAccessService().getDomainObject(Role.class,roleId,null); - Set<Role> allParentRoles = new TreeSet<Role>(); - allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles); - - - Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator(); - while (availableChildRolesIterator.hasNext()) { - Role role = availableChildRolesIterator.next(); - if(!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)){ - availableChildRolesIterator.remove(); - } - } - return availableChildRoles; - } - - @SuppressWarnings("unchecked") - private Set<Role> getAllParentRolesAsList(Role role, Set<Role> allParentRoles) { - Set<Role> parentRoles = role.getParentRoles(); - allParentRoles.addAll(parentRoles); - Iterator<Role> parentRolesIterator = parentRoles.iterator(); - while (parentRolesIterator.hasNext()) { - getAllParentRolesAsList(parentRolesIterator.next(),allParentRoles); - } - return allParentRoles; - } - - public RoleFunction getRoleFunction(String code) { - return (RoleFunction)getDataAccessService().getDomainObject(RoleFunction.class, code, null); - } - - public void saveRoleFunction(RoleFunction domainRoleFunction) { - getDataAccessService().saveDomainObject(domainRoleFunction, null); - } - - public void deleteRoleFunction(RoleFunction domainRoleFunction) { - getDataAccessService().deleteDomainObject(domainRoleFunction, null); - } - - public Role getRole(Long id) { - return (Role)getDataAccessService().getDomainObject(Role.class, id, null); - } - - public void saveRole(Role domainRole) { - getDataAccessService().saveDomainObject(domainRole, null); - } - - public void deleteRole(Role domainRole) { - getDataAccessService().deleteDomainObject(domainRole, null); - } - - @SuppressWarnings("unchecked") - public List<Role> getAvailableRoles() { - return getDataAccessService().getList(Role.class, null); - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - - -} -*/ diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/UserProfileService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/UserProfileService.java deleted file mode 100644 index 0cf3986b..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/UserProfileService.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.List; - -import org.openecomp.portalsdk.core.domain.User; - - -public interface UserProfileService { - List<User> findAll(); - User getUser(String id); - User getUserByLoginId(String loginId); - void saveUser(User user); - public List<User> findAllUserWithOnOffline(String originOrgUserId); - List<User> findAllActive(); - List<User> searchPost(User user, String sortBy1, String sortBy2, String sortBy3, int pageNo, int newDataSize, - int intValue); -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/UserProfileServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/UserProfileServiceImpl.java deleted file mode 100644 index e0899917..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/UserProfileServiceImpl.java +++ /dev/null @@ -1,210 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.SortedSet; - -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; -import org.json.JSONArray; -import org.json.JSONObject; -import org.openecomp.portalsdk.core.FusionObject.Utilities; -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.domain.support.CollaborateList; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("userProfileService") -@Transactional -public class UserProfileServiceImpl implements UserProfileService{ - - - @Autowired - private DataAccessService dataAccessService; - - @SuppressWarnings("unchecked") - public List<User> findAll() { - return getDataAccessService().getList(User.class, null); - } - - public User getUser(String userId){ - return (User) getDataAccessService().getDomainObject(User.class, Long.parseLong(userId), null); - } - - @SuppressWarnings("unchecked") - public User getUserByLoginId(String loginId){ - User user=null; - List<Criterion> restrictionsList = new ArrayList<Criterion>(); - Criterion criterion1= Restrictions.eq("loginId",loginId); - restrictionsList.add(criterion1); - List<User> users = (List<User>) getDataAccessService().getList(User.class,null, restrictionsList, null); - if(users!=null && users.size()==1) - user = users.get(0); - return user; - } - - public void saveUser(User user){ - - getDataAccessService().saveDomainObject(user, null); - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - @SuppressWarnings("unchecked") - public List<User> findAllUserWithOnOffline(String originOrgUserId) { - HashSet<String> onlineUser = CollaborateList.getInstance().getAllUserName(); - List<User> users = getDataAccessService().getList(User.class, null); - for(User u:users){ - if(onlineUser.contains(u.getOrgUserId())) - u.setOnline(true); - if(u.getOrgUserId()!=null){ - if(originOrgUserId.compareTo(u.getOrgUserId()) > 0) { - u.setChatId(originOrgUserId + "-" + u.getOrgUserId()); - } else u.setChatId(u.getOrgUserId() + "-" + originOrgUserId ); - } - } - return users; - - } - - @SuppressWarnings("unchecked") - public List<User> findAllActive() { - List<User> users = getDataAccessService().getList(User.class, null); - Iterator<User> itr = users.iterator(); - while(itr.hasNext()){ - User u = (User) itr.next(); - if(!u.getActive()) - itr.remove();//if not active remove user from list - else { - SortedSet<Role> roles = u.getRoles(); - Iterator<Role> itrRoles = roles.iterator(); - while(itrRoles.hasNext()){ - Role role = (Role) itrRoles.next(); - if(!role.getActive()) - u.removeRole(role.getId());//if not active remove role from list - } - } - } - return users; - } - - - @Override - public List<User> searchPost(User user, String sortBy1, String sortBy2, String sortBy3, int pageNo, - int newDataSize, int intValue) { - - List<User> users=new ArrayList<User>(); - List<User> filterdUsers=new ArrayList<User>(); - BufferedReader in = null; - - try{ - String url = SystemProperties.getProperty(SystemProperties.AUTH_USER_SERVER); - URL obj = new URL(url); - - HttpURLConnection con = (HttpURLConnection) obj.openConnection(); - - // optional default is GET - con.setRequestMethod("GET"); - con.setConnectTimeout(3000); - con.setReadTimeout(8000); - - StringBuffer response = new StringBuffer(); - - - - in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); - String inputLine; - while ((inputLine = in.readLine()) != null) - response.append(inputLine); - - JSONObject jObject = new JSONObject(response.toString()); // json - JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object - for (int i = 0; i < jsonUsers.length(); i++) { - JSONObject eachObject = jsonUsers.getJSONObject(i); - User eachUser = new User(); - eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id")); - eachUser.setFirstName(eachObject.get("givenName").toString()); - eachUser.setLastName(eachObject.get("familyName").toString()); - eachUser.setEmail(eachObject.get("email").toString()); - - users.add(eachUser); - } - - for(int i = 0 ; i < users.size(); i ++){ - - if(Utilities.nvl(user.getFirstName()).length() > 0){ - if(!user.getFirstName().equalsIgnoreCase(users.get(i).getFirstName())){ - continue; - } - } - if(Utilities.nvl(user.getLastName()).length() > 0){ - if(!user.getLastName().equalsIgnoreCase(users.get(i).getLastName())){ - continue; - } - } - if(Utilities.nvl(user.getOrgUserId()).length() > 0){ - if(!user.getOrgUserId().equalsIgnoreCase(users.get(i).getOrgUserId())){ - continue; - } - } - if(Utilities.nvl(user.getEmail()).length() > 0){ - if(!user.getEmail().equalsIgnoreCase(users.get(i).getEmail())){ - continue; - } - } - - filterdUsers.add(users.get(i)); - - } - - }catch (Exception e){ - - }finally{ - try { - in.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - return filterdUsers; - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallService.java deleted file mode 100644 index a7a5ad07..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallService.java +++ /dev/null @@ -1,26 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - - -public interface WebServiceCallService { - public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception; - /*public String get(String restURL, String restPath);*/ -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallServiceImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallServiceImpl.java deleted file mode 100644 index 3e1a1a40..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/WebServiceCallServiceImpl.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service; - -import java.util.List; - -import org.openecomp.portalsdk.core.domain.App; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.CipherUtil; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service("webServiceCallService") -@Transactional -public class WebServiceCallServiceImpl implements WebServiceCallService{ - - @Autowired - private DataAccessService dataAccessService; - - @Autowired - AppService appService; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebServiceCallServiceImpl.class); - - /** - * Verify REST Credential - * @return true if the credential is accepted; else false. - */ - @Override - public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception { - App app = appService.getDefaultApp(); - if (app!=null) { - String encriptedPwdDB = app.getAppPassword(); - String appUserName = app.getUsername(); - String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB, secretKey==null?SystemProperties.getProperty(SystemProperties.Decryption_Key):secretKey); - if(decreptedPwd.equals(requestPassword) && appUserName.equals(requestAppName)) { - return true; - } - } - return false; - } - - /** - * Getting App information from FN_APP table - * @return App domain object, or null if not found. - */ - public App findApp(){ - List<?> list = null; - StringBuffer criteria = new StringBuffer(); - criteria.append(" where id = 1"); - list = getDataAccessService().getList(App.class, criteria.toString(), null, null); - return (list == null || list.size() == 0) ? null : (App) list.get(0); - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - /*/ - @Override - public String get(String restURL, String restPath) { - String appUserName = ""; - String appUebKey = ""; - String decreptedPwd = ""; - String appName = ""; - String inputLine = ""; - String serviceName = ""; - String loginId = ""; - StringBuffer jsonResponse = new StringBuffer(); - - StopWatch stopWatch = new StopWatch("WebServiceCallServiceImpl.get"); - stopWatch.start(); - try { - logger.info(EELFLoggerDelegate.metricsLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started."); - logger.debug(EELFLoggerDelegate.debugLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started."); - loginId = MDC.get("LoginId"); - appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); - App app = appService.getDefaultApp(); - if (app!=null) { - appName = app.getName(); - appUserName = app.getUsername(); - try{ - decreptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key)); - } catch(Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.getMessage()); - } - } else { - logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database."); - appName = SystemProperties.SERVICE_NAME; - } - - //Create the connection object - URL obj = new URL(restURL + restPath); - HttpURLConnection con = (HttpURLConnection) obj.openConnection(); - con.setRequestMethod("GET"); - con.setConnectTimeout(3000); - con.setReadTimeout(8000); - - //add request header - con.setRequestProperty("username", appUserName); - con.setRequestProperty("password", decreptedPwd); - con.setRequestProperty("uebkey", appUebKey); - con.setRequestProperty(SystemProperties.LOGIN_ID, loginId); - con.setRequestProperty(SystemProperties.USERAGENT_NAME, appName); - con.setRequestProperty(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID)); - - //set MDC context for outgoing audit logging - serviceName = String.format("%s:%s.%s", appName, SystemProperties.ECOMP_PORTAL_BE, restPath); - MDC.put(Configuration.MDC_SERVICE_NAME, serviceName); - MDC.put(Configuration.MDC_REMOTE_HOST, restURL); - MDC.put(SystemProperties.MDC_APPNAME, appName); - MDC.put(SystemProperties.MDC_REST_PATH, restPath); - MDC.put(SystemProperties.MDC_REST_METHOD, "GET"); - - int responseCode = con.getResponseCode(); - logger.info(EELFLoggerDelegate.errorLogger, "Received the response code '" + responseCode + "' while getting the '" + restPath + "' for user: " + loginId); - - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - - while ((inputLine = in.readLine()) != null) { - jsonResponse.append(inputLine); - } - in.close(); - - logSecurityMessage(RESULT_ENUM.SUCCESS); - logger.debug(EELFLoggerDelegate.debugLogger, restPath + " response: " + jsonResponse.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started."); - } catch(UrlAccessRestrictedException e) { - logger.error(EELFLoggerDelegate.errorLogger, "Authentication exception occurred in WebServiceCallServiceImpl.get (" + restPath + "). Details: " + e.getMessage()); - logSecurityMessage(RESULT_ENUM.FAILURE); - } catch(Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get (" + restPath + "). Details: " + e.getMessage()); - logSecurityMessage(RESULT_ENUM.FAILURE); - } finally { - if (stopWatch.isRunning()) stopWatch.stop(); - MDC.put(SystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms"); - logger.info(EELFLoggerDelegate.metricsLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is completed."); - - //clear the temporary MDC context values - MDC.remove(SystemProperties.MDC_TIMER); - MDC.remove(SystemProperties.MDC_REST_METHOD); - MDC.remove(SystemProperties.MDC_REST_PATH); - MDC.remove(SystemProperties.MDC_APPNAME); - MDC.remove(Configuration.MDC_REMOTE_HOST); - MDC.remove(Configuration.MDC_SERVICE_NAME); - } - - return jsonResponse.toString(); - } - - //Handles all the outgoing rest/ueb messages. - public void logSecurityMessage(RESULT_ENUM isSuccess) { - String additionalInfo = ""; - String protocol = "HTTP"; - String loginId = MDC.get("LoginId"); - additionalInfo = String.format("Rest API=%s, Rest Method=%s, App-Name=%s, Request-URL=%s", - MDC.get(SystemProperties.MDC_REST_PATH), MDC.get(SystemProperties.MDC_REST_METHOD), - MDC.get(SystemProperties.MDC_APPNAME), MDC.get(Configuration.MDC_REMOTE_HOST)); - - logger.info(EELFLoggerDelegate.auditLogger, AuditLogFormatter.getInstance().createMessage( - protocol, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE.name(), loginId, SystemProperties.SERVICE_NAME, - isSuccess.name(), additionalInfo)); - } - /**/ -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/support/FusionService.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/support/FusionService.java deleted file mode 100644 index 34649ee1..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/support/FusionService.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service.support; - - -import org.openecomp.portalsdk.core.FusionObject; - -public class FusionService implements FusionObject { - /** Logger for this class and subclasses */ -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocator.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocator.java deleted file mode 100644 index 5858c3fa..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocator.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service.support; - -import javax.naming.directory.DirContext; - - -public interface ServiceLocator { - DirContext getDirContext(String initialContextFactory, String providerUrl, String securityPrincipal); -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocatorImpl.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocatorImpl.java deleted file mode 100644 index e7437835..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/service/support/ServiceLocatorImpl.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.service.support; - -import java.util.Properties; - -import javax.naming.Context; -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.directory.InitialDirContext; -import javax.naming.ldap.InitialLdapContext; - -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.stereotype.Service; - -/** - * This class implements the J2EE service locator pattern. It provides lookup - * facilities for various services. Currenttly LDAP (pre-v3) is supported - */ -@Service("serviceLocator") -public class ServiceLocatorImpl implements ServiceLocator { - - private 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() {} - - // 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; - } - - /** Logger for this class and subclasses */ - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ServiceLocatorImpl.class); - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/CacheManager.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/CacheManager.java deleted file mode 100644 index e26ac884..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/CacheManager.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.util; - -import org.openecomp.portalsdk.core.objectcache.jcs.JCSCacheManager; -import org.springframework.context.annotation.Configuration; -@Configuration -public class CacheManager extends JCSCacheManager { - public CacheManager() { - - } - - /* The following can be customized for your application to cache the appropriate data upon application startup. The provided - example retrieves a list of sample lookup data and puts the list in the Cache Manager. To retrieve that data, simply call the - Cache Manager's getObject(String key) method which will return an Object instance. To put additional data in the Cache Manager - outside of application startup, call the Cache Manager's putObject(String key, Object objectToCache) method. */ - public void loadLookUpCache() { - /* - List<Role> result = (List<Role>)getDataAccessService().getList(Role.class,null); - - if (result != null) { - putObject("lookupRoles", result); - }*/ - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/CipherUtil.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/CipherUtil.java deleted file mode 100644 index 0eec9295..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/CipherUtil.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.util; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.codec.binary.Base64; - -public class CipherUtil { - - private final static String key = "AGLDdG4D04BKm2IxIWEr8o==!"; - - /** - * @param plainText - * @param secretKey - * @return encrypted version of plain text. - * @throws Exception - */ - public static String encrypt(String plainText, String secretKey) throws Exception{ - byte[] rawKey; - String encryptedString; - SecretKeySpec sKeySpec; - byte[] encryptText = plainText.getBytes("UTF-8"); - Cipher cipher; - rawKey = Base64.decodeBase64(secretKey); - sKeySpec = new SecretKeySpec(rawKey, "AES"); - cipher = Cipher.getInstance("AES"); - cipher.init(Cipher.ENCRYPT_MODE, sKeySpec); - encryptedString = Base64.encodeBase64String(cipher.doFinal(encryptText)); - - return encryptedString; - } - - /** - * - * @param plainText - * @return Encrypted Text - * @throws Exception - */ - public static String encrypt(String plainText) throws Exception - { - return CipherUtil.encrypt(plainText,key); - } - - /** - * @param encryptedText - * @param secretKey - * @return plain text version of encrypted text - * @throws Exception - */ - public static String decrypt(String encryptedText, String secretKey) throws Exception { - Cipher cipher; - String encryptedString; - byte[] encryptText = null; - byte[] rawKey; - SecretKeySpec sKeySpec; - - rawKey = Base64.decodeBase64(secretKey); - sKeySpec = new SecretKeySpec(rawKey, "AES"); - encryptText = Base64.decodeBase64(encryptedText.getBytes("UTF-8")); - cipher = Cipher.getInstance("AES"); - cipher.init(Cipher.DECRYPT_MODE, sKeySpec); - encryptedString = new String(cipher.doFinal(encryptText)); - - return encryptedString; - } - - /** - * @param encryptedText - * @return Decrypted Text - * @throws Exception - */ - public static String decrypt(String encryptedText) throws Exception - { - return CipherUtil.decrypt(encryptedText,key); - } - - - public static void main(String[] args) throws Exception { - - String password = "Welcome123"; - String encrypted; - String decrypted; - - if (args.length != 2) { - System.out.println("Default password testing... "); - System.out.println("Plain password: " + password); - encrypted = encrypt(password); - System.out.println("Encrypted password: " + encrypted); - decrypted = decrypt(encrypted); - System.out.println("Decrypted password: " + decrypted); - } else { - String whatToDo = args[0]; - if (whatToDo.equalsIgnoreCase("d")) { - encrypted = args[1]; - System.out.println("Encrypted Text: " + encrypted); - decrypted = decrypt(encrypted); - System.out.println("Decrypted Text: " + decrypted); - } else { - decrypted = args[1]; - System.out.println("Plain Text: " + decrypted); - encrypted = encrypt(decrypted); - System.out.println("Encrypted Text" + encrypted); - } - } - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/EncDecUtilTest.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/EncDecUtilTest.java deleted file mode 100644 index 46a24533..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/EncDecUtilTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.util; -import java.security.AlgorithmParameters; -import java.security.SecureRandom; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.codec.binary.Base64; - -public class EncDecUtilTest { - - private static final String password = "test"; - private static final String salt = "r n�HN~��|f��X�" ; - private static int pswdIterations = 65536 ; - private static int keySize = 256; - private byte[] ivBytes; - - public String encrypt(String plainText) throws Exception { - - //get salt - //salt = generateSalt(); - byte[] saltBytes = salt.getBytes("UTF-8"); - - // Derive the key - SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); - PBEKeySpec spec = new PBEKeySpec( - password.toCharArray(), - saltBytes, - pswdIterations, - keySize - ); - - SecretKey secretKey = factory.generateSecret(spec); - SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); - - //encrypt the message - Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); - cipher.init(Cipher.ENCRYPT_MODE, secret); - AlgorithmParameters params = cipher.getParameters(); - ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV(); - byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8")); - return new Base64().encodeAsString(encryptedTextBytes); - } - - @SuppressWarnings("static-access") - public String decrypt(String encryptedText) throws Exception { - - byte[] saltBytes = salt.getBytes("UTF-8"); - byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText); - - // Derive the key - SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); - PBEKeySpec spec = new PBEKeySpec( - password.toCharArray(), - saltBytes, - pswdIterations, - keySize - ); - - SecretKey secretKey = factory.generateSecret(spec); - SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); - - // Decrypt the message - Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); - cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes)); - - - byte[] decryptedTextBytes = null; - try { - decryptedTextBytes = cipher.doFinal(encryptedTextBytes); - } catch (IllegalBlockSizeException e) { - e.printStackTrace(); - } catch (BadPaddingException e) { - e.printStackTrace(); - } - - return new String(decryptedTextBytes); - } - - public String generateSalt() { - SecureRandom random = new SecureRandom(); - byte bytes[] = new byte[20]; - random.nextBytes(bytes); - String s = new String(bytes); - return s; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/EncTest.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/EncTest.java deleted file mode 100644 index 865731db..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/EncTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.util; - -public class EncTest { - - - public static void main(String[] args) { - String secretKey = "AGLDdG4D04BKm2IxIWEr8o=="; - String value1= "AppPassword!1"; - try { - String encryptedValue1= CipherUtil.encrypt(value1, secretKey); - System.out.println(encryptedValue1); - String decryptedValue1 = CipherUtil.decrypt(encryptedValue1, secretKey); - System.out.println(decryptedValue1); - } catch (Exception e) { - // Invalid key would throw an exception. - e.printStackTrace(); - } - - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/JSONUtil.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/JSONUtil.java deleted file mode 100644 index 6b849e81..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/JSONUtil.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.util; - -import java.util.HashMap; -import java.util.Map; - -import org.openecomp.portalsdk.core.domain.User; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JSONUtil { - public static String convertResponseToJSON(String response) throws JsonProcessingException{ - ObjectMapper mapper = new ObjectMapper(); - Map<String, String> responseMap = new HashMap<String, String>(); - responseMap.put("response", response); - response = mapper.writeValueAsString(responseMap); - return response; - } - - public static User mapToDomainUser(User domainUser, User editUser) { - domainUser.setOrgId(editUser.getOrgId()); - domainUser.setManagerId(editUser.getManagerId()); - domainUser.setFirstName(editUser.getFirstName()); - domainUser.setMiddleInitial(editUser.getMiddleInitial()); - domainUser.setLastName(editUser.getLastName()); - domainUser.setPhone(editUser.getPhone()); - domainUser.setEmail(editUser.getEmail()); - domainUser.setHrid(editUser.getHrid()); - domainUser.setOrgUserId(editUser.getOrgUserId()); - domainUser.setOrgCode(editUser.getOrgCode()); - domainUser.setOrgManagerUserId(editUser.getOrgManagerUserId()); - domainUser.setJobTitle(editUser.getJobTitle()); - domainUser.setLoginId(editUser.getLoginId()); - domainUser.setActive(editUser.getActive()); - return domainUser; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/SystemProperties.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/SystemProperties.java deleted file mode 100644 index 8bc6d7a1..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/SystemProperties.java +++ /dev/null @@ -1,279 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.util; - -import javax.servlet.ServletContext; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; - -/** - * SystemProperties contains a list of constants used throughout portions of the - * application. Populated by Spring from multiple configuration files. - * - * Should be used like this: - * - * <pre> - * - * @Autowired - * SystemProperties systemProperties; - * </pre> - */ -@Configuration -@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/system.properties", - "${container.classpath:}/WEB-INF/fusion/conf/fusion.properties", - "${container.classpath:}/WEB-INF/conf/sql.properties" }) -public class SystemProperties { - - private static Environment environment; - - 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; - } - - - public static boolean containsProperty(String key) { - return environment.containsProperty(key); - } - - public static String getProperty(String key) { - if (environment!=null) { - return environment.getRequiredProperty(key); - } else { - return ""; - } - } - - // method created to get around JSTL 1.0 limitation of not being able to - // access a static method of a bean - public String getApplicationName() { - return getProperty(APPLICATION_NAME); - } - - public String getAppDisplayName() { - return getProperty(APP_DISPLAY_NAME); - } - - private ServletContext servletContext; - - // keys used to reference values in the system properties file - public static final String DOMAIN_CLASS_LOCATION = "domain_class_location"; - public static final String DEFAULT_ERROR_MESSAGE = "default_error_message"; - - public static final String AUTHENTICATION_MECHANISM = "authentication_mechanism"; - - public static final String APPLICATION_NAME = "application_name"; - public static final String HIBERNATE_CONFIG_FILE_PATH = "hibernate_config_file_path"; - public static final String APPLICATION_USER_ID = "application_user_id"; - - public static final String POST_INITIAL_CONTEXT_FACTORY = "post_initial_context_factory"; - public static final String POST_PROVIDER_URL = "post_provider_url"; - public static final String POST_SECURITY_PRINCIPAL = "post_security_principal"; - public static final String POST_MAX_RESULT_SIZE = "post_max_result_size"; - public static final String POST_DEFAULT_ROLE_ID = "post_default_role_id"; - - public static final String FILES_PATH = "files_path"; - public static final String TEMP_PATH = "temp_path"; - - public static final String NUM_UPLOAD_FILES = "num_upload_files"; - - public static final String SYS_ADMIN_ROLE_ID = "sys_admin_role_id"; - - public static final String SYS_ADMIN_ROLE_FUNCTION_DELETE_FROM_UI = "sys_admin_role_function_delete_from_ui"; - public static final String USER_NAME = "user_name"; - public static final String FIRST_NAME = "first_name"; - public static final String LAST_NAME = "last_name"; - public static final String APP_DISPLAY_NAME = "app_display_name"; - // Application base URL is a proper prefix of the on-boarding URL - public static final String APP_BASE_URL = "app_base_url"; - - public static final String MENU_PROPERTIES_FILE_LOCATION = "menu_properties_file_location"; - public static final String MENU_QUERY_NAME = "menu_query_name"; - public static final String APPLICATION_MENU_SET_NAME = "application_menu_set_name"; - public static final String APPLICATION_MENU_ATTRIBUTE_NAME = "application_menu_attribute_name"; - public static final String APPLICATION_MENU_PROPERTIES_NAME = "application_menu_properties_name"; - public static final String BUSINESS_DIRECT_MENU_SET_NAME = "business_direct_menu_set_name"; - public static final String BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME = "business_direct_menu_attribute_name"; - public static final String BUSINESS_DIRECT_MENU_PROPERTIES_NAME = "business_direct_menu_properties_name"; - public static final String RAPTOR_CONFIG_FILE_PATH = "raptor_config_file_path"; - public static final String HOMEPAGE_DATA_CALLBACK_CLASS = "homepage_data_callback_class"; - public static final String ERROR_EMAIL_DISTRIBUTION = "error_email_distribution"; - public static final String ERROR_EMAIL_SOURCE_ADDRESS = "error_email_source_address"; - public static final String ERROR_EMAIL_SUBJECT_LINE = "error_email_subject_line"; - public static final String PROFILE_SEARCH_REPORT_ID = "profile_search_report_id"; - public static final String CALLABLE_PROFILE_SEARCH_REPORT_ID = "callable_profile_search_report_id"; - public static final String CLUSTERED = "clustered"; - - public static final String USER_ATTRIBUTE_NAME = "user_attribute_name"; - public static final String ROLES_ATTRIBUTE_NAME = "roles_attribute_name"; - public static final String ROLE_FUNCTIONS_ATTRIBUTE_NAME = "role_functions_attribute_name"; - public static final String CLIENT_DEVICE_ATTRIBUTE_NAME = "client_device_attribute_name"; - public static final String CLIENT_DEVICE_EMULATION = "client_device_emulation"; - public static final String CLIENT_DEVICE_TYPE_TO_EMULATE = "client_device_type_to_emulate"; - // File generation - Document - public static final String TEMPLATES_PATH = "templates_path"; - public static final String DOCUMENT_XML_ENCODING = "document_xml_encoding"; - - // Transaction - public static final String ROUTING_DATASOURCE_KEY = "routing_datasource_key"; - - // Document Library keys - public static final String DOCLIB_ADMIN_ROLE_ID = "doclib_admin_role_id"; - public static final String DOCLIB_USER_ROLE_ID = "doclib_user_role_id"; - - public static final String SYSTEM_PROPERTIES_FILENAME = "system.properties"; - public static final String FUSION_PROPERTIES_FILENAME = "fusion.properties"; - public static final String SUCCESS_TASKS_PROPERTIES_FILENAME = "success_tasks.properties"; - - // login error message keys - public static final String MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY = "login.error.hrid.empty"; - public static final String MESSAGE_KEY_LOGIN_ERROR_HEADER_EMPTY = "login.error.header.empty"; - public static final String MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE = "login.error.user.inactive"; - public static final String MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND = "login.error.hrid.not-found"; - public static final String MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED = "login.error.application.locked"; - public static final String MESSAGE_KEY_AUTOLOGIN_NONE = "webphone.autoimport.nouser"; - public static final String MESSAGE_KEY_AUTOLOGIN_MULTIPLE = "webphone.autoimport.multiple"; - - // Application Mobile capability - public static final String MOBILE_ENABLE = "mobile_enable"; - - public static final String DATABASE_TIME_ZONE = "db.time_zone"; - - public static final String AUTO_USER_IMPORT_ENABLE = "auto_user_import_enable"; - public static final String AUTO_USER_IMPORT_ROLE = "auto_user_import_role"; - - public static final String ITRACKER_EMAIL_SOURCE_ADDRESS = "itracker_email_source_address"; - public static final String ITRACKER_EMAIL_DISTRIBUTION = "itracker_email_distribution"; - public static final String ITRACKER_SYSTEM_USER = "itracker_system_user_id"; - - public static final String MAIL_SERVER_HOST = "mail_server_host"; - public static final String MAIL_SERVER_PORT = "mail_server_port"; - - // Routing Data Source keys - public static final String ROUTING_DATASOURCE_KEY_NON_XA = "NON-XA"; - public static final String ROUTING_DATASOURCE_KEY_XA = "XA"; - public static final String QUARTZ_JOB_ENABLED = "quartz_job_enable"; - public static final String WORKFLOW_EMAIL_SENDER = "workflow_email_sender"; - public static final String DROOLS_GUVNOR_HOME = "drools.guvnor.home"; - - // Hibernate Config - public static final String HB_DIALECT = "hb.dialect"; - public static final String HB_SHOW_SQL = "hb.show_sql"; - // DataSource - public static final String DB_DRIVER = "db.driver"; - public static final String DB_CONNECTIONURL = "db.connectionURL"; - public static final String DB_USERNAME = "db.userName"; - public static final String DB_PASSWOR = "db.password"; - public static final String DB_MIN_POOL_SIZE = "db.min_pool_size"; - public static final String DB_MAX_POOL_SIZE = "db.max_pool_size"; - public static final String IDLE_CONNECTION_TEST_PERIOD = "hb.idle_connection_test_period"; - - public static final String MYLOGINS_FEED_CRON = "mylogins_feed_cron"; - public static final String SESSIONTIMEOUT_FEED_CRON = "sessiontimeout_feed_cron"; - public static final String LOG_CRON = "log_cron"; - - public static final String DB_ENCRYPT_FLAG = "db.encrypt_flag"; - - // Decryption Key - public static final String Decryption_Key = "decryption_key"; - - // Logging/Audit Fields - public static final String MDC_APPNAME = "AppName"; - public static final String MDC_REST_PATH = "RestPath"; - public static final String MDC_REST_METHOD = "RestMethod"; - public static final String INSTANCE_UUID = "instance_uuid"; - public static final String MDC_CLASS_NAME = "ClassName"; - public static final String MDC_LOGIN_ID = "LoginId"; - public static final String MDC_TIMER = "Timer"; - public static final String SDK_NAME = "ECOMP_SDK"; - public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID"; - public static final String PARTNER_NAME = "PartnerName"; - public static final String FULL_URL = "Full-URL"; - public static final String AUDITLOG_BEGIN_TIMESTAMP = "AuditLogBeginTimestamp"; - public static final String AUDITLOG_END_TIMESTAMP = "AuditLogEndTimestamp"; - public static final String METRICSLOG_BEGIN_TIMESTAMP = "MetricsLogBeginTimestamp"; - public static final String METRICSLOG_END_TIMESTAMP = "MetricsLogEndTimestamp"; - public static final String CLIENT_IP_ADDRESS = "ClientIPAddress"; - public static final String STATUS_CODE = "StatusCode"; - public static final String RESPONSE_CODE = "ResponseCode"; - public static final String TARGET_ENTITY = "TargetEntity"; //Component or sub component name - public static final String TARGET_SERVICE_NAME = "TargetServiceName"; //API or operation name - - // Logging Compliance - public static final String DOUBLE_WHITESPACE_SEPARATOR = " "; - public static final String SINGLE_WHITESPACE_SEPARATOR = " "; - public static final String SINGLE_QUOTE = "'"; - public static final String NA = "N/A"; - public static final String UNKNOWN = "Unknown"; - public static final String SECURITY_LOG_TEMPLATE = "Protocol:{0} Security-Event-Type:{1} Login-ID:{2} {3}"; - public static final String ECOMP_PORTAL_BE = "ECOMP_PORTAL_BE"; - public static final String PROTOCOL = "PROTOCOL"; - public static final String SECURIRY_EVENT_TYPE = "SECURIRY_EVENT_TYPE"; - public static final String LOGIN_ID = "LOGIN_ID"; - public static final String ACCESSING_CLIENT = "ACCESSING_CLIENT"; - public static final String RESULT_STR = "RESULT"; - public static final String ECOMP_PORTAL_FE = "ECOMP_PORTAL_FE"; - public static final String ADDITIONAL_INFO = "ADDITIONAL_INFO"; - public static final String INTERFACE_NAME = "INTERFACE_NAME"; - public static final String USERAGENT_NAME = "user-agent"; - - // Protocols - public static final String HTTP = "HTTP"; - public static final String HTTPS = "HTTPS"; - public static final String SSO_VALUE = "sso"; - - public enum RESULT_ENUM { - SUCCESS, FAILURE - } - - public enum SecurityEventTypeEnum { - FE_LOGIN_ATTEMPT, FE_LOGOUT, SSO_LOGIN_ATTEMPT_PHASE_1, SSO_LOGIN_ATTEMPT_PHASE_2, SSO_LOGOUT, LDAP_PHONEBOOK_USER_SEARCH, INCOMING_REST_MESSAGE, OUTGOING_REST_MESSAGE, REST_AUTHORIZATION_CREDENTIALS_MODIFIED, ECOMP_PORTAL_USER_MODIFIED, ECOMP_PORTAL_USER_ADDED, ECOMP_PORTAL_USER_REMOVED, ECOMP_PORTAL_WIDGET, INCOMING_UEB_MESSAGE, ECOMP_PORTAL_HEALTHCHECK - } - - // Menu - public static final String CONTACT_US_LINK = "contact_us_link"; - - //Left Menu - public static final String LEFT_MENU_PARENT = "parentList"; - public static final String LEFT_MENU_CHILDREND = "childItemList"; - - // URL of the portal site that provides the shared-context REST service - public static final String ECOMP_SHARED_CONTEXT_REST_URL = "ecomp_shared_context_rest_url"; - - public static final String AUTH_USER_SERVER = "authenticate_user_server"; -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/UsageUtils.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/UsageUtils.java deleted file mode 100644 index a8cc7fd7..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/UsageUtils.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.util; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; - -import javax.servlet.http.HttpSession; - -import org.openecomp.portalsdk.core.command.UserRowBean; -import org.openecomp.portalsdk.core.domain.User; - -public class UsageUtils { - @SuppressWarnings("rawtypes") - public static ArrayList<UserRowBean> getActiveUsers(HashMap activeUsers) { - ArrayList<UserRowBean> rows = new ArrayList<UserRowBean>(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - - for(Iterator i = activeUsers.keySet().iterator(); i.hasNext(); ){ - String sessionId = (String)i.next(); - HttpSession session = (HttpSession)activeUsers.get(sessionId); - User userBean = (User)session.getAttribute("user"); - // - // Not all sessions will be valid logins - // Skip those ones - // - if(null == userBean) - continue; - - UserRowBean userRow = new UserRowBean(); - userRow.setFirstName(userBean.getFirstName()); - userRow.setLastName(userBean.getLastName()); - userRow.setEmail(userBean.getEmail()); - userRow.setId(userBean.getId()); - userRow.setSessionId(sessionId); - userRow.setLoginTime(sdf.format(new Date(session.getCreationTime()))); - userRow.setLastLoginTime(sdf.format(userBean.getLastLoginDate())); - - // - // Calculate the last time and time remaining for these sessions. - // - int sessionLength = session.getMaxInactiveInterval(); - long now = new java.util.Date().getTime(); - long lastAccessed = (now - session.getLastAccessedTime()) / 1000; - long lengthInactive = (now - session.getLastAccessedTime()); - long minutesRemaining = sessionLength - (lengthInactive / 1000); - - userRow.setLastAccess((lastAccessed / 60) + ":" + String.format("%02d", (lastAccessed % 60))); - userRow.setRemaining((minutesRemaining / 60) + ":" + String.format("%02d", (minutesRemaining % 60))); - - rows.add(userRow); - } - - return rows; - } - - @SuppressWarnings("rawtypes") - public static ArrayList<UserRowBean> getActiveUsersAfterDelete(HashMap activeUsers, final java.lang.Object data) { - return getActiveUsers(deleteSession(activeUsers,data)); - - } - - @SuppressWarnings("rawtypes") - private static HashMap deleteSession(HashMap activeUsers, Object data) { - String sessionId = ((UserRowBean)data).getSessionId(); - HttpSession session = (HttpSession)activeUsers.get(sessionId); - session.invalidate(); - activeUsers.remove(sessionId); - - return activeUsers; - } -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/YamlUtils.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/YamlUtils.java deleted file mode 100644 index 58bcb252..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/util/YamlUtils.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.util; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Map; - -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.representer.Representer; - -public class YamlUtils { - - static Yaml yaml; - - static { - - Representer representer = new Representer(); - yaml = new Yaml(representer); - - } - - public static void writeYamlFile(String filePath, String fileName, - Map<String, Object> model) throws IOException { - FileWriter writer = new FileWriter(filePath + File.separator + fileName); - yaml.dump(model, writer); - writer.close(); - } - - public static String returnYaml( - Map<String, Object> model) throws IOException { - - return yaml.dump(model); - - } - - @SuppressWarnings("unchecked") - public static Map<String, Object> readYamlFile( - String filePath, String fileName) throws FileNotFoundException, - IOException { - FileReader reader = new FileReader(filePath + File.separator + fileName); - - Map<String,Object> callFlowBs = (Map<String,Object>)yaml.load(reader); - reader.close(); - return callFlowBs; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/socket/PeerBroadcastSocket.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/socket/PeerBroadcastSocket.java deleted file mode 100644 index ddf08c8f..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/socket/PeerBroadcastSocket.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.web.socket; - -import java.io.IOException; -import java.util.Hashtable; -import java.util.Map; - -import javax.websocket.OnClose; -import javax.websocket.OnMessage; -import javax.websocket.OnOpen; -import javax.websocket.Session; -import javax.websocket.server.ServerEndpoint; - -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@ServerEndpoint("/contact") -public class PeerBroadcastSocket { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PeerBroadcastSocket.class); - - public static Map<String, Object> channelMap = new Hashtable<String, Object>(); - public Map<String, String> sessionMap = new Hashtable<String, String>(); - ObjectMapper mapper = new ObjectMapper(); - - @OnMessage - public void message(String message, Session session) { - try { - // JSONObject jsonObject = new JSONObject(message); - @SuppressWarnings("unchecked") - Map<String, Object> jsonObject = mapper.readValue(message, Map.class); - try { - Object from = jsonObject.get("from"); - if (from != null) { - channelMap.put(from.toString(), session); - sessionMap.put(session.getId(), from.toString()); - } - } catch (Exception je) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to read value" + je.getMessage()); - } - - try { - Object to = jsonObject.get("to"); - if (to == null) - return; - Object toSessionObj = channelMap.get(to); - if (toSessionObj != null) { - Session toSession = null; - toSession = (Session) toSessionObj; - toSession.getBasicRemote().sendText(message); - } - - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to send text" + ex.getMessage()); - } - - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed" + ex.getMessage()); - } - - } - - @OnOpen - public void open(Session session) { - logger.info(EELFLoggerDelegate.debugLogger, "Channel opened"); - } - - @OnClose - public void close(Session session) { - String channel = sessionMap.get(session.getId()); - if (channel != null) { - Object sessObj = channelMap.get(channel); - if (sessObj != null) { - try { - ((Session) sessObj).close(); - } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to close" + e.getMessage()); - } - } - channelMap.remove(channel); - } - logger.info(EELFLoggerDelegate.debugLogger, "Channel closed"); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/socket/WebRTCSocket.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/socket/WebRTCSocket.java deleted file mode 100644 index 810cba5c..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/socket/WebRTCSocket.java +++ /dev/null @@ -1,143 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.web.socket; - -import java.util.Hashtable; -import java.util.Map; - -import javax.websocket.OnClose; -import javax.websocket.OnMessage; -import javax.websocket.OnOpen; -import javax.websocket.Session; -import javax.websocket.server.ServerEndpoint; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@ServerEndpoint("/webrtc") -public class WebRTCSocket { - - - public static Map<String,Hashtable<String,Object[]>> channelMap = new Hashtable<String,Hashtable<String,Object[]>>(); - public Map<String,String> sessionMap = new Hashtable<String,String>(); - ObjectMapper mapper = new ObjectMapper(); - - - @OnMessage - public void message(String message, Session session) { - try { - //JSONObject jsonObject = new JSONObject(message); - @SuppressWarnings("unchecked") - Map<String,Object> jsonObject = mapper.readValue(message, Map.class); - try { - Object isOpen = jsonObject.get("open"); - if(isOpen != null && (Boolean)isOpen == true) { - String channel = (String) jsonObject.get("channel"); - Object value = channelMap.get(channel); - Hashtable<String,Object[]> sourceDestMap = null; - if(value == null) - sourceDestMap = new Hashtable<String,Object[]>(); - else - sourceDestMap = (Hashtable<String,Object[]>) value; - - sourceDestMap.put(session.getId(), new Object[]{session}); - channelMap.put(channel, sourceDestMap); - sessionMap.put(session.getId(), channel); - - - } - } - catch (Exception je) { - je.printStackTrace(); - } - - try{ - - Object dataObj = jsonObject.get("data"); - if(dataObj == null) - return; - Map<String,Object> dataMapObj = ( Map<String,Object>)dataObj; - //Object thisUserId = dataMapObj.get("userid"); - String channel = null; - try{ - Object channelObj = dataMapObj.get("sessionid"); - if(channelObj != null) - channel = (String) channelObj; - else - channel = (String) jsonObject.get("channel"); - } - catch(Exception json) { - json.printStackTrace(); - } - - /* - JSONObject dataMapObj = (JSONObject)dataObj; - Object thisUserId = dataMapObj.get("userid"); - String channel = (String) dataMapObj.get("sessionid"); - Hashtable<String,Object> sourceDestMap = sessionMap.get(channel); - - if(thisUserId != null && sourceDestMap.get((String)thisUserId) == null) { - sourceDestMap.put((String)thisUserId, new Object[] {message, session}); - } - - for(String userId : sourceDestMap.keySet()){ - if(!userId.equals(thisUserId)) { - Session otherSession = (Session) ((Object[])sourceDestMap.get(userId))[1]; - otherSession.getBasicRemote().sendText(message); - } - } - */ - - Hashtable<String,Object[]> sourceDestMap = channelMap.get(channel); - if(sourceDestMap != null) - for(String id : sourceDestMap.keySet()){ - if(!id.equals(session.getId())) { - Session otherSession = (Session) ((Object[])sourceDestMap.get(id))[0]; - if(otherSession.isOpen()) - otherSession.getBasicRemote().sendText(mapper.writeValueAsString(dataObj)); - } - - } - } - catch (Exception je) { - je.printStackTrace(); - } - - } - catch (Exception je) { - je.printStackTrace(); - } - //System.out.println("Message received:" + message); - } - - @OnOpen - public void open(Session session) { - // System.out.println("Channel opened"); - } - - @OnClose - public void close(Session session) { - String channel = sessionMap.get(session.getId()); - if (channel != null) { - channelMap.remove(channel); - } - // System.out.println("Channel closed"); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/AppUtils.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/AppUtils.java deleted file mode 100644 index 170d87cb..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/AppUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.web.support; - -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.sql.DataSource; - -import org.hibernate.Session; -import org.openecomp.portalsdk.core.exception.SessionExpiredException; -import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.springframework.beans.factory.annotation.Autowired; - - -public class AppUtils { - - private static DataAccessService dataAccessService; - - private static AbstractCacheManager cacheManager; - - private static boolean applicationLocked; - - private static Hashtable feedback = new Hashtable(); - - private static DataSource datasource; - - public static DataSource getDatasource() { - return datasource; - } - - @Autowired - public void setDatasource(DataSource datasource) { - AppUtils.datasource = datasource; - } - - public AppUtils() { - } - - public static HttpSession getSession(HttpServletRequest request) { - HttpSession session = null; - if (request != null) { - session = request.getSession(false); - if (session == null) { - throw new SessionExpiredException(); - } - } else { - throw new SessionExpiredException(); - } - return session; - } - - public static List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy) { - return getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null); - } // getLookupList - - public static List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, Session session) { - String cacheKey = dbTable + "|" + dbValueCol + "|" + dbLabelCol + "|" + dbFilter + "|" + dbOrderBy; - List list = getLookupListFromCache(cacheKey); - if (list == null) { - list = getDataAccessService().getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null); - if (list != null) { - addLookupListToCache(cacheKey, list); - } - } // if - return list; - } // getLookupList - - private static List getLookupListFromCache(String key) { - return (List)getObjectFromCache(key); - } // getLookupListFromCache - - public static Object getObjectFromCache(String key) { - if (isCacheManagerAvailable()) { - return getCacheManager().getObject(key); - } else { - return null; - } - } // getObjectFromCache - - private static void addLookupListToCache(String key, List list) { - addObjectToCache(key, list); - } // addLookupListToCache - - public static void addObjectToCache(String key, Object o) { - if (isCacheManagerAvailable()) { - getCacheManager().putObject(key, o); - } - } // addObjectToCache - - @Autowired - public void setCacheManager(AbstractCacheManager cacheManager) { - this.cacheManager = cacheManager; - } - - public static AbstractCacheManager getCacheManager() { - return cacheManager; - } - - public static boolean isCacheManagerAvailable() { - return (getCacheManager() != null); - } - - public void setFeedback(Hashtable feedback) { - this.feedback = feedback; - } - - public static boolean isApplicationLocked() { - return applicationLocked; - } - - public static DataAccessService getDataAccessService() { - return dataAccessService; - } - - @Autowired - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - public static void setApplicationLocked(boolean locked) { - applicationLocked = locked; - } - - public static String getLookupValueByLabel(String label, String dbTable, String dbValueCol, String dbLabelCol) { - if (label == null || label.equals("")) { - return ""; - } - - List<org.openecomp.portalsdk.core.domain.Lookup> lstResult = getLookupListNoCache(dbTable, dbValueCol, dbLabelCol, dbLabelCol + "='" + label.replaceAll("'", "''") + "'", ""); - if (lstResult == null) { - return ""; - } - if (lstResult.size() > 0) { - return ((org.openecomp.portalsdk.core.domain.Lookup)lstResult.toArray()[0]).getValue(); - } else { - return ""; - } - } - - public static String getLookupValueByLabel(String label, List lookupList) { - Iterator i = null; - - if (label == null || label.equalsIgnoreCase("")) { - return ""; - } - - if (lookupList == null || lookupList.size() == 0) { - return ""; - } - - i = lookupList.iterator(); - while (i.hasNext()) { - org.openecomp.portalsdk.core.domain.Lookup lookup = (org.openecomp.portalsdk.core.domain.Lookup)i.next(); - - if (lookup.getLabel().equals(label)) { - return lookup.getValue(); - } - } - - return ""; -} - public static List getLookupListNoCache(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy) { - return getLookupListNoCache(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null); - } // getLookupListNoCache - - - public static List getLookupListNoCache(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, Session session) { - return getDataAccessService().getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null); - } // getLookupListNoCache - - - -} // AppUtils diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/ControllerProperties.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/ControllerProperties.java deleted file mode 100644 index 1d09eba0..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/ControllerProperties.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.web.support; - -public interface ControllerProperties { - - static final String TASK_GET = "get"; - static final String TASK_DELETE = "delete"; - static final String TASK_SAVE = "save"; - static final String TASK_PROCESS = "process"; - static final String TASK_TOGGLE_ACTIVE = "toggleActive"; - static final String TASK_DOWNLOAD = "download"; - static final String TASK_POPUP = "popup"; - static final String TASK_LOOKUP = "lookup"; - static final String TASK_ADD_ROW = "addRow"; - static final String TASK_APPROVE = "approve"; - static final String TASK_REJECT = "reject"; - static final String TASK_RESET = "reset"; - static final String TASK_ASSIGN = "assign"; - static final String TASK_CUT = "cut"; - static final String TASK_COPY = "copy"; - static final String TASK_PASTE = "paste"; - static final String TASK_SELECT = "select"; -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/FeedbackMessage.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/FeedbackMessage.java deleted file mode 100644 index d8993b03..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/FeedbackMessage.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.web.support; - -public class FeedbackMessage { - - private String message; - private int messageType; - private boolean keyed; - - public static final int MESSAGE_TYPE_ERROR = 10; - public static final int MESSAGE_TYPE_WARNING = 20; - public static final int MESSAGE_TYPE_INFO = 30; - public static final int MESSAGE_TYPE_SUCCESS = 40; - - public static final String DEFAULT_MESSAGE_SUCCESS = "Update successful."; - public static final String DEFAULT_MESSAGE_ERROR = "An error occurred while processing the request: "; - - public static final String DEFAULT_MESSAGE_SYSTEM_ADMINISTRATOR = "If the problem persists, please contact your Administrator."; - - public FeedbackMessage() { - } - - public FeedbackMessage(String message) { - this(message, MESSAGE_TYPE_ERROR); - } - - public FeedbackMessage(String message, int messageType) { - this(message, messageType, false); - } - - public FeedbackMessage(String message, int messageType, boolean keyed) { - this.message = message; - this.messageType = messageType; - this.keyed = keyed; - } - - public String getMessage() { - return message; - } - - public int getMessageType() { - return messageType; - } - - public boolean isKeyed() { - return keyed; - } - - public void setMessage(String message) { - this.message = message; - } - - public void setMessageType(int messageType) { - this.messageType = messageType; - } - - public void setKeyed(boolean keyed) { - this.keyed = keyed; - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/JsonMessage.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/JsonMessage.java deleted file mode 100644 index 5566bf90..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/JsonMessage.java +++ /dev/null @@ -1,118 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.web.support; - -import java.io.PrintWriter; -import java.io.StringWriter; - -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JsonMessage { - - private String data; - private String data2; - private String data3; - public JsonMessage(String data) { - super(); - this.data = data; - } - public JsonMessage(String data,String data2) { - super(); - this.data = data; - this.data2 = data2; - } - - public JsonMessage(String data,String data2,String data3) { - super(); - this.data = data; - this.data2 = data2; - this.data3 = data3; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - public String getData2() { - return data2; - } - public void setData2(String data2) { - this.data2 = data2; - } - public String getData3() { - return data3; - } - public void setData3(String data3) { - this.data3 = data3; - } - - - /** - * Builds JSON object with status + message response body. - * - * @param success - * True to indicate success, false to signal failure. - * @param msg - * Message to include in the response object; ignored if null. - * @return - * - * <pre> - * { "status" : "ok" (or "error"), "message": "some explanation" } - * </pre> - */ - public static String buildJsonResponse(boolean success, String msg) { - PortalAPIResponse response = new PortalAPIResponse(success, msg); - String json = null; - try { - json = new ObjectMapper().writeValueAsString(response); - } catch (JsonProcessingException ex) { - // Truly should never, ever happen - json = "{ \"status\": \"error\",\"message\":\"" + ex.toString() + "\" }"; - } - return json; - } - - /** - * Builds JSON object with status of error and message containing stack - * trace for the specified throwable. - * - * @param t - * Throwable with stack trace to use as message - * @return - * - * <pre> - * { "status" : "error", "message": "some-big-stacktrace" } - * </pre> - */ - public static String buildJsonResponse(Throwable t) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - t.printStackTrace(pw); - return buildJsonResponse(false, sw.toString()); - } - - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/MessagesList.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/MessagesList.java deleted file mode 100644 index 9ab956d0..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/MessagesList.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.web.support; - -import java.util.ArrayList; -import java.util.List; - -public class MessagesList { - - private boolean successMessageDisplayed = true; - private boolean includeCauseInCustomExceptions = false; - - private List successMessages; - private List exceptionMessages; - - public MessagesList() { - setExceptionMessages(new ArrayList()); - setSuccessMessages(new ArrayList()); - } - - public MessagesList(boolean displaySuccess) { - this(); - setSuccessMessageDisplayed(displaySuccess); - } - - public List getExceptionMessages() { - return exceptionMessages; - } - - public List getSuccessMessages() { - return successMessages; - } - - public boolean isSuccessMessageDisplayed() { - return successMessageDisplayed; - } - - public boolean isIncludeCauseInCustomExceptions() { - return includeCauseInCustomExceptions; - } - - - public void setExceptionMessages(List exceptionMessages) { - this.exceptionMessages = exceptionMessages; - } - - public void setSuccessMessages(List successMessages) { - this.successMessages = successMessages; - } - - public void setSuccessMessageDisplayed(boolean successMessageDisplayed) { - this.successMessageDisplayed = successMessageDisplayed; - } - - public void setIncludeCauseInCustomExceptions(boolean includeCauseInCustomExceptions) { - this.includeCauseInCustomExceptions = includeCauseInCustomExceptions; - } - - - public void addSuccessMessage(FeedbackMessage message) { - getSuccessMessages().add(message); - } - - public void addExceptionMessage(FeedbackMessage message) { - getExceptionMessages().add(message); - } - - public boolean hasExceptionMessages() { - return!getExceptionMessages().isEmpty(); - } - - public boolean hasSuccessMessages() { - return!getSuccessMessages().isEmpty(); - } - -} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/UserUtils.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/UserUtils.java deleted file mode 100644 index 7f974574..00000000 --- a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/web/support/UserUtils.java +++ /dev/null @@ -1,373 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalsdk.core.web.support; - -import java.io.PrintWriter; -import java.io.Serializable; -import java.io.StringWriter; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.UUID; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.openecomp.portalsdk.core.FusionObject; -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.RoleFunction; -import org.openecomp.portalsdk.core.domain.UrlsAccessible; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.exception.SessionExpiredException; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.menu.MenuBuilder; -import org.openecomp.portalsdk.core.restful.domain.EcompRole; -import org.openecomp.portalsdk.core.restful.domain.EcompUser; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.openecomp.portalsdk.core.util.CipherUtil; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; - -@SuppressWarnings("rawtypes") -public class UserUtils implements Serializable, FusionObject { - - /** - * - */ - private static final long serialVersionUID = 1L; - private static final String USER_ID = "UserId"; - - static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserUtils.class); - - public static final String KEY_USER_ROLES_CACHE = "userRoles"; - - public static final String WJ_HEADER_USER_NAME = "iv-user"; - public static final String WJ_HEADER_USER_GROUP = "iv-groups"; - - private static DataAccessService dataAccessService; - - public static void setUserSession(HttpServletRequest request, User user, Set applicationMenuData, Set businessDirectMenuData, String loginMethod) { - HttpSession session = request.getSession(true); - - UserUtils.clearUserSession(request); // let's clear the current user session to avoid any conflicts during the set - - session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); - - getRoleFunctions(request); - - // truncate the role (and therefore the role function) data to save memory in the session - user.setRoles(null); - session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName()); - session.setAttribute(SystemProperties.FIRST_NAME, user.getFirstName()); - session.setAttribute(SystemProperties.LAST_NAME, user.getLastName()); - String displayName = ""; - if (SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) != null) - displayName = SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME); - session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), displayName); - - session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME), MenuBuilder.filterMenu(applicationMenuData, request)); - session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME), MenuBuilder.filterMenu(businessDirectMenuData, request)); - } - - public static void clearUserSession(HttpServletRequest request) { - HttpSession session = AppUtils.getSession(request); - - if (session == null) { - throw new SessionExpiredException(); - } - - // removes all stored attributes from the current user's session - session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); - session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); - session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME)); - session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)); - session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); - } - - @SuppressWarnings("unchecked") - public static Set getRoleFunctions(HttpServletRequest request) { - HashSet roleFunctions = null; - - HttpSession session = request.getSession(); - roleFunctions = (HashSet)session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); - - if (roleFunctions == null) { - HashMap roles = getRoles(request); - roleFunctions = new HashSet(); - - Iterator i = roles.keySet().iterator(); - - while (i.hasNext()) { - Long roleKey = (Long)i.next(); - Role role = (Role)roles.get(roleKey); - - Iterator j = role.getRoleFunctions().iterator(); - - while (j.hasNext()) { - RoleFunction function = (RoleFunction) j.next(); - roleFunctions.add(function.getCode()); - } - } - - session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME), roleFunctions); - } - - return roleFunctions; - } - - public static HashMap getRoles(HttpServletRequest request) { - HashMap roles = null; - - //HttpSession session = request.getSession(); - HttpSession session = AppUtils.getSession(request); - roles = (HashMap)session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)); - - // if roles are not already cached, let's grab them from the user session - if (roles == null) { - User user = getUserSession(request); - - // get all user roles (including the tree of child roles) - roles = getAllUserRoles(user); - - session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), getAllUserRoles(user)); - } - - return roles; - } - - public static User getUserSession(HttpServletRequest request) { - HttpSession session = AppUtils.getSession(request); - - if (session == null) { - throw new SessionExpiredException(); - } - - return (User)session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); - } - - @SuppressWarnings("unchecked") - public static HashMap getAllUserRoles(User user) { - HashMap roles = new HashMap(); - Iterator i = user.getRoles().iterator(); - - while (i.hasNext()) { - Role role = (Role)i.next(); - - if (role.getActive()) { - roles.put(role.getId(), role); - - // let's take a recursive trip down the tree to add all child roles - addChildRoles(role, roles); - } - } - - return roles; - } - - @SuppressWarnings("unchecked") - private static void addChildRoles(Role role, HashMap roles) { - Set childRoles = role.getChildRoles(); - - if (childRoles != null && childRoles.size() > 0) { - Iterator j = childRoles.iterator(); - while (j.hasNext()) { - Role childRole = (Role)j.next(); - - if (childRole.getActive()) { - roles.put(childRole.getId(), childRole); - - addChildRoles(childRole, roles); - } - } - } - - } - - @SuppressWarnings("unchecked") - public static boolean isUrlAccessible(HttpServletRequest request, String currentUrl) { - boolean isAccessible = false; - - Map params = new HashMap(); - params.put("current_url", currentUrl); - - List list = getDataAccessService().executeNamedQuery("restrictedUrls", params, null); - - // loop through the list of restricted URL's - if (list != null && list.size() > 0) { - for (int i=0; i < list.size(); i++) { - - UrlsAccessible urlFunctions = (UrlsAccessible) list.get(i); - String functionCd = (String)urlFunctions.getFunctionCd(); - - if (UserUtils.isAccessible(request, functionCd)) { - isAccessible = true; - } - } - return isAccessible; - } - - return true; - } - - public static boolean hasRole(HttpServletRequest request, String roleKey) { - return getRoles(request).keySet().contains(new Long(roleKey)); - } - - - public static boolean hasRole(User user, String roleKey) { - return getAllUserRoles(user).keySet().contains(new Long(roleKey)); - } - - public static boolean isAccessible(HttpServletRequest request, String functionKey) { - return getRoleFunctions(request).contains(functionKey); - } - - public static DataAccessService getDataAccessService() { - return dataAccessService; - } - - @Autowired - public void setDataAccessService(DataAccessService dataAccessService) { - UserUtils.dataAccessService = dataAccessService; - } - - public static int getUserId(HttpServletRequest request) { - return getUserIdAsLong(request).intValue(); - } - - public static Long getUserIdAsLong(HttpServletRequest request) { - Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID)); - - if (request != null) { - if (getUserSession(request) != null) { - userId = getUserSession(request).getId(); - } - } - - return userId; - } - - - private static final Object stackTraceLock = new Object(); - public static String getStackTrace(Throwable t) { - synchronized(stackTraceLock) { - StringWriter sw = new StringWriter (); - PrintWriter pw = new PrintWriter (sw); - t.printStackTrace (pw); - return sw.toString (); - } - } - - public static String getFullURL(HttpServletRequest request) { - if (request!=null) { - StringBuffer requestURL = request.getRequestURL(); - String queryString = request.getQueryString(); - - if (queryString == null) { - return requestURL.toString(); - } else { - return requestURL.append('?').append(queryString).toString(); - } - } - - return ""; - } - - public static String getRequestId(HttpServletRequest request) { - Enumeration<String> headerNames = request.getHeaderNames(); - - String requestId = ""; - try { - while (headerNames.hasMoreElements()) { - String headerName = (String) headerNames.nextElement(); - logger.info(EELFLoggerDelegate.debugLogger, "One header is " + headerName + " : " + request.getHeader(headerName)); - if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) { - requestId = request.getHeader(headerName); - break; - } - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.debugLogger, "HEADER!!!! Exception : " + UserUtils.getStackTrace(e)); - } - - return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId); - } - - - public static EcompUser convertToEcompUser (User user){ - EcompUser userJson = new EcompUser(); - - - userJson.setEmail(user.getEmail()); - userJson.setFirstName(user.getFirstName()); - userJson.setHrid(user.getHrid()); - userJson.setJobTitle(user.getJobTitle()); - userJson.setLastName(user.getLastName()); - userJson.setLoginId(user.getLoginId()); - userJson.setOrgManagerUserId(user.getOrgManagerUserId()); - userJson.setMiddleInitial(user.getMiddleInitial()); - userJson.setOrgCode(user.getOrgCode()); - userJson.setOrgId(user.getOrgId()); - userJson.setPhone(user.getPhone()); - userJson.setOrgUserId(user.getOrgUserId()); - - - Set<EcompRole> ecompRoles = new TreeSet<EcompRole>(); - - for(Role role : user.getRoles()){ - ecompRoles.add(convertToEcompRole(role)); - } - - userJson.setRoles(ecompRoles); - - return userJson; - } - - public static EcompRole convertToEcompRole(Role role){ - - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(role.getId()); - ecompRole.setName(role.getName()); - - return ecompRole; - } - - public static String getUserIdFromCookie(HttpServletRequest request) throws Exception { - String userId = ""; - Cookie[] cookies = request.getCookies(); - Cookie userIdcookie = null; - if (cookies != null) - for (Cookie cookie : cookies) - if (cookie.getName().equals(USER_ID)) - userIdcookie = cookie; - if(userIdcookie!=null){ - userId = CipherUtil.decrypt(userIdcookie.getValue(), - SystemProperties.getProperty(SystemProperties.Decryption_Key)); - } - return userId; - - } -} |