diff options
author | Pamela Dragosh <pdragosh@research.att.com> | 2017-02-14 19:41:00 -0500 |
---|---|---|
committer | Pamela Dragosh <pdragosh@research.att.com> | 2017-02-14 19:41:32 -0500 |
commit | 91d04c64771832a0b8815ffbe1f0f9920320d94d (patch) | |
tree | fb02d5e1c84a3d91def9a7ee95bc87f9c046cc96 /ecomp-sdk-app/src/main/java/org/openecomp | |
parent | b9d4caa40ef8e3566ac475968bce17b9b64b6939 (diff) |
Initial OpenECOMP policy/engine commit
Change-Id: I7dbff37733b661643dd4d1caefa3d7dccc361b6e
Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
Diffstat (limited to 'ecomp-sdk-app/src/main/java/org/openecomp')
125 files changed, 27124 insertions, 0 deletions
diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AddressGroupJson.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AddressGroupJson.java new file mode 100644 index 000000000..e60e4061e --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AddressGroupJson.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +import java.util.ArrayList; +import java.util.List; + +public class AddressGroupJson { + + protected String name; + protected String description; + protected List<AddressMembers> members; + + // name + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } + + public boolean equals(Object obj) + { + AddressGroupJson servGroupobj=(AddressGroupJson) obj; + if(this.getName().equals(servGroupobj.getName())) + { + return true; + } + return false; + } + + public int hashCode() { + return Integer.valueOf(name.charAt(0)+(name.charAt(1))); + } + + // description + public String getDescription() { + return description; + } + + public void setDescription(String value) { + this.description = value; + } + + public List<AddressMembers> getMembers() + { + if(members==null) + { + members= new ArrayList<AddressMembers>(); + } + return this.members; + } + + public void setMembers(List<AddressMembers> members) + { + this.members = members; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AddressJson.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AddressJson.java new file mode 100644 index 000000000..372eddf1b --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AddressJson.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +public class AddressJson { + + protected String type; + protected String value; + // type + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AddressMembers.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AddressMembers.java new file mode 100644 index 000000000..3fd22eec6 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AddressMembers.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + + +public class AddressMembers { + + protected String type; + protected String value; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AutoPushTabAdapter.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AutoPushTabAdapter.java new file mode 100644 index 000000000..85f767f26 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/AutoPushTabAdapter.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +import java.util.ArrayList; + +public class AutoPushTabAdapter { + + private ArrayList<Object> pdpDatas; + private ArrayList<Object> policyDatas; + public ArrayList<Object> getPdpDatas() { + return pdpDatas; + } + public void setPdpDatas(ArrayList<Object> pdpDatas) { + this.pdpDatas = pdpDatas; + } + public ArrayList<Object> getPolicyDatas() { + return policyDatas; + } + public void setPolicyDatas(ArrayList<Object> policyDatas) { + this.policyDatas = policyDatas; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopFaultBody.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopFaultBody.java new file mode 100644 index 000000000..cb1ce55a6 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopFaultBody.java @@ -0,0 +1,280 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + + +public class ClosedLoopFaultBody { + + private boolean trinity; + private boolean vUSP; + private boolean mcr; + private boolean gama; + private boolean vDNS; + + private String vnfType; + private String vServices; + private String ECOMPname; + + private String closedLoopPolicyStatus; + private ClosedLoopSignatures triggerSignatures; + private String actions; + private int timeInterval; + private int timeOutvPRO; + private int timeOutRuby; + private int retrys; + private int agingWindow; + private String geoLink; + private String emailAddress; + private ClosedLoopSignatures verificationSignatures; + private ClosedLoopPolicyConditions conditions; + private ClosedLoopFaultTriggerUISignatures triggerSignaturesUsedForUI; + private ClosedLoopFaultTriggerUISignatures verificationSignaturesUsedForUI; + private int triggerTimeWindowUsedForUI; + private int verfificationTimeWindowUsedForUI; + private String pepName; + private String pepAction; + private String templateVersion; + private int trapMaxAgeUsedForUI; + + + public Integer getTrapMaxAgeUsedForUI() { + return trapMaxAgeUsedForUI; + } + + public void setTrapMaxAgeUsedForUI(int trapMaxAgeUsedForUI) { + this.trapMaxAgeUsedForUI = trapMaxAgeUsedForUI; + } + + public String getTemplateVersion() { + return templateVersion; + } + + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + + public Integer getTimeOutvPRO() { + return timeOutvPRO; + } + + public void setTimeOutvPRO(int timeOutvPRO) { + this.timeOutvPRO = timeOutvPRO; + } + + + public Integer getTriggerTimeWindowUsedForUI() { + return triggerTimeWindowUsedForUI; + } + + public String getPepName() { + return pepName; + } + + public void setPepName(String pepName) { + this.pepName = pepName; + } + + public String getPepAction() { + return pepAction; + } + + public void setPepAction(String pepAction) { + this.pepAction = pepAction; + } + + public void setTriggerTimeWindowUsedForUI(int triggerTimeWindowUsedForUI) { + this.triggerTimeWindowUsedForUI = triggerTimeWindowUsedForUI; + } + + public Integer getVerfificationTimeWindowUsedForUI() { + return verfificationTimeWindowUsedForUI; + } + + public void setVerfificationTimeWindowUsedForUI( + int verfificationTimeWindowUsedForUI) { + this.verfificationTimeWindowUsedForUI = verfificationTimeWindowUsedForUI; + } + + public String getECOMPname(){ + return ECOMPname; + } + + public void setECOMPname(String ECOMPname){ + this.ECOMPname = ECOMPname; + } + + public String getvServices() { + return vServices; + } + public void setvServices(String vServices) { + this.vServices = vServices; + } + + public ClosedLoopFaultTriggerUISignatures getVerificationSignaturesUsedForUI() { + return verificationSignaturesUsedForUI; + } + public void setVerificationSignaturesUsedForUI( + ClosedLoopFaultTriggerUISignatures verificationSignaturesUsedForUI) { + this.verificationSignaturesUsedForUI = verificationSignaturesUsedForUI; + } + public ClosedLoopFaultTriggerUISignatures getTriggerSignaturesUsedForUI() { + return triggerSignaturesUsedForUI; + } + public void setTriggerSignaturesUsedForUI( + ClosedLoopFaultTriggerUISignatures triggerSignaturesUsedForUI) { + this.triggerSignaturesUsedForUI = triggerSignaturesUsedForUI; + } + public ClosedLoopPolicyConditions getConditions() { + return conditions; + } + public void setConditions(ClosedLoopPolicyConditions conditions) { + this.conditions = conditions; + } + + public String getVnfType() { + return vnfType; + } + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + + public Integer getAgingWindow() { + return agingWindow; + } + public void setAgingWindow(int agingWindow) { + this.agingWindow = agingWindow; + } + + public String getClosedLoopPolicyStatus() { + return closedLoopPolicyStatus; + } + public void setClosedLoopPolicyStatus( + String closedLoopPolicyStatus) { + this.closedLoopPolicyStatus = closedLoopPolicyStatus; + } + public ClosedLoopSignatures getTriggerSignatures() { + return triggerSignatures; + } + public void setTriggerSignatures(ClosedLoopSignatures triggerSignatures) { + this.triggerSignatures = triggerSignatures; + } + public String getActions() { + return actions; + } + public void setActions(String actions) { + this.actions = actions; + } + public Integer getTimeInterval() { + return timeInterval; + } + public void setTimeInterval(int timeInterval) { + this.timeInterval = timeInterval; + } + public Integer getTimeOutRuby() { + return timeOutRuby; + } + public void setTimeOutRuby(int timeOutRuby) { + this.timeOutRuby = timeOutRuby; + } + public Integer getRetrys() { + return retrys; + } + public void setRetrys(int retrys) { + this.retrys = retrys; + } + public String getGeoLink() { + return geoLink; + } + public void setGeoLink(String geoLink) { + this.geoLink = geoLink; + } + public String getEmailAddress() { + return emailAddress; + } + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + public ClosedLoopSignatures getVerificationSignatures() { + return verificationSignatures; + } + public void setVerificationSignatures( + ClosedLoopSignatures verificationSignatures) { + this.verificationSignatures = verificationSignatures; + } + + /*public ArrayList<String> getD2Services() { + return d2Services; + } + + public void setD2Services(ArrayList<String> d2Services) { + this.d2Services = d2Services; + } + + public ArrayList<String> getSiteNames() { + return siteNames; + } + + public void setSiteNames(ArrayList<String> siteNames) { + this.siteNames = siteNames; + }*/ + + public boolean isvDNS() { + return vDNS; + } + + public void setvDNS(boolean vDNS) { + this.vDNS = vDNS; + } + + public boolean isTrinity() { + return trinity; + } + + public void setTrinity(boolean trinity) { + this.trinity = trinity; + } + + public boolean isvUSP() { + return vUSP; + } + + public void setvUSP(boolean vUSP) { + this.vUSP = vUSP; + } + + public boolean isMcr() { + return mcr; + } + + public void setMcr(boolean mcr) { + this.mcr = mcr; + } + + public boolean isGama() { + return gama; + } + + public void setGama(boolean gama) { + this.gama = gama; + } +} + diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopFaultTriggerUISignatures.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopFaultTriggerUISignatures.java new file mode 100644 index 000000000..2330496fe --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopFaultTriggerUISignatures.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + + +public class ClosedLoopFaultTriggerUISignatures { + + private String signatures; + + private String connectSignatures; + + public String getConnectSignatures() { + return connectSignatures; + } + public void setConnectSignatures(String connectSignatures) { + this.connectSignatures = connectSignatures; + } + public String getSignatures() { + return signatures; + } + public void setSignatures(String signatures) { + this.signatures = signatures; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPMBody.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPMBody.java new file mode 100644 index 000000000..bbbf5508b --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPMBody.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +import java.util.Map; + +public class ClosedLoopPMBody { + + private boolean trinity; + private boolean vUSP; + private boolean mcr; + private boolean gama; + private boolean vDNS; + private String geoLink; + private String vServices; + private String ECOMPname; + + private String emailAddress; + + private String serviceTypePolicyName; + + private Map<String, String> attributes; + private String templateVersion; + + public String getTemplateVersion() { + return templateVersion; + } + + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + + public String getECOMPname(){ + return ECOMPname; + } + + public void setECOMPname(String ECOMPname){ + this.ECOMPname = ECOMPname; + } + + public String getvServices() { + return vServices; + } + + public void setvServices(String vServices) { + this.vServices = vServices; + } + + public Map<String, String> getAttributes() { + return attributes; + } + + public void setAttributes(Map<String, String> map) { + this.attributes = map; + } + + public String getGeoLink() { + return geoLink; + } + + public void setGeoLink(String geoLink) { + this.geoLink = geoLink; + } + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + public String getServiceTypePolicyName() { + return serviceTypePolicyName; + } + + public void setServiceTypePolicyName(String serviceTypePolicyName) { + this.serviceTypePolicyName = serviceTypePolicyName; + } + + public boolean isGama() { + return gama; + } + public void setGama(boolean gama) { + this.gama = gama; + } + public boolean isvDNS() { + return vDNS; + } + public void setvDNS(boolean vDNS) { + this.vDNS = vDNS; + } + + public boolean isTrinity() { + return trinity; + } + public void setTrinity(boolean trinity) { + this.trinity = trinity; + } + public boolean isvUSP() { + return vUSP; + } + public void setvUSP(boolean vUSP) { + this.vUSP = vUSP; + } + public boolean isMcr() { + return mcr; + } + public void setMcr(boolean mcr) { + this.mcr = mcr; + } + +} + diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPerformanceMetrics.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPerformanceMetrics.java new file mode 100644 index 000000000..25d83169f --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPerformanceMetrics.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +public class ClosedLoopPerformanceMetrics { + public static final String CLPM_UIFIELD_ONSET_MESSAGE = "Onset Message"; + public static final String CLPM_UIJSON_ONSET_MESSAGE = "attributes.OnsetMessage"; + + public static final String CLPM_UIFIELD_POLICY_NAME = "PolicyName"; + public static final String CLPM_UIJSON_POLICY_NAME = "attributes.PolicyName"; + + public static final String CLPM_UIFIELD_ABATEMENT_MESSAGE = "Abatement Message"; + public static final String CLPM_UIJSON_ABATEMENT_MESSAGE = "attributes.AbatementMessage"; + + public static final String CLPM_UIFIELD_GEOLINK = "Geo Link"; + public static final String CLPM_UIJSON_GEOLINK = "geoLink"; +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPolicy.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPolicy.java new file mode 100644 index 000000000..727c9cba8 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPolicy.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +public class ClosedLoopPolicy { + public static final String CLFAULT_UIFIELD_D2_SERVICES_TRINITY = "Hosted Voice (Trinity)"; + public static final String CLFAULT_UIJSON_D2_SERVICES_TRINITY = "trinity"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_VUSP = "vUSP"; + public static final String CLFAULT_UIJSON_D2_SERVICES_VUSP = "vUSP"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_MCR = "MCR"; + public static final String CLFAULT_UIJSON_D2_SERVICES_MCR = "mcr"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_GAMMA = "Gamma"; + public static final String CLFAULT_UIJSON_D2_SERVICES_GAMMA = "gama"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_VDNS = "vDNS"; + public static final String CLFAULT_UIJSON_D2_SERVICES_VDNS = "vDNS"; + + public static final String CLFAULT_UIFIELD_EMAIL_ADDRESS = "Email Address"; + public static final String CLFAULT_UIJSON_EMAIL_ADDRESS = "emailAddress"; + + public static final String CLFAULT_UIFIELD_TRIGGER_SIGNATURE = "Trigger Signature"; + public static final String CLFAULT_UIJSON_TRIGGER_SIGNATURE = "triggerSignaturesUsedForUI.signatures"; + + public static final String CLFAULT_UIFIELD_VERIFICATION_SIGNATURE = "Verification Signature"; + public static final String CLFAULT_UIJSON_VERIFICATION_SIGNATURE = "verificationSignaturesUsedForUI.signatures"; + + public static final String CLFAULT_UIFIELD_CONNECT_ALL_TRAPS = "Connect All Traps"; + public static final String CLFAULT_UIJSON_CONNECT_ALL_TRAPS = "triggerSignaturesUsedForUI.connectSignatures"; + + public static final String CLFAULT_UIFIELD_CONNECT_ALL_FAULTS = "Connect All Faults"; + public static final String CLFAULT_UIJSON_CONNECT_ALL_FAULTS = "verificationSignaturesUsedForUI.connectSignatures"; + + public static final String CLFAULT_UIFIELD_POLICY_STATUS_ACTIVE = "Active"; + public static final String CLFAULT_UIJSON_POLICY_STATUS_ACTIVE = "ACTIVE"; + + public static final String CLFAULT_UIFIELD_POLICY_STATUS_INACTIVE = "InActive"; + public static final String CLFAULT_UIJSON_POLICY_STATUS_INACTIVE = "INACTIVE"; + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPolicyConditions.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPolicyConditions.java new file mode 100644 index 000000000..cdae20e17 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPolicyConditions.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +public enum ClosedLoopPolicyConditions { + SEND("DCAE should send event notification"), + + NOTSEND("DCAE should not send event notification"); + private String name; + + private ClosedLoopPolicyConditions(String name){ + this.name = name; + } + + @Override + public String toString(){ + return this.name; + } +} + diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPolicyStatus.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPolicyStatus.java new file mode 100644 index 000000000..7ecd3b053 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopPolicyStatus.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +public enum ClosedLoopPolicyStatus { + ACTIVE("active"), + + INACTIVE("inactive") + ; + + private String name; + + private ClosedLoopPolicyStatus(String name){ + this.name = name; + } + + @Override + public String toString(){ + return this.name; + } +} + diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopSignatures.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopSignatures.java new file mode 100644 index 000000000..2eab27eea --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ClosedLoopSignatures.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +public class ClosedLoopSignatures { + + private String signatures; + + private int timeWindow; + + private Integer trapMaxAge; + + public String getSignatures() { + return signatures; + } + public void setSignatures(String signatures) { + this.signatures = signatures; + } + + public Integer getTimeWindow() { + return timeWindow; + } + public void setTimeWindow(Integer timeWindow) { + this.timeWindow = timeWindow; + } + + public Integer getTrapMaxAge() { + return trapMaxAge; + } + public void setTrapMaxAge(Integer trapMaxAge) { + this.trapMaxAge = trapMaxAge; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/DeletePolicyCondition.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/DeletePolicyCondition.java new file mode 100644 index 000000000..4698aa672 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/DeletePolicyCondition.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +public enum DeletePolicyCondition { + ONE("Are you sure you want to delete Current Version of policy"), + + ALL("Are you sure you want to delete All Versions of policy"); + private String name; + + private DeletePolicyCondition(String name){ + this.name = name; + } + + @Override + public String toString(){ + return this.name; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/DeployNowJson.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/DeployNowJson.java new file mode 100644 index 000000000..635431559 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/DeployNowJson.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +public class DeployNowJson { + + protected boolean deployNow; + + // deployNow + public boolean getDeployNow() { + return deployNow; + } + + public void setDeployNow(boolean value) { + this.deployNow = value; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/GridData.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/GridData.java new file mode 100644 index 000000000..dfb3e0024 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/GridData.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +import java.util.ArrayList; + +public class GridData { + private ArrayList<Object> attributes; + private ArrayList<Object> transportProtocols; + private ArrayList<Object> appProtocols; + + public ArrayList<Object> getAttributes() { + return attributes; + } + + public void setAttributes(ArrayList<Object> attributes) { + this.attributes = attributes; + } + + public ArrayList<Object> getAppProtocols() { + return appProtocols; + } + + public void setAppProtocols(ArrayList<Object> appProtocols) { + this.appProtocols = appProtocols; + } + + public ArrayList<Object> getTransportProtocols() { + return transportProtocols; + } + + public void setTransportProtocols(ArrayList<Object> transportProtocols) { + this.transportProtocols = transportProtocols; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/PolicyAdapter.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/PolicyAdapter.java new file mode 100644 index 000000000..f9a0bd48e --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/PolicyAdapter.java @@ -0,0 +1,619 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.policy.rest.jpa.EcompName; + +public class PolicyAdapter { + + private Object data; + private String policyName = null; + private Path parentPath; + public boolean isEditPolicy = false; + private boolean isViewPolicy = false; + private Object policyData = null; + private String comboPolicyType; + private boolean readOnly; + + //adding new properties for REST interface call when creating Policies + private String oldPolicyFileName = null; + private String configType = null; + private String policyID = null; + private String policyType = null; + private String configPolicyType = null; + private String policyDescription = null; + private String ecompName = null; + private String configName = null; + private String ruleID = null; + private String ruleCombiningAlgId = null; + private Map<String,String> dynamicFieldConfigAttributes; + private Map<String,String> dropDownMap; + private Map<String,String> dynamicSettingsMap; + private Path gitPath; + private String configBodyData = null; + private boolean isValidData = false; + private boolean draft = false; + private String version = null; + private String domain = null; + private String filterName = null; + private String comboConfigPolicyType; + private String jsonBody = null; + private Map<String,String> brmsParamBody=null; + private Integer highestVersion; + private String actionPerformer = null; + private String actionAttribute = null; + private List<String> dynamicRuleAlgorithmLabels; + private List<String> dynamicRuleAlgorithmCombo; + private List<String> dynamicRuleAlgorithmField1; + private List<String> dynamicRuleAlgorithmField2; + private List<Object> dynamicVariableList; + private List<String> dataTypeList; + private String actionBody = null; + private String actionDictHeader = null; + private String actionDictType = null; + private String actionDictUrl = null; + private String actionDictMethod = null; + private String serviceType = null; + private String uuid = null; + private String location = null; + private String priority = null; + private String actionAttributeValue; + private String ruleProvider; + + private EcompName ecompNameField; + private Object jsonBodyData; + private String dirPath; + private String configBodyPath; + private ArrayList<Object> attributes; + private ArrayList<Object> settings; + private ArrayList<Object> ruleAlgorithmschoices; + + private LinkedHashMap<?, ?> serviceTypePolicyName; + private String ruleName; + private LinkedHashMap<?, ?> ruleData; + private LinkedHashMap<?,?> ruleListData; + private String clearTimeOut; + private String trapMaxAge; + private String verificationclearTimeOut; + private String fwPolicyType; + private ArrayList<Object> fwattributes; + private String parentForChild; + public String getFwPolicyType() { + return fwPolicyType; + } + public ArrayList<Object> getFwattributes() { + return fwattributes; + } + public String getParentForChild() { + return parentForChild; + } + public void setFwPolicyType(String fwPolicyType) { + this.fwPolicyType = fwPolicyType; + } + public void setFwattributes(ArrayList<Object> fwattributes) { + this.fwattributes = fwattributes; + } + public void setParentForChild(String parentForChild) { + this.parentForChild = parentForChild; + } + + private String riskLevel; + private String riskType = null; + private String guard = null; + private String ttlDate = null; + + public String getClearTimeOut() { + return clearTimeOut; + } + public void setClearTimeOut(String clearTimeOut) { + this.clearTimeOut = clearTimeOut; + } + public String getTrapMaxAge() { + return trapMaxAge; + } + public void setTrapMaxAge(String trapMaxAge) { + this.trapMaxAge = trapMaxAge; + } + public String getVerificationclearTimeOut() { + return verificationclearTimeOut; + } + public void setVerificationclearTimeOut(String verificationclearTimeOut) { + this.verificationclearTimeOut = verificationclearTimeOut; + } + public LinkedHashMap<?, ?> getRuleListData() { + return ruleListData; + } + public void setRuleListData(LinkedHashMap<?, ?> ruleListData) { + this.ruleListData = ruleListData; + } + private ArrayList<Object> triggerSignatures; + private ArrayList<Object> symptomSignatures; + private String logicalConnector; + private String policyStatus; + public String gocServerScope; + public Map<String , String> dynamicLayoutMap; + private String securityZone; + + private String policyScope; + private String supressionType; + + + + public String getSupressionType() { + return supressionType; + } + public void setSupressionType(String supressionType) { + this.supressionType = supressionType; + } + public Map<String, String> getDynamicLayoutMap() { + return dynamicLayoutMap; + } + public void setDynamicLayoutMap(Map<String, String> dynamicLayoutMap) { + this.dynamicLayoutMap = dynamicLayoutMap; + } + public String getGocServerScope() { + return gocServerScope; + } + public void setGocServerScope(String gocServerScope) { + this.gocServerScope = gocServerScope; + } + public Object getJsonBodyData() { + return jsonBodyData; + } + public void setJsonBodyData(Object jsonBodyData) { + this.jsonBodyData = jsonBodyData; + } + public EcompName getEcompNameField() { + return ecompNameField; + } + public void setEcompNameField(EcompName ecompNameField) { + this.ecompNameField = ecompNameField; + } + public Integer getHighestVersion() { + return highestVersion; + } + public void setHighestVersion(Integer highestVersion) { + this.highestVersion = highestVersion; + } + public String getConfigType() { + return configType; + } + public void setConfigType(String configType) { + this.configType = configType; + } + public String getPolicyID() { + return policyID; + } + public void setPolicyID(String policyID) { + this.policyID = policyID; + } + public String getPolicyType() { + return policyType; + } + public void setPolicyType(String policyType) { + this.policyType = policyType; + } + public String getPolicyDescription() { + return policyDescription; + } + public void setPolicyDescription(String policyDescription) { + this.policyDescription = policyDescription; + } + public String getEcompName() { + return ecompName; + } + public void setEcompName(String ecompName) { + this.ecompName = ecompName; + } + public String getConfigName() { + return configName; + } + public void setConfigName(String configName) { + this.configName = configName; + } + public String getRuleID() { + return ruleID; + } + public void setRuleID(String ruleID) { + this.ruleID = ruleID; + } + public String getRuleCombiningAlgId() { + return ruleCombiningAlgId; + } + public void setRuleCombiningAlgId(String ruleCombiningAlgId) { + this.ruleCombiningAlgId = ruleCombiningAlgId; + } + public Map<String, String> getDynamicFieldConfigAttributes() { + return dynamicFieldConfigAttributes; + } + public void setDynamicFieldConfigAttributes( + Map<String, String> dynamicFieldConfigAttributes) { + this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; + } + public Path getGitPath() { + return gitPath; + } + public void setGitPath(Path gitPath) { + this.gitPath = gitPath; + } + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } + public String getPolicyName() { + return policyName; + } + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + public Path getParentPath() { + return parentPath; + } + public void setParentPath(Path parentPath) { + this.parentPath = parentPath; + } + public boolean isEditPolicy() { + return isEditPolicy; + } + public void setEditPolicy(boolean isEditPolicy) { + this.isEditPolicy = isEditPolicy; + } + public boolean isViewPolicy() { + return isViewPolicy; + } + public void setViewPolicy(boolean isViewPolicy) { + this.isViewPolicy = isViewPolicy; + } + public Object getPolicyData() { + return policyData; + } + public void setPolicyData(Object policyData) { + this.policyData = policyData; + } + public String getComboPolicyType() { + return comboPolicyType; + } + public void setComboPolicyType(String comboPolicyType) { + this.comboPolicyType = comboPolicyType; + } + public boolean isReadOnly() { + return readOnly; + } + public void setReadOnly(boolean readOnly) { + this.readOnly = readOnly; + } + public String getConfigBodyData() { + return configBodyData; + } + public void setConfigBodyData(String configBodyData) { + this.configBodyData = configBodyData; + } + public boolean isValidData() { + return isValidData; + } + public void setValidData(boolean isValidData) { + this.isValidData = isValidData; + } + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } + public String getDomainDir() { + return domain; + } + public void setDomainDir(java.lang.String domain) { + this.domain = domain; + + } + public String getFilterName() { + return filterName; + } + public void setFilterName(String filterName) { + this.filterName = filterName; + } + public String getComboConfigPolicyType() { + return comboConfigPolicyType; + } + public void setComboConfigPolicyType(String comboConfigPolicyType) { + this.comboConfigPolicyType = comboConfigPolicyType; + } + public Map<String, String> getBRMSParamBody() { + return brmsParamBody; + } + public void setBRMSParamBody(Map<String, String> brmsParamBody) { + this.brmsParamBody = brmsParamBody; + } + public String getJsonBody() { + return jsonBody; + } + public void setJsonBody(String jsonBody) { + this.jsonBody = jsonBody; + } + public String getConfigPolicyType() { + return configPolicyType; + } + public void setConfigPolicyType(String configPolicyType) { + this.configPolicyType = configPolicyType; + } + public String getActionPerformer() { + return actionPerformer; + } + public void setActionPerformer(String actionPerformer) { + this.actionPerformer = actionPerformer; + } + public String getActionAttribute() { + return actionAttribute; + } + public void setActionAttribute(String actionAttribute) { + this.actionAttribute = actionAttribute; + } + public List<String> getDynamicRuleAlgorithmLabels() { + return dynamicRuleAlgorithmLabels; + } + public void setDynamicRuleAlgorithmLabels( + List<String> dynamicRuleAlgorithmLabels) { + this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; + } + public List<String> getDynamicRuleAlgorithmCombo() { + return dynamicRuleAlgorithmCombo; + } + public void setDynamicRuleAlgorithmCombo( + List<String> dynamicRuleAlgorithmCombo) { + this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; + } + public List<String> getDynamicRuleAlgorithmField1() { + return dynamicRuleAlgorithmField1; + } + public void setDynamicRuleAlgorithmField1( + List<String> dynamicRuleAlgorithmField1) { + this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; + } + public List<String> getDynamicRuleAlgorithmField2() { + return dynamicRuleAlgorithmField2; + } + public void setDynamicRuleAlgorithmField2( + List<String> dynamicRuleAlgorithmField2) { + this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; + } + public String getActionBody() { + return actionBody; + } + public void setActionBody(String actionBody) { + this.actionBody = actionBody; + } + public Map<String,String> getDropDownMap() { + return dropDownMap; + } + public void setDropDownMap(Map<String,String> dropDownMap) { + this.dropDownMap = dropDownMap; + } + public String getActionDictHeader() { + return actionDictHeader; + } + public void setActionDictHeader(String actionDictHeader) { + this.actionDictHeader = actionDictHeader; + } + public String getActionDictType() { + return actionDictType; + } + public void setActionDictType(String actionDictType) { + this.actionDictType = actionDictType; + } + public String getActionDictUrl() { + return actionDictUrl; + } + public void setActionDictUrl(String actionDictUrl) { + this.actionDictUrl = actionDictUrl; + } + public String getActionDictMethod() { + return actionDictMethod; + } + public void setActionDictMethod(String actionDictMethod) { + this.actionDictMethod = actionDictMethod; + } + public boolean isDraft() { + return draft; + } + public void setDraft(boolean draft) { + this.draft = draft; + } + public Map<String,String> getDynamicSettingsMap() { + return dynamicSettingsMap; + } + public void setDynamicSettingsMap(Map<String,String> dynamicSettingsMap) { + this.dynamicSettingsMap = dynamicSettingsMap; + } + public List<Object> getDynamicVariableList() { + return dynamicVariableList; + } + public void setDynamicVariableList(List<Object> dynamicVariableList) { + this.dynamicVariableList = dynamicVariableList; + } + public List<String> getDataTypeList() { + return dataTypeList; + } + public void setDataTypeList(List<String> dataTypeList) { + this.dataTypeList = dataTypeList; + } + public String getOldPolicyFileName() { + return oldPolicyFileName; + } + public void setOldPolicyFileName(String oldPolicyFileName) { + this.oldPolicyFileName = oldPolicyFileName; + } + public String getServiceType() { + return serviceType; + } + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getLocation() { + return location; + } + public void setLocation(String location) { + this.location = location; + } + public String getPriority() { + return priority; + } + public void setPriority(String priority) { + this.priority = priority; + } + public String getDirPath() { + return dirPath; + } + public void setDirPath(String dirPath) { + this.dirPath = dirPath; + } + public String getConfigBodyPath() { + return configBodyPath; + } + public void setConfigBodyPath(String configBodyPath) { + this.configBodyPath = configBodyPath; + } + public ArrayList<Object> getAttributes() { + return attributes; + } + + @SuppressWarnings("unchecked") + public void setAttributes(Object attributes) { + this.attributes = (ArrayList<Object>) attributes; + } + public LinkedHashMap<?, ?> getServiceTypePolicyName() { + return serviceTypePolicyName; + } + public void setServiceTypePolicyName(LinkedHashMap<?, ?> serviceTypePolicyName) { + this.serviceTypePolicyName = (LinkedHashMap<?, ?>) serviceTypePolicyName; + } + public ArrayList<Object> getSettings() { + return settings; + } + public void setSettings(ArrayList<Object> settings) { + this.settings = settings; + } + public String getRuleName() { + return ruleName; + } + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + public LinkedHashMap<?, ?> getRuleData() { + return ruleData; + } + public void setRuleData(LinkedHashMap<?, ?> ruleData) { + this.ruleData = ruleData; + } + public ArrayList<Object> getTriggerSignatures() { + return triggerSignatures; + } + public void setTriggerSignatures(ArrayList<Object> triggerSignatures) { + this.triggerSignatures = triggerSignatures; + } + public String getLogicalConnector() { + return logicalConnector; + } + public void setLogicalConnector(String logicalConnector) { + this.logicalConnector = logicalConnector; + } + public String getPolicyStatus() { + return policyStatus; + } + public void setPolicyStatus(String policyStatus) { + this.policyStatus = policyStatus; + } + public String getActionAttributeValue() { + return actionAttributeValue; + } + public void setActionAttributeValue(String actionAttributeValue) { + this.actionAttributeValue = actionAttributeValue; + } + public ArrayList<Object> getRuleAlgorithmschoices() { + return ruleAlgorithmschoices; + } + public void setRuleAlgorithmschoices(ArrayList<Object> ruleAlgorithmschoices) { + this.ruleAlgorithmschoices = ruleAlgorithmschoices; + } + public String getSecurityZone() { + return securityZone; + } + public void setSecurityZone(String securityZone) { + this.securityZone = securityZone; + } + public ArrayList<Object> getSymptomSignatures() { + return symptomSignatures; + } + public void setSymptomSignatures(ArrayList<Object> symptomSignatures) { + this.symptomSignatures = symptomSignatures; + } + public String getPolicyScope() { + return policyScope; + } + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + public String getRuleProvider() { + return ruleProvider; + } + public void setRuleProvider(String ruleProvider) { + this.ruleProvider = ruleProvider; + } + public String getRiskLevel() { + return riskLevel; + } + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + public String getRiskType() { + return riskType; + } + public void setRiskType(String riskType) { + this.riskType = riskType; + } + public String getGuard() { + return guard; + } + public void setGuard(String guard) { + this.guard = guard; + } + public String getTtlDate() { + return ttlDate; + } + public void setTtlDate(String ttlDate) { + this.ttlDate = ttlDate; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/PolicyExportAdapter.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/PolicyExportAdapter.java new file mode 100644 index 000000000..37ed83d16 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/PolicyExportAdapter.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +import java.util.ArrayList; + +public class PolicyExportAdapter { + + private ArrayList<Object> policyDatas; + + public ArrayList<Object> getPolicyDatas() { + return policyDatas; + } + public void setPolicyDatas(ArrayList<Object> policyDatas) { + this.policyDatas = policyDatas; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/PrefixIPList.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/PrefixIPList.java new file mode 100644 index 000000000..e2c70e69f --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/PrefixIPList.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + + +import java.util.ArrayList; +import java.util.List; + + +public class PrefixIPList { + protected String name; + protected String description; + protected List<AddressMembers> members; + /* protected String type; + protected String value;*/ + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List<AddressMembers> getMembers() + { + if(members==null) + { + members= new ArrayList<AddressMembers>(); + } + return this.members; + } + + public void setMembers(List<AddressMembers> members) + { + this.members = members; + } + /*public String getValue() { + return value; + } + + + public void setValue(String value) { + this.value = value; + }*/ + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServiceGroupJson.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServiceGroupJson.java new file mode 100644 index 000000000..1cc34fbb4 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServiceGroupJson.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +import java.util.ArrayList; +import java.util.List; + +public class ServiceGroupJson { + + protected String name; + protected String description; + protected List<ServiceMembers> members; + + // name + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } + + public boolean equals(Object obj) + { + ServiceGroupJson servGroupobj=(ServiceGroupJson) obj; + if(this.getName().equals(servGroupobj.getName())) + { + return true; + } + return false; + } + + public int hashCode() { + return Integer.valueOf(name.charAt(0)+(name.charAt(1))); + } + + // description + public String getDescription() { + return description; + } + + public void setDescription(String value) { + this.description = value; + } + + public List<ServiceMembers> getMembers() + { + if(members==null) + { + members= new ArrayList<ServiceMembers>(); + } + return this.members; + } + + public void setMembers(List<ServiceMembers> members) + { + this.members = members; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServiceListJson.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServiceListJson.java new file mode 100644 index 000000000..05df303b9 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServiceListJson.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + + +public class ServiceListJson { + + protected String name; + protected String description; + protected String type; + protected String transportProtocol; + protected String appProtocol; + protected String ports; + // name + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } + + public boolean equals(Object obj) + { + ServiceListJson servobj=(ServiceListJson) obj; + if(this.getName().equals(servobj.getName())) + { + return true; + } + return false; + } + + public int hashCode() { + if(name!=null){ + return Integer.valueOf(name.charAt(0)+(name.charAt(1))); + }else{ + return 0; + } + } + + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + // type + public String getType() { + return type; + } + + public void setType(String value) { + this.type = value; + } + + // transportProtocol + public String getTransportProtocol() { + return transportProtocol; + } + + public void setTransportProtocol(String value) { + this.transportProtocol = value; + } + + // appProtocol + public String getAppProtocol() { + return appProtocol; + } + + public void setAppProtocol(String value) { + this.appProtocol = value; + } + + // ports + public String getPorts() { + return ports; + } + + public void setPorts(String value) { + this.ports = value; + } + + + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServiceMembers.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServiceMembers.java new file mode 100644 index 000000000..a8b1abea5 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServiceMembers.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + + +public class ServiceMembers { + + protected String type; + protected String name; + + // type + public String getType() { + return type; + } + + public void setType(String value) { + this.type = value; + } + + // transportProtocol + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServicesJson.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServicesJson.java new file mode 100644 index 000000000..bdc9232b5 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/ServicesJson.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + +public class ServicesJson { + + protected String type; + protected String name; + // type + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/Term.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/Term.java new file mode 100644 index 000000000..3080f2707 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/Term.java @@ -0,0 +1,201 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + + +public class Term { + + String position; + protected String ruleName; + protected List<String> fromZones; + protected List<String> toZones; + protected boolean negateSource; //hardcoded + protected boolean negateDestination; //hardcoded + protected List<AddressJson> sourceList; + protected List<AddressJson> destinationList; + protected List<ServicesJson> sourceServices; + protected Set<ServicesJson> destServices; + protected String action; + protected String description; + boolean enabled; //hardcoded + boolean log; //hardcoded + + //position + public String getPosition() { + return position; + } + + public void setPosition(String value) { + this.position = value; + } + + //RuleName + public String getRuleName() { + return ruleName; + } + + public void setRuleName(String value) { + this.ruleName = value; + } + + //From Zone + public List<String> getFromZones() { + if (fromZones==null) + { + fromZones= new ArrayList<String>(); + } + return fromZones; + } + + public void setFromZones(List<String> fromZones) { + this.fromZones = fromZones; + } + + //To Zone + public List<String> getToZones() { + if (toZones==null) + { + toZones= new ArrayList<String>(); + } + return toZones; + } + + public void setToZones(List<String> toZones) { + this.toZones = toZones; + } + + + //Negate Source + public boolean getNegateSource() { + return negateSource; + } + + public void setNegateSource(boolean negateSource) { + this.negateSource = negateSource; + } + + //Negate Destination + public boolean getNegateDestination() { + return negateDestination; + } + + public void setNegateDestination(boolean negateDestination) { + this.negateDestination = negateDestination; + } + + //SourceList + public List<AddressJson> getSourceList() + { + if(sourceList==null) + { + sourceList= new ArrayList<AddressJson>(); + } + return this.sourceList; + } + + public void setSourceList(List<AddressJson> srcList) { + this.sourceList = srcList; + } + + //Destination List + public List<AddressJson> getDestinationList() + { + if(destinationList==null) + { + destinationList= new ArrayList<AddressJson>(); + } + return this.destinationList; + } + + public void setDestinationList(List<AddressJson> destList) { + this.destinationList = destList; + } + + //Source Services + public List<ServicesJson> getSourceServices() { + if(sourceServices==null) + { + sourceServices= new ArrayList<ServicesJson>(); + } + return this.sourceServices; + } + + public void setSourceServices(List<ServicesJson> sourceServices) { + this.sourceServices = sourceServices; + } + + //Destination services. + public Set<ServicesJson> getDestServices() { + if(destServices==null) + { + destServices= new HashSet<ServicesJson>(); + } + return this.destServices; + } + + public void setDestServices(Set<ServicesJson> destServices) { + this.destServices = destServices; + } + + //Action + public String getAction() { + return action; + } + + public void setAction(String value) { + this.action = value; + } + + //description + public String getDescription() { + return description; + } + + public void setDescription(String desc) { + this.description = desc; + } + + //enabled + public boolean getEnabled() { + return enabled; + } + + public void setEnabled(boolean value) { + this.enabled = value; + } + + //Log + public boolean getLog() { + return log; + } + + public void setLog(boolean value) { + this.log = value; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/TermCollector.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/TermCollector.java new file mode 100644 index 000000000..169ab3637 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/adapter/TermCollector.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.adapter; + + + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + + +public class TermCollector { + String serviceTypeId; + String configName; + DeployNowJson deploymentOption; + String securityZoneId; + + protected Set<Object> serviceGroups; + protected Set<Object> addressGroups; + protected List<Term> firewallRuleList; + + private String primaryParentZoneId; + + + //SecurityTypeId + public String getServiceTypeId() { + return serviceTypeId; + } + + public void setServiceTypeId(String serviceTypeId) { + this.serviceTypeId = serviceTypeId; + } + + //ConfigName + public String getConfigName() { + return configName; + } + + public void setConfigName(String configName) { + this.configName = configName; + } + + //DeploymentControl + public DeployNowJson getDeploymentOption() { + return deploymentOption; + } + + public void setDeploymentOption(DeployNowJson deploymentOption) { + this.deploymentOption = deploymentOption; + } + + //SecurityZoneId + public String getSecurityZoneId() { + return securityZoneId; + } + public void setSecurityZoneId(String securityZoneId) { + this.securityZoneId = securityZoneId; + } + + + //ServiceGroup + public Set<Object> getServiceGroups() { + if(serviceGroups==null) + { + serviceGroups= new HashSet<Object>(); + } + return this.serviceGroups; + } + + public void setServiceGroups(Set<Object> servListArray) { + this.serviceGroups = servListArray; + } + + //AddressGroup + public Set<Object> getAddressGroups() { + if(addressGroups==null) + { + addressGroups= new HashSet<Object>(); + } + return this.addressGroups; + } + + public void setAddressGroups(Set<Object> addressGroups) { + this.addressGroups = addressGroups; + } + + //FirewallRuleList + public List<Term> getFirewallRuleList() { + + if(firewallRuleList==null) + { + firewallRuleList= new ArrayList<Term>(); + } + return this.firewallRuleList; + } + + public void setFirewallRuleList(List<Term> firewallRuleList) { + this.firewallRuleList = firewallRuleList; + } + + + //primaryParentZoneId + public String getPrimaryParentZoneId() { + return primaryParentZoneId; + } + + public void setPrimaryParentZoneId(String primaryParentZoneId) { + this.primaryParentZoneId = primaryParentZoneId; + } + + + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/CheckPDP.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/CheckPDP.java new file mode 100644 index 000000000..f1447f135 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/CheckPDP.java @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.admin; + + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; + +import org.openecomp.policy.rest.XACMLRestProperties; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.util.XACMLProperties; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +public class CheckPDP { + private static Path pdpPath = null; + private static Properties pdpProp = null; + private static Long oldModified = null; + private static Long newModified = null; + private static HashMap<String, String> pdpMap = null; + private static final Logger logger = FlexLogger.getLogger(CheckPDP.class); + + public static boolean validateID(String id) { + // ReadFile + try { + readFile(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + return false; + } + // Check ID + if (pdpMap.containsKey(id)) { + return true; + } + return false; + } + + private static void readFile() throws Exception { + String pdpFile = null; + try{ + pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); + }catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File"); + return; + } + if (pdpFile == null) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile); + } + if (pdpPath == null) { + pdpPath = Paths.get(pdpFile); + if (Files.notExists(pdpPath)) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath.toString()); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString()); + } + if (pdpPath.toString().endsWith(".properties")) { + readProps(); + } else { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + pdpFile); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file"); + } + } + // Check if File is updated recently + else { + newModified = pdpPath.toFile().lastModified(); + if (newModified != oldModified) { + // File has been updated. + readProps(); + } + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void readProps() throws Exception { + InputStream in; + pdpProp = new Properties(); + try { + in = new FileInputStream(pdpPath.toFile()); + oldModified = pdpPath.toFile().lastModified(); + pdpProp.load(in); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + throw new Exception("Cannot Load the Properties file", e); + } + // Read the Properties and Load the PDPs and encoding. + pdpMap = new HashMap<String, String>(); + // Check the Keys for PDP_URLs + Collection<Object> unsorted = pdpProp.keySet(); + List<String> sorted = new ArrayList(unsorted); + Collections.sort(sorted); + for (String propKey : sorted) { + if (propKey.startsWith("PDP_URL")) { + String check_val = pdpProp.getProperty(propKey); + if (check_val == null) { + throw new Exception("Properties file doesn't have the PDP_URL parameter"); + } + if (check_val.contains(";")) { + List<String> pdp_default = new ArrayList<String>(Arrays.asList(check_val.split("\\s*;\\s*"))); + int pdpCount = 0; + while (pdpCount < pdp_default.size()) { + String pdpVal = pdp_default.get(pdpCount); + readPDPParam(pdpVal); + pdpCount++; + } + } else { + readPDPParam(check_val); + } + } + } + if (pdpMap == null || pdpMap.isEmpty()) { + logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs"); + } + } + + private static void readPDPParam(String pdpVal) throws Exception{ + if(pdpVal.contains(",")){ + List<String> pdpValues = new ArrayList<String>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); + if(pdpValues.size()==3){ + // 1:2 will be UserID:Password + String userID = pdpValues.get(1); + String pass = pdpValues.get(2); + Base64.Encoder encoder = Base64.getEncoder(); + // 0 - PDPURL + pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); + }else{ + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues); + throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); + } + }else{ + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); + throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request."); + } + } + + public static String getEncoding(String pdpID){ + try { + readFile(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + String encoding = null; + if(pdpMap!=null && (!pdpMap.isEmpty())){ + try{ + encoding = pdpMap.get(pdpID); + } catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + return encoding; + }else{ + return null; + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PAPNotificationBroadcaster.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PAPNotificationBroadcaster.java new file mode 100644 index 000000000..cff0828e2 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PAPNotificationBroadcaster.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.admin; + + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +/** + * Handle Notifications from the PAP that the PDP Groups have been changed. + * We need a Server Push Broadcaster because there may be multiple Vaadin instances (i.e. Users) that need to be told when a change occurs. + * + * Initially we only update the entire set of PDPGroups in one shot. + * + * (Code copied from Book of Vaadin chapter on Server Push + * + */ +public class PAPNotificationBroadcaster implements Serializable { + /** + * + */ + private static final long serialVersionUID = -2539940306348821754L; + + + private static Logger logger = FlexLogger.getLogger(PAPNotificationBroadcaster.class); + + + static ExecutorService executorService = Executors.newSingleThreadExecutor(); + + /** + * Interface used by all classes that need to be notified when PAP sends an update message. + * + * + */ + public interface PAPNotificationBroadcastListener { + void updateAllGroups(); + } + + + + /* + * list of registered listeners + */ + private static LinkedList<PAPNotificationBroadcastListener> listeners = + new LinkedList<PAPNotificationBroadcastListener>(); + + /** + * Listener registers to hear about updates. + * @param listener + */ + public static synchronized void register( + PAPNotificationBroadcastListener listener) { + listeners.add(listener); + } + + + /** + * Listener is going away. + * + * @param listener + */ + public static synchronized void unregister( + PAPNotificationBroadcastListener listener) { + listeners.remove(listener); + } + + + + /** + * Tell all listeners about an update. + * + * @param message + */ + public static synchronized void updateAllGroups() { + for (final PAPNotificationBroadcastListener listener: listeners) { + // Original code copied from example: + // executorService.execute(new Runnable() { + // @Override + // public void run() { + // The problem with this is that the execute starts a new Thread, but the thing we are calling (the listener.updateAllGroups) + // happens in this case to ALSO create a new thread, and it locks up because the shared threadpool queue is already locked by this method. + // On application shutdown that left us with a blocked thread, so the process never goes away. + // Since the listener.updateAllGroups does ALL of its work inside a new Runnable thread, there should be no need for this method to also create a thread. + + /* + * IMPORTANT: + * All listeners MUST either execute with no possibility of blocking + * OR must start their own threads to handle blocking and concurrent operations. + */ + if (logger.isDebugEnabled()) { + logger.debug("updateAllGroups"); + } + listener.updateAllGroups(); + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java new file mode 100644 index 000000000..e355b8295 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java @@ -0,0 +1,1334 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +/* + * + * + * + * */ +package org.openecomp.policy.admin; + + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.compress.utils.IOUtils; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.apache.http.HttpStatus; +import org.json.JSONException; +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.components.HumanPolicyComponent; +import org.openecomp.policy.controller.ActionPolicyController; +import org.openecomp.policy.controller.CreateBRMSParamController; +import org.openecomp.policy.controller.CreateBRMSRawController; +import org.openecomp.policy.controller.CreateClosedLoopFaultController; +import org.openecomp.policy.controller.CreateClosedLoopPMController; +import org.openecomp.policy.controller.CreateDcaeMicroServiceController; +import org.openecomp.policy.controller.CreateFirewallController; +import org.openecomp.policy.controller.CreatePolicyController; +import org.openecomp.policy.controller.DecisionPolicyController; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.controller.PolicyExportAndImportController; +import org.openecomp.policy.elk.client.ElkConnector; +import org.openecomp.policy.model.Roles; +import org.openecomp.policy.rest.jpa.PolicyEditorScopes; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.UserInfo; +import org.openecomp.policy.utils.XACMLPolicyWriterWithPapNotify; +import org.openecomp.portalsdk.core.web.support.UserUtils; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PolicyManagerServlet extends HttpServlet { + private static final Logger LOG = FlexLogger.getLogger(PolicyManagerServlet.class); + private static final long serialVersionUID = -8453502699403909016L; + + private enum Mode { + LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT + } + + public static final String REPOSITORY_BASE_PATH = PolicyController.getGitPath().toString(); + private static String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss"; + public static final String CONFIG_HOME = PolicyController.getConfigHome(); + public static final String ACTION_HOME = PolicyController.getActionHome(); + private static String CONTENTTYPE = "application/json"; + private File repofilePath; + private static String SUPERADMIN = "super-admin"; + private static String SUPEREDITOR = "super-editor"; + private static String SUPERGUEST = "super-guest"; + private static String ADMIN = "admin"; + private static String EDITOR = "editor"; + private static String GUEST = "guest"; + private static String RESULT = "result"; + private static String REPOSITORY = "repository"; + + private static String CONFIG = "Config_"; + private static String ACTION = "Action_"; + private static String DECISION = "Decision_"; + + @Override + public void init() throws ServletException { + super.init(); + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String path = request.getParameter("path"); + File file = new File(REPOSITORY_BASE_PATH, path); + + if (!file.isFile()) { + // if not a file, it is a folder, show this error. + response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource Not Found"); + return; + } + + response.setHeader("Content-Type", getServletContext().getMimeType(file.getName())); + response.setHeader("Content-Length", String.valueOf(file.length())); + response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); + + FileInputStream input = null; + BufferedOutputStream output = null; + try { + input = new FileInputStream(file); + output = new BufferedOutputStream(response.getOutputStream()); + byte[] buffer = new byte[8192]; + for (int length = 0; (length = input.read(buffer)) > 0;) { + output.write(buffer, 0, length); + } + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Reading Imput Stream" + e); + } finally { + if (output != null) { + try { + output.close(); + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Closing Output Stream" + e); + } + } + if (input != null) { + try { + input.close(); + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Closing Input Stream" + e); + } + } + } + + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + LOG.debug("doPost"); + try { + // if request contains multipart-form-data + if (ServletFileUpload.isMultipartContent(request)) { + uploadFile(request, response); + } + // all other post request has json params in body + else { + fileOperation(request, response); + } + } catch (Exception e) { + setError(e, response); + } + } + + //Set Error Message for Exception + private void setError(Exception t, HttpServletResponse response) throws IOException { + try { + JSONObject responseJsonObject = error(t.getMessage()); + response.setContentType(CONTENTTYPE); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } catch (Exception x) { + response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage()); + } + } + + //Policy Import Functionality + private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException { + try { + String newFile; + Map<String, InputStream> files = new HashMap<String, InputStream>(); + + List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + for (FileItem item : items) { + if (!item.isFormField()) { + // Process form file field (input type="file"). + files.put(item.getName(), item.getInputStream()); + if(item.getName().endsWith(".tar")){ + try{ + File file = new File(item.getName()); + OutputStream outputStream = new FileOutputStream(file); + IOUtils.copy(item.getInputStream(), outputStream); + outputStream.close(); + newFile = file.toString(); + PolicyExportAndImportController importController = new PolicyExportAndImportController(); + importController.ImportRepositoryFile(newFile, request); + }catch(Exception e){ + LOG.error("Upload error : " + e); + } + } + } + } + + JSONObject responseJsonObject = null; + responseJsonObject = this.success(); + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } catch (Exception e) { + LOG.debug("Cannot write file"); + throw new ServletException("Cannot write file", e); + } + } + + //File Operation Functionality + private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject responseJsonObject = null; + try { + StringBuilder sb = new StringBuilder(); + BufferedReader br = request.getReader(); + String str; + while ((str = br.readLine()) != null) { + sb.append(str); + } + br.close(); + JSONObject jObj = new JSONObject(sb.toString()); + JSONObject params = jObj.getJSONObject("params"); + Mode mode = Mode.valueOf(params.getString("mode")); + switch (mode) { + case ADDFOLDER: + responseJsonObject = addFolder(params, request); + break; + case COPY: + responseJsonObject = copy(params, request); + break; + case DELETE: + responseJsonObject = delete(params, request); + break; + case EDITFILE: + responseJsonObject = editFile(params); + break; + case VIEWPOLICY: + responseJsonObject = editFile(params); + break; + case LIST: + responseJsonObject = list(params, request); + break; + case RENAME: + responseJsonObject = rename(params, request); + break; + case DESCRIBEPOLICYFILE: + responseJsonObject = describePolicy(params); + break; + case ADDSUBSCOPE: + responseJsonObject = addFolder(params, request); + break; + case SWITCHVERSION: + responseJsonObject = switchVersion(params, request); + break; + default: + throw new ServletException("not implemented"); + } + if (responseJsonObject == null) { + responseJsonObject = error("generic error : responseJsonObject is null"); + } + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e); + responseJsonObject = error(e.getMessage()); + } + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } + + //Switch Version Functionality + private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{ + String path = params.getString("path"); + String userId = null; + try { + userId = UserUtils.getUserIdFromCookie(request); + } catch (Exception e) { + LOG.error("Exception Occured while reading userid from cookie" +e); + } + if(params.toString().contains("activeVersion")){ + String activeVersion = params.getString("activeVersion"); + String highestVersion = params.getString("highestVersion"); + if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){ + return error("The Version shouldn't be greater than Highest Value"); + }else{ + String removeExtension = path.replace(".xml", ""); + String policyName = removeExtension.substring(0, removeExtension.lastIndexOf(".")); + String activePolicy = policyName + "." + activeVersion + ".xml"; + File file = new File(Paths.get(REPOSITORY_BASE_PATH, activePolicy).toString()); + if(!file.exists()){ + return error("The Policy is Not Existing in Workspace"); + }else{ + if(policyName.contains("/")){ + policyName = policyName.replace("/", File.separator); + } + policyName = policyName.substring(policyName.indexOf(File.separator)+1); + if(policyName.contains("\\")){ + policyName = policyName.replace(File.separator, "\\"); + } + String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='" +policyName+"' and id >0"; + //query the database + PolicyController.updatePolicyVersion(query); + //Policy Notification + PolicyController controller = new PolicyController(); + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(policyName); + entity.setActiveVersion(Integer.parseInt(activeVersion)); + entity.setModifiedBy(userId); + controller.WatchPolicyFunction(entity, policyName, "SwitchVersion"); + } + } + } + File policyFile = new File(REPOSITORY_BASE_PATH, path); + PolicyController policyController = new PolicyController(); + return policyController.SwitchVersionPolicyContent(policyFile); + } + + //Describe Policy + private JSONObject describePolicy(JSONObject params){ + String path = params.getString("path"); + File policyFile = new File(REPOSITORY_BASE_PATH, path); + + return HumanPolicyComponent.DescribePolicy(policyFile); + } + + //Get the List of Policies and Scopes for Showing in Editor tab + private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException { + Set<String> scopes = null; + List<String> roles = null; + try { + //Get the Login Id of the User from Request + String userId = UserUtils.getUserIdFromCookie(request); + //Check if the Role and Scope Size are Null get the values from db. + List<Roles> userRoles = PolicyController.getRoles(userId); + roles = new ArrayList<String>(); + scopes = new HashSet<String>(); + for(Roles userRole: userRoles){ + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + scopes.add(userRole.getScope()); + } + } + } + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { + if(scopes.isEmpty()){ + return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); + } + } + + List<JSONObject> resultList = new ArrayList<JSONObject>(); + SimpleDateFormat dt = new SimpleDateFormat(DATE_FORMAT); + boolean onlyFolders = params.getBoolean("onlyFolders"); + String path = params.getString("path"); + if(path.contains("..xml")){ + path = path.replaceAll("..xml", "").trim(); + } + + + if("/".equals(path)){ + if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ + try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(REPOSITORY_BASE_PATH, path))) { + for (Path pathObj : directoryStream) { + BasicFileAttributes attrs = Files.readAttributes(pathObj, BasicFileAttributes.class); + if (onlyFolders && !attrs.isDirectory()) { + continue; + } + JSONObject el = new JSONObject(); + String fileName = pathObj.getFileName().toString(); + if (!(fileName.equals(".DS_Store") || fileName.contains(".git"))) { + if(!fileName.endsWith(".xml")){ + el.put("name", fileName); + el.put("date", dt.format(new Date(attrs.lastModifiedTime().toMillis()))); + el.put("size", attrs.size()); + el.put("type", attrs.isDirectory() ? "dir" : "file"); + resultList.add(el); + } + } + } + } catch (IOException ex) { + LOG.error("Error Occured While reading Policy Files List"+ex ); + } + }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){ + for(Object scope : scopes){ + JSONObject el = new JSONObject(); + Path filePath = Paths.get(REPOSITORY_BASE_PATH + File.separator + scope); + if(Files.exists(filePath)){ + el.put("name", scope); + el.put("date", dt.format(filePath.toFile().lastModified())); + el.put("size", ""); + el.put("type", "dir"); + resultList.add(el); + } + } + } + }else{ + try{ + String scopeName = path.substring(path.indexOf("/") +1); + activePolicyList(scopeName, resultList, roles, scopes, onlyFolders); + } catch (Exception ex) { + LOG.error("Error Occured While reading Policy Files List"+ex ); + } + } + + return new JSONObject().put(RESULT, resultList); + } catch (Exception e) { + LOG.error("list", e); + return error(e.getMessage()); + } + } + + //Get Active Policy List based on Scope Selection form Policy Version table + private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){ + if(scopeName.contains("/")){ + scopeName = scopeName.replace("/", File.separator); + } + if(scopeName.contains("\\")){ + scopeName = scopeName.replace("\\", "\\\\\\\\"); + } + String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'"; + String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'"; + List<PolicyVersion> activePolicies = PolicyController.getListOfActivePolicies(query); + List<PolicyEditorScopes> scopesList = PolicyController.getListOfPolicyEditorScopes(scopeNamequery); + for(PolicyEditorScopes scopeById : scopesList){ + String scope = scopeById.getScopeName(); + if(scope.contains(File.separator)){ + String checkScope = scope.substring(0, scope.lastIndexOf(File.separator)); + if(scopeName.contains("\\\\")){ + scopeName = scopeName.replace("\\\\", File.separator); + } + if(scopeName.equalsIgnoreCase(checkScope)){ + JSONObject el = new JSONObject(); + Path filePath = Paths.get(REPOSITORY_BASE_PATH + File.separator + scope); + if(Files.exists(filePath)){ + el.put("name", filePath.getFileName()); + el.put("date", scopeById.getModifiedDate()); + el.put("size", ""); + el.put("type", "dir"); + el.put("createdBy", scopeById.getUserCreatedBy().getUserName()); + el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName()); + resultList.add(el); + } + } + } + } + for (PolicyVersion policy : activePolicies) { + String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator)); + String activepath = REPOSITORY_BASE_PATH + File.separator + policy.getPolicyName() + "." + policy.getActiveVersion() + ".xml"; + Path pathObj = Paths.get(activepath); + if(Files.exists(pathObj)){ + BasicFileAttributes attrs; + try { + attrs = Files.readAttributes(pathObj, BasicFileAttributes.class); + if (onlyFolders && !attrs.isDirectory()) { + continue; + } + if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ + readPolicies(pathObj, attrs, scopeName, resultList); + }else if(!scopes.isEmpty()){ + for(String value : scopes){ + if(scopeNameValue.startsWith(value)){ + readPolicies(pathObj, attrs, scopeName, resultList); + } + } + } + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception occured while reading File Attributes"+e); + } + } + } + } + + //Read the Policy File to get Created by and Modified by User Name of Policy + public void readPolicies(Path pathObj, BasicFileAttributes attrs, String scopeName, List<JSONObject> resultList){ + JSONObject el = new JSONObject(); + String policyName = ""; + String version = ""; + String scope = ""; + if(scopeName.contains("\\\\")){ + scopeName = scopeName.replace("\\\\", File.separator); + } + SimpleDateFormat dt = new SimpleDateFormat(DATE_FORMAT); + String fileName = pathObj.getFileName().toString(); + if (!(fileName.equals(".DS_Store") || fileName.startsWith(".git"))) { + if(fileName.endsWith(".xml")){ + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + //Query the database + String parent = pathObj.toString().substring(pathObj.toString().indexOf(REPOSITORY)+ 11); + parent = FilenameUtils.removeExtension(parent); + version = parent.substring(parent.indexOf(".")+1); + policyName = parent.substring(0, parent.lastIndexOf(".")); + scope = policyName.substring(0, policyName.lastIndexOf(File.separator)); + if(policyName.contains("\\")){ + policyName = scope + "\\" + policyName.substring(policyName.lastIndexOf("\\")); + } + } + if(scopeName.equalsIgnoreCase(scope)){ + el.put("name", fileName); + if(pathObj.toFile().toString().endsWith(".xml")){ + el.put("version", version); + List<String> createdByModifiedBy; + try { + createdByModifiedBy = XACMLPolicyScanner.getCreatedByModifiedBy(pathObj); + } catch (IOException e) { + LOG.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while Reading the Policy File" + pathObj.toString() + e.getMessage()); + createdByModifiedBy = Arrays.asList("", ""); + } + el.put("createdBy", getUserName(createdByModifiedBy.get(0))); + el.put("modifiedBy", getUserName(createdByModifiedBy.get(1))); + } + el.put("date", dt.format(new Date(attrs.lastModifiedTime().toMillis()))); + el.put("size", attrs.size()); + el.put("type", attrs.isDirectory() ? "dir" : "file"); + } + } + + if(!el.keySet().isEmpty()){ + resultList.add(el); + } + + } + + //Get the User Name based on ID from User Info table + public String getUserName(String userId) { + String userName = "super-admin"; + if("".equals(userId)){ + return userName; + } + try{ + return PolicyController.getUserName(userId); + }catch(Exception e){ + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Retriving User Name from User Info table"+e); + return userName; + } + } + + //Rename Policy + private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException { + try { + String userId = null; + try { + userId = UserUtils.getUserIdFromCookie(request); + } catch (Exception e) { + LOG.error("Exception Occured while reading userid from cookie" +e); + } + String path = params.getString("path"); + String newpath = params.getString("newPath"); + LOG.debug("rename from: {} to:Â {}" +path + newpath); + + File srcFile = new File(REPOSITORY_BASE_PATH, path); + File destFile = new File(REPOSITORY_BASE_PATH, newpath); + if (srcFile.isFile()) { + renameXMLandConfig(destFile.getPath().toString(), srcFile.getPath().toString(), userId); + } else { + FileUtils.moveDirectory(srcFile, destFile); + String oldScopeName = path.substring(1).replace("/", File.separator); + String newScopeName = newpath.substring(1).replace("/", File.separator); + String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +oldScopeName.replace("\\", "\\\\\\\\")+"%'"; + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + List<PolicyEditorScopes> scopesList = PolicyController.getListOfPolicyEditorScopes(scopeNamequery); + for(PolicyEditorScopes scopes : scopesList){ + String scope = scopes.getScopeName(); + String newScope = scope.replace(oldScopeName, newScopeName); + scopes.setScopeName(newScope); + scopes.setUserModifiedBy(userInfo); + PolicyController.updatePolicyScopeEditor(scopes); + } + File[] list = destFile.listFiles(); + if(list.length > 0){ + renameXMLandConfig(destFile.getPath().toString(), srcFile.getPath().toString(), userId); + } + } + return success(); + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); + return error(e.getMessage()); + } + } + + //rename the xml and config files when renaming scope + public void renameXMLandConfig(String newPath, String oldPath, String loginId){ + if(!newPath.endsWith(".xml")){ + File dir = new File(newPath); + File[] listOfFiles = dir.listFiles(); + for(File file : listOfFiles){ + if(file.toString().endsWith(".xml")){ + renameFile(file, oldPath, newPath ); + }else if(file.isDirectory()){ + String oldFilePath = oldPath + File.separator +file.getName(); + renameXMLandConfig(file.toString(), oldFilePath, loginId); + } + } + }else{ + Path parent = Paths.get(oldPath.toString().substring(0, oldPath.toString().lastIndexOf(File.separator))); + String policyName = oldPath.toString().substring(oldPath.toString().indexOf(REPOSITORY) +11); + String removeExtension = policyName.replace(".xml", ""); + String dbPolicyName = removeExtension.substring(0, removeExtension.lastIndexOf(".")); + //Policy Notifcation + PolicyController controller = new PolicyController(); + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(dbPolicyName); + entity.setModifiedBy(loginId); + controller.WatchPolicyFunction(entity, dbPolicyName, "Rename"); + String filterPolicyName = dbPolicyName.substring(dbPolicyName.lastIndexOf(File.separator)+1); + FileFilter fileFilter = new WildcardFileFilter(filterPolicyName + "." + "*" + ".xml"); + File[] files = parent.toFile().listFiles(fileFilter); + for(File file : files){ + String removeNewPathExtension = newPath.replace(".xml", ""); + String removeNewFileVersion = removeNewPathExtension.substring(0, removeNewPathExtension.lastIndexOf(".")); + String oldFile = file.getPath(); + oldFile = oldFile.replace(".xml", ""); + String version = oldFile.substring(oldFile.lastIndexOf(".")+1); + String finalPath = removeNewFileVersion + "." + version + ".xml"; + File destFile = new File(finalPath); + try { + FileUtils.moveFile(file, destFile); + renameFile(file, oldFile, finalPath); + } catch (IOException e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming or Moving Policy"+e); + } + + } + } + } + + //Rename File + private void renameFile(File file, String oldPath, String newPath){ + if(file.toString().contains(CONFIG) || file.toString().contains(ACTION) || file.toString().contains(DECISION)){ + File xmlFileName = new File(newPath); + String oldfileWithExtension = null; + String filelocation = null; + String oldfile = null; + String newfile = null; + String extension = null; + if(newPath.endsWith(".xml")){ + extension = XACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(xmlFileName.toPath()); + }else{ + extension = XACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(file.toPath()); + String fileName = file.getName(); + oldPath = oldPath + File.separator + fileName; + newPath = newPath + File.separator + fileName; + } + + try{ + if(file.toString().contains(CONFIG)){ + filelocation = PolicyController.getConfigHome(); + } + if(file.toString().contains(ACTION)){ + filelocation = PolicyController.getActionHome(); + } + File oldFilePath = new File(oldPath); + String oldFileName = oldFilePath.getName().replace(".xml", ""); + File newFilePath = new File(newPath); + String newFileName = newFilePath.getName().replace(".xml", ""); + File target = new File(oldPath); + File newParentScope = new File(newPath); + if(newParentScope.toString().endsWith(".xml")){ + String newScope = newParentScope.toString().substring(0, newParentScope.toString().lastIndexOf(File.separator)); + newParentScope = new File(newScope); + } + String oldParentScope = target.toString().substring(0, target.toString().lastIndexOf(File.separator)); + String oldDomain = oldParentScope.toString().substring(oldParentScope.toString().indexOf(REPOSITORY) + 11); + if(oldDomain.endsWith(".xml")){ + oldDomain = oldDomain.substring(0, oldDomain.lastIndexOf(File.separator)); + } + oldfile = oldDomain + File.separator + oldFileName.substring(0, oldFileName.indexOf(".")); + if(oldDomain.contains(File.separator)){ + oldDomain = oldDomain.replace(File.separator, "."); + } + String newDomain = newParentScope.toString().substring(newParentScope.toString().indexOf(REPOSITORY) + 11); + newfile = newDomain + File.separator +newFileName.substring(0, newFileName.indexOf(".")); + if(newDomain.contains(File.separator)){ + newDomain = newDomain.replace(File.separator, "."); + } + if(file.toString().contains(CONFIG) || file.toString().contains(ACTION)){ + oldfileWithExtension = oldDomain + "." + oldFileName + "."+ extension; + String newfilewithExtension = newDomain + "." + newFileName + "." + extension; + File file1 = new File(filelocation, oldfileWithExtension); + file1.renameTo(new File(filelocation , newfilewithExtension)); + } + String query = "update PolicyVersion set policy_name='"+newfile.replace("\\", "\\\\")+"' where policy_name ='" +oldfile.replace("\\", "\\\\")+"' and id >0"; + //query the database + PolicyController.updatePolicyVersion(query); + }catch(Exception e){ + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Config file cannot found:" + oldfileWithExtension + e); + } + } + } + + //Clone the Policy + private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException { + try { + String path = params.getString("path"); + String newpath = params.getString("newPath"); + LOG.debug("copy from: {} to:Â {}" + path +newpath); + File srcFile = new File(REPOSITORY_BASE_PATH, path); + File destFile = new File(REPOSITORY_BASE_PATH, newpath); + if (srcFile.isFile()) { + FileUtils.copyFile(srcFile, destFile); + cloneXMLandConfig(destFile, srcFile, request); + } else { + FileUtils.copyDirectory(srcFile, destFile); + } + return success(); + } catch (Exception e) { + LOG.error("copy", e); + return error(e.getMessage()); + } + } + + public void cloneXMLandConfig(File newPath, File oldPath, HttpServletRequest request){ + String userId = null; + try { + userId = UserUtils.getUserIdFromCookie(request); + } catch (Exception e) { + LOG.error("Exception Occured while reading userid from cookie" +e); + } + String newPolicyName = newPath.getPath().toString().substring(newPath.getPath().toString().indexOf(REPOSITORY) + 11); + newPolicyName = newPolicyName.replace(".xml", ""); + String version = newPolicyName.substring(newPolicyName.lastIndexOf(".") +1); + String policyName = newPolicyName.substring(0, newPolicyName.indexOf(".")); + newPolicyName = newPolicyName.replace(File.separator, "."); + //if the user leaves the name of the policy blank + if (newPolicyName == null) { + return; + }else{ + Path newPolicyPath = newPath.toPath(); + File dir = null; + File[] listOfFiles = null; + if(newPolicyName.contains(CONFIG)){ + LOG.debug("CONFIG_HOME: "+CONFIG_HOME); + dir=new File(CONFIG_HOME); + listOfFiles = dir.listFiles(); + }else if(newPolicyName.contains(ACTION)){ + LOG.debug("ACTION_HOME: "+ACTION_HOME); + dir=new File(ACTION_HOME); + listOfFiles = dir.listFiles(); + } + String indexValue = ""; + String orignalPolicyName = oldPath.getPath().toString().substring(oldPath.getPath().toString().indexOf(REPOSITORY) + 11); + orignalPolicyName = orignalPolicyName.replace(".xml", ""); + orignalPolicyName = orignalPolicyName.replace(File.separator, "."); + if(orignalPolicyName.contains("Config_Fault_")){ + indexValue = "Config_Fault_"; + } else if(orignalPolicyName.contains("Config_PM_")){ + indexValue = "Config_PM_"; + }else if(orignalPolicyName.contains("Config_FW")){ + indexValue = "Config_FW_"; + }else if(orignalPolicyName.contains("Config_BRMS_Param")){ + indexValue = "Config_BRMS_Param_"; + }else if(orignalPolicyName.contains("Config_BRMS_Raw")){ + indexValue = "Config_BRMS_Raw_"; + } else if(orignalPolicyName.contains("Config_MS")){ + indexValue = "Config_MS_"; + }else if(orignalPolicyName.contains(ACTION)){ + indexValue = ACTION; + }else if(orignalPolicyName.contains(DECISION)){ + indexValue = DECISION; + }else{ + indexValue = CONFIG; + } + File newConfigFile = null; + + //making changes to the xml file + if(indexValue.contains(CONFIG) || indexValue.contains(ACTION)){ + for (File file : listOfFiles) { + if (file.isFile()){ + String fileName=file.getName(); + if(fileName.contains(orignalPolicyName)){ + String newConfigFileName=fileName.replaceAll(orignalPolicyName,newPolicyName); + if(dir.toString().contains(File.separator)){ + newConfigFile=new File(dir.toString()+ File.separator +newConfigFileName); + } + try { + Files.copy(file.toPath(), newConfigFile.toPath()); + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while Cloning the config file" + e); + return; + } + } + } + } + XACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(newPolicyPath); + } + //set the clone policy name into policy version database table + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(Integer.parseInt(version)); + entityItem.setHigherVersion(Integer.parseInt(version)); + entityItem.setPolicyName(policyName); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + PolicyController.SaveToPolicyVersion(entityItem); + + + new Thread(new Runnable() { + @Override + public void run() { + try { + ElkConnector.singleton.update(newPolicyPath.toFile()); + if (LOG.isInfoEnabled()) { + LOG.info("ELK cloning to " + newPolicyPath); + } + } catch (Exception e) { + LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": Internal Error: Unsucessful clone: " + e.getMessage(), e); + } + } + }).start(); + + //send to pap + XACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(newPolicyPath.toAbsolutePath().toString()); + LOG.info("Cloned policy "+newPolicyName+" created successfully."); + return; + } + } + + //Delete Policy or Scope Functionality + private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException { + try { + String userId = UserUtils.getUserIdFromCookie(request); + String deleteVersion = ""; + String path1 = params.getString("path"); + LOG.debug("delete {}" +path1); + if(params.has("deleteVersion")){ + deleteVersion = params.getString("deleteVersion"); + } + + this.repofilePath = new File(REPOSITORY_BASE_PATH, path1); + File policyFile = new File(REPOSITORY_BASE_PATH, path1); + if("ALL".equals(deleteVersion)){ + String removexmlExtension = policyFile.toString().substring(0, policyFile.toString().lastIndexOf(".")); + String removeVersion = removexmlExtension.substring(0, removexmlExtension.lastIndexOf(".")); + String notificationName = removeVersion.substring(removeVersion.lastIndexOf(REPOSITORY)+11); + //Policy Notifcation + PolicyController controller = new PolicyController(); + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(notificationName); + entity.setModifiedBy(userId); + controller.WatchPolicyFunction(entity, notificationName, "DeleteAll"); + File dirXML = new File(policyFile.getParent()); + File[] listOfXMLFiles = dirXML.listFiles(); + for (File file : listOfXMLFiles) { + //delete the xml files from Repository + if (file.isFile() && file.toString().contains(removeVersion)) { + if(XACMLPolicyWriterWithPapNotify.notifyPapOfDelete(file.toString())){ + LOG.info("Policy deleted from database. Continuing with file delete"); + } else { + LOG.error("Failed to delete Policy from database. Aborting file delete"); + } + //Elk Update + updateElkOnPolicyDelete(file); + + if (file.delete()) { + if (LOG.isDebugEnabled()) { + LOG.debug("Deleted file: " + file.toString()); + } + } else { + LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file in specified location: " + file.getAbsolutePath()); + } + + // Get tomcat home directory for deleting config data + String path = getParentPathSubScopeDir(); + path = path.replace('\\', '.'); + if(path.contains("/")){ + path = path.replace('/', '.'); + } + String fileName = FilenameUtils.removeExtension(file.getName()); + String removeVersionInFileName = fileName.substring(0, fileName.lastIndexOf(".")); + String fileLocation = null; + if (fileName != null && fileName.contains(CONFIG)) { + fileLocation = CONFIG_HOME; + } else if (fileName != null && fileName.contains(ACTION)) { + fileLocation = ACTION_HOME; + } + if (LOG.isDebugEnabled()) { + LOG.debug("Attempting to rename file from the location: "+ fileLocation); + } + if(!file.toString().contains(DECISION)){ + // Get the file from the saved location + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + + for (File file1 : listOfFiles) { + if (file1.isFile() && file1.getName().contains( path + removeVersionInFileName)) { + try { + if (file1.delete() == false) { + throw new Exception("No known error, Delete failed"); + } + } catch (Exception e) { + LOG.error("Failed to Delete file: "+ e.getLocalizedMessage()); + } + } + } + } + + //Delete the Policy from Database Policy Version table + String removeExtension = removeVersion.substring(removeVersion.indexOf(REPOSITORY)+11); + String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +removeExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + PolicyController.updatePolicyVersion(policyVersionQuery); + } + } + } + //If Only Particular version to be deleted + }else if("CURRENT".equals(deleteVersion)){ + String removexmlExtension = policyFile.toString().substring(0, policyFile.toString().lastIndexOf(".")); + String getVersion = removexmlExtension.substring(removexmlExtension.indexOf(".")+1); + String removeVersion = removexmlExtension.substring(0, removexmlExtension.lastIndexOf(".")); + String notificationName = removeVersion.substring(removeVersion.lastIndexOf(REPOSITORY)+11); + //Policy Notifcation + PolicyController controller = new PolicyController(); + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(notificationName); + entity.setActiveVersion(Integer.parseInt(getVersion)); + entity.setModifiedBy(userId); + controller.WatchPolicyFunction(entity, notificationName, "DeleteOne"); + if(XACMLPolicyWriterWithPapNotify.notifyPapOfDelete(policyFile.toString())){ + LOG.info("Policy deleted from database. Continuing with file delete"); + } else { + LOG.error("Failed to delete Policy from database. Aborting file delete"); + } + //Elk Update + updateElkOnPolicyDelete(policyFile); + + if (policyFile.delete()) { + LOG.debug("Deleted file: " + policyFile.toString()); + } else { + LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file in specified location: " +policyFile.getAbsolutePath()); + } + + // Get tomcat home directory for storing action body config data + String path = getParentPathSubScopeDir(); + path = path.replace('\\', '.'); + if(path.contains("/")){ + path = path.replace('/', '.'); + LOG.info("print the path:" +path); + } + final String tempPath = path; + String fileName = FilenameUtils.removeExtension(policyFile.getName()); + String fileLocation = null; + if (fileName != null && fileName.contains(CONFIG)) { + fileLocation = CONFIG_HOME; + } else if (fileName != null && fileName.contains(ACTION)) { + fileLocation = ACTION_HOME; + } + if (LOG.isDebugEnabled()) { + LOG.debug("Attempting to delete file from the location: "+ fileLocation); + } + if(!policyFile.toString().contains(DECISION)){ + // Get the file from the saved location + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + + for (File file : listOfFiles) { + if (file.isFile() && file.toString().contains( tempPath + fileName)) { + try { + if (file.delete() == false) { + throw new Exception("No known error, Delete failed"); + } + } catch (Exception e) { + LOG.error("Failed to Delete file: "+ e.getLocalizedMessage()); + } + } + } + } + //Delete the Policy from Database and set Active Version based on the deleted file. + int highestVersion = 0; + String removeExtension = removeVersion.substring(removeVersion.indexOf(REPOSITORY)+11); + PolicyVersion policyVersionEntity = PolicyController.getPolicyEntityFromPolicyVersion(removeExtension); + if(policyVersionEntity != null){ + highestVersion = policyVersionEntity.getHigherVersion(); + } + int i =0; + int version = Integer.parseInt(getVersion); + if(version == highestVersion){ + for(i = highestVersion; i >= 1 ; i--){ + highestVersion = highestVersion-1; + path = removeVersion + "."+ highestVersion +".xml"; + File file = new File(path); + if(file.exists()){ + break; + } + } + } + String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +removeExtension.replace("\\", "\\\\")+"'"; + PolicyController.updatePolicyVersion(updatequery); + }else{ + String scopeName = policyFile.getAbsolutePath().substring(policyFile.getAbsolutePath().indexOf(REPOSITORY)+11); + String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+scopeName.replace("\\", "\\\\")+"%' and id >0"; + String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+scopeName.replace("\\", "\\\\")+"%' and id >0"; + PolicyController.updatePolicyVersion(policyVersionQuery); + PolicyController.updatePolicyScopeEditorWithQuery(policyScopeQuery); + delete(policyFile); + //Policy Notifcation + PolicyController controller = new PolicyController(); + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(scopeName); + entity.setModifiedBy(userId); + controller.WatchPolicyFunction(entity, scopeName, "DeleteScope"); + } + return success(); + } catch (Exception e) { + LOG.error("delete", e); + return error(e.getMessage()); + } + } + + //Notify ELK on File Delete + private void updateElkOnPolicyDelete(File file){ + try { + ElkConnector.singleton.delete(file); + } catch (Exception e) { + LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": Cannot delete: " + file.getName() + + " at " + file.getAbsolutePath() + ": " + e.getMessage(), e); + } + } + //Deletes Files when Scope is Selected to delete + public void delete(File file) throws IOException{ + if(file.isDirectory()){ + //directory is empty, then delete it + if(file.list().length==0){ + file.delete(); + }else{ + //list all the directory contents + String[] files = file.list(); + for (String temp : files) { + //construct the file structure + File fileDelete = new File(file, temp); + //delete from Elk first + if(fileDelete.getAbsolutePath().toString().endsWith(".xml")){ + try { + String deleteFile= fileDelete.getAbsoluteFile().toString().substring(fileDelete.getAbsoluteFile().toString().indexOf("workspace")); + File deletePath= new File(deleteFile); + LOG.debug("Search:"+deletePath); + ElkConnector.singleton.delete(deletePath); + } catch (Exception e) { + LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": Cannot delete: " + fileDelete.getAbsoluteFile().getName() + + " at " + fileDelete.getAbsoluteFile().getAbsolutePath() + ": " +e.getMessage(), e); + } + } + + //recursive delete + delete(fileDelete); + + //Delete the Configuration files from Config and Action Home Location + String fileLocation = null; + String policyName = fileDelete.toString().substring(fileDelete.toString().indexOf(REPOSITORY)+11, fileDelete.toString().lastIndexOf(".")); + if(policyName.contains(CONFIG)){ + fileLocation = PolicyController.getConfigHome(); + } + if(policyName.contains(ACTION)){ + fileLocation = PolicyController.getActionHome(); + } + if(policyName.contains(File.separator)){ + policyName = policyName.replace(File.separator, "."); + } + if(!fileDelete.toString().contains(DECISION) && fileLocation != null){ + // Get the file from the saved location and delete + File dir = new File(fileLocation); + FileFilter fileFilter = new WildcardFileFilter(policyName + ".*"); + File[] configFiles = (dir).listFiles(fileFilter); + if(configFiles.length > 0){ + configFiles[0].delete(); + } + } + //Notify the PAP and Elk database for deleting the Policies Under Scopes + if(fileDelete.getAbsolutePath().toString().endsWith(".xml")){ + if(!XACMLPolicyWriterWithPapNotify.notifyPapOfDelete(fileDelete.getAbsolutePath().toString())){ + LOG.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Could not delete the policy from the database: "+ + fileDelete.getAbsolutePath().toString()); + throw new IOException("Could not delete the policy from the database: "+ + fileDelete.getAbsolutePath().toString()); + } + } + } + //check the directory again, if empty then delete it + if(file.list().length==0){ + file.delete(); + } + } + }else{ + //if file, then delete it + file.delete(); + } + } + + //Get the Parent Scope of File + protected String getParentPathSubScopeDir() { + String domain1 = null; + final Path gitPath = PolicyController.getGitPath(); + String policyDir = this.repofilePath.getAbsolutePath(); + int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1; + policyDir = policyDir.substring(startIndex, policyDir.length()); + if(policyDir.contains(CONFIG)){ + domain1 = policyDir.substring(0,policyDir.indexOf(CONFIG)); + }else if(policyDir.contains(ACTION)){ + domain1 = policyDir.substring(0,policyDir.indexOf(ACTION)); + }else{ + domain1 = policyDir.substring(0,policyDir.indexOf(DECISION)); + } + LOG.info("print the main domain value"+policyDir); + return domain1; + } + + //Edit the Policy + private JSONObject editFile(JSONObject params) throws ServletException { + // get content + try { + String mode = params.getString("mode"); + String path = params.getString("path"); + LOG.debug("editFile path: {}"+ path); + + File policyFile = new File(REPOSITORY_BASE_PATH, path); + + Object policy = XACMLPolicyScanner.readPolicy(new FileInputStream(policyFile)); + Path fullPath = Paths.get(policyFile.getAbsolutePath(), new String[0]); + PolicyAdapter policyAdapter = new PolicyAdapter(); + policyAdapter.setData(policy); + String dirPath = fullPath.getParent().toString().substring(fullPath.getParent().toString().lastIndexOf(REPOSITORY)+11); + policyAdapter.setDirPath(dirPath); + policyAdapter.setParentPath(fullPath.getParent()); + + if("viewPolicy".equalsIgnoreCase(mode)){ + policyAdapter.setReadOnly(true); + policyAdapter.setEditPolicy(false); + }else{ + policyAdapter.setReadOnly(false); + policyAdapter.setEditPolicy(true); + } + + policyAdapter.setPolicyData(policy); + policyAdapter.setPolicyName(FilenameUtils.removeExtension(policyFile.getName())); + + String policyNameValue = null ; + String configPolicyName = null ; + if(policyAdapter.getPolicyName().startsWith("Config_PM")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "ClosedLoop_PM"; + }else if(policyAdapter.getPolicyName().startsWith("Config_Fault")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "ClosedLoop_Fault"; + }else if(policyAdapter.getPolicyName().startsWith("Config_FW")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "Firewall Config"; + }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "BRMS_Raw"; + }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "BRMS_Param"; + }else if(policyAdapter.getPolicyName().startsWith("Config_MS")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "DCAE Micro Service"; + }else if(policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName().startsWith("Decision") ){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + } + else{ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "Base"; + } + if (policyNameValue != null) { + policyAdapter.setPolicyType(policyNameValue); + } + if (configPolicyName != null) { + policyAdapter.setConfigPolicyType(configPolicyName); + } + + if("Action".equalsIgnoreCase(policyAdapter.getPolicyType())){ + ActionPolicyController actionController = new ActionPolicyController(); + actionController.PrePopulateActionPolicyData(policyAdapter); + } + if("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())){ + DecisionPolicyController decisionController = new DecisionPolicyController(); + decisionController.PrePopulateDecisionPolicyData(policyAdapter); + } + if("Config".equalsIgnoreCase(policyAdapter.getPolicyType())){ + if("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreatePolicyController baseController = new CreatePolicyController(); + baseController.PrePopulateBaseConfigPolicyData(policyAdapter); + } + else if("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateBRMSRawController brmsController = new CreateBRMSRawController(); + brmsController.PrePopulateBRMSRawPolicyData(policyAdapter); + } + else if("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateBRMSParamController paramController = new CreateBRMSParamController(); + paramController.PrePopulateBRMSParamPolicyData(policyAdapter); + } + else if("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateClosedLoopFaultController newFaultTemplate = new CreateClosedLoopFaultController(); + newFaultTemplate.PrePopulateClosedLoopFaultPolicyData(policyAdapter); + } + else if("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateClosedLoopPMController pmController = new CreateClosedLoopPMController(); + pmController.PrePopulateClosedLoopPMPolicyData(policyAdapter); + } + else if("DCAE Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); + msController.PrePopulateDCAEMSPolicyData(policyAdapter); + } + else if("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateFirewallController firewallController = new CreateFirewallController(); + firewallController.PrePopulateFWPolicyData(policyAdapter); + } + } + + + policyAdapter.setParentPath(null); + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(policyAdapter); + JsonNode jsonNode = mapper.readTree(json); + + return new JSONObject().put(RESULT, jsonNode); + } catch (Exception e) { + LOG.error("editFile", e); + return error(e.getMessage()); + } + } + + //Add Scopes + private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException { + String name = ""; + + try { + String userId = UserUtils.getUserIdFromCookie(request); + String path = params.getString("path"); + try{ + if(params.has("subScopename")){ + if(!params.getString("subScopename").equals("")){ + name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename"); + } + }else{ + name = params.getString("name"); + } + }catch(Exception e){ + name = params.getString("name"); + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e); + } + + + LOG.debug("addFolder path: {} name: {}" + path +name); + File newDir = new File(REPOSITORY_BASE_PATH, name); + if(!newDir.exists()){ + if (!newDir.mkdir()) { + throw new Exception("Can't create directory: " + newDir.getAbsolutePath()); + } + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + PolicyEditorScopes newScope = new PolicyEditorScopes(); + String scopeName = null; + if(name.startsWith(File.separator)){ + scopeName = name.substring(1); + }else{ + scopeName = name; + } + newScope.setScopeName(scopeName); + newScope.setUserCreatedBy(userInfo); + newScope.setUserModifiedBy(userInfo); + PolicyController.SavePolicyScope(newScope); + }else{ + return error("Scope Already Exists"); + } + + return success(); + } catch (Exception e) { + LOG.error("addFolder", e); + return error(e.getMessage()); + } + } + + //Return Error Object + private JSONObject error(String msg) throws ServletException { + try { + JSONObject result = new JSONObject(); + result.put("success", false); + result.put("error", msg); + return new JSONObject().put(RESULT, result); + } catch (JSONException e) { + throw new ServletException(e); + } + } + + //Return Success Object + private JSONObject success() throws ServletException { + try { + JSONObject result = new JSONObject(); + result.put("success", true); + result.put("error", (Object) null); + return new JSONObject().put(RESULT, result); + } catch (JSONException e) { + throw new ServletException(e); + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java new file mode 100644 index 000000000..186adfa29 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java @@ -0,0 +1,140 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.admin; + +/* + * + * + * + * */ +import java.io.UnsupportedEncodingException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Properties; + +import javax.mail.MessagingException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.WatchPolicyNotificationTable; +import org.springframework.beans.factory.annotation.Configurable; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.springframework.mail.javamail.MimeMessageHelper; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Configurable +public class PolicyNotificationMail{ + private static Logger logger = FlexLogger.getLogger(PolicyNotificationMail.class); + + @Bean + public JavaMailSenderImpl javaMailSenderImpl(){ + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost(PolicyController.smtpHost); + mailSender.setPort(Integer.parseInt(PolicyController.smtpPort)); + mailSender.setUsername(PolicyController.smtpUsername); + mailSender.setPassword(PolicyController.smtpPassword); + Properties prop = mailSender.getJavaMailProperties(); + prop.put("mail.transport.protocol", "smtp"); + prop.put("mail.smtp.auth", "true"); + prop.put("mail.smtp.starttls.enable", "true"); + prop.put("mail.debug", "true"); + return mailSender; + } + + @SuppressWarnings("resource") + public void sendMail(PolicyVersion entityItem, String policyName, String mode, WatchPolicyNotificationDao policyNotificationDao) throws MessagingException { + String from = PolicyController.smtpUsername; + String to = ""; + String subject = ""; + String message = ""; + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + if(mode.equalsIgnoreCase("EditPolicy")){ + subject = "Policy has been Updated : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Updated" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Modified By : " +entityItem.getModifiedBy() + '\n' + "Modified Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("Rename")){ + subject = "Policy has been Renamed : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Renamed" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Renamed By : " +entityItem.getModifiedBy() + '\n' + "Renamed Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("DeleteAll")){ + subject = "Policy has been Deleted : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted with All Versions" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("DeleteOne")){ + subject = "Policy has been Deleted : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' +"Policy Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("DeleteScope")){ + subject = "Scope has been Deleted : "+entityItem.getPolicyName(); + message = "The Scope Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Scope Name : " + policyName + '\n' + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("SwitchVersion")){ + subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been SwitchedVersion" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Switched By : " +entityItem.getModifiedBy() + '\n' + "Switched Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("Move")){ + subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Moved to Other Scope" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Moved By : " +entityItem.getModifiedBy() + '\n' + "Moved Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + String policyFileName = entityItem.getPolicyName(); + List<WatchPolicyNotificationTable> watchList = policyNotificationDao.getListDataByPolicyName(policyFileName); + if(watchList.size() > 0){ + for(WatchPolicyNotificationTable list : watchList){ + to = list.getLoginIds()+"@"+PolicyController.smtpEmailExtension; + to = to.trim(); + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + ctx.register(PolicyNotificationMail.class); + ctx.refresh(); + JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class); + MimeMessage mimeMessage = mailSender.createMimeMessage(); + MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage); + try { + mailMsg.setFrom(new InternetAddress(from, "Policy Notification System")); + } catch (UnsupportedEncodingException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e); + } + mailMsg.setTo(to); + mailMsg.setSubject(subject); + mailMsg.setText(message); + mailSender.send(mimeMessage); + } + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java new file mode 100644 index 000000000..ecb610264 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java @@ -0,0 +1,732 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.admin; + + + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.io.IOUtils; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.rest.XACMLRestProperties; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDP; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; +import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; +import org.openecomp.policy.xacml.std.pap.StdPDP; +import org.openecomp.policy.xacml.std.pap.StdPDPGroup; +import org.openecomp.policy.xacml.std.pap.StdPDPItemSetChangeNotifier; +import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; +import org.openecomp.policy.xacml.std.pap.StdPDPStatus; +import com.att.research.xacml.api.pap.PAPEngine; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPGroup; +//import com.att.research.xacml.api.pap.PDP; +//import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.api.pap.PDPStatus; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.introspect.VisibilityChecker; +import com.fasterxml.jackson.databind.type.CollectionType; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +/** + * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet + * through a RESTful interface + * + * + */ +public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine { + private static final Logger logger = FlexLogger.getLogger(RESTfulPAPEngine.class); + + // + // URL of the PAP Servlet that this Admin Console talks to + // + private String papServletURLString; + + /** + * Set up link with PAP Servlet and get our initial set of Groups + * @throws Exception + */ + public RESTfulPAPEngine (String myURLString) throws PAPException, IOException { + // + // Get our URL to the PAP servlet + // + this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + if (this.papServletURLString == null || this.papServletURLString.length() == 0) { + String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. Admin Console cannot call PAP."; + logger.error(message); + throw new PAPException(message); + } + + // + // register this Admin Console with the PAP Servlet to get updates + // + Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); + if (newURL != null) { + // assume this was a re-direct and try again + logger.warn("Redirecting to '" + newURL + "'"); + this.papServletURLString = (String)newURL; + newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); + if (newURL != null) { + logger.error("Failed to redirect to " + this.papServletURLString); + throw new PAPException("Failed to register with PAP"); + } + } + } + + + // + // High-level commands used by the Admin Console code through the PAPEngine Interface + // + + @Override + public EcompPDPGroup getDefaultGroup() throws PAPException { + EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "default="); + return newGroup; + } + + @Override + public void SetDefaultGroup(EcompPDPGroup group) throws PAPException { + sendToPAP("POST", null, null, null, "groupId=" + group.getId(), "default=true"); + } + + @SuppressWarnings("unchecked") + @Override + public Set<EcompPDPGroup> getEcompPDPGroups() throws PAPException { + Set<EcompPDPGroup> newGroupSet; + newGroupSet = (Set<EcompPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, "groupId="); + return Collections.unmodifiableSet(newGroupSet); + } + + + @Override + public EcompPDPGroup getGroup(String id) throws PAPException { + EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=" + id); + return newGroup; + } + + @Override + public void newGroup(String name, String description) + throws PAPException, NullPointerException { + String escapedName = null; + String escapedDescription = null; + try { + escapedName = URLEncoder.encode(name, "UTF-8"); + escapedDescription = URLEncoder.encode(description, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new PAPException("Unable to send name or description to PAP: " + e.getMessage()); + } + + this.sendToPAP("POST", null, null, null, "groupId=", "groupName="+escapedName, "groupDescription=" + escapedDescription); + } + + + /** + * Update the configuration on the PAP for a single Group. + * + * @param group + * @return + * @throws PAPException + */ + public void updateGroup(EcompPDPGroup group) throws PAPException { + + try { + + // + // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP! + // + // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace. + // + + +// // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory. +// // This is not efficient since most of the policies will already exist there. +// // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any corrupted files on the PAP get refreshed. +// + + // now update the group object on the PAP + + sendToPAP("PUT", group, null, null, "groupId=" + group.getId()); + } catch (Exception e) { + String message = "Unable to PUT policy '" + group.getId() + "', e:" + e; + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + + @Override + public void removeGroup(EcompPDPGroup group, EcompPDPGroup newGroup) + throws PAPException, NullPointerException { + String moveToGroupString = null; + if (newGroup != null) { + moveToGroupString = "movePDPsToGroupId=" + newGroup.getId(); + } + sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), moveToGroupString); + } + + @Override + public EcompPDPGroup getPDPGroup(EcompPDP pdp) throws PAPException { + return getPDPGroup(pdp.getId()); + } + + + public EcompPDPGroup getPDPGroup(String pdpId) throws PAPException { + EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "pdpId=" + pdpId, "getPDPGroup="); + return newGroup; + } + + @Override + public EcompPDP getPDP(String pdpId) throws PAPException { + EcompPDP newPDP = (EcompPDP)sendToPAP("GET", null, null, StdPDP.class, "groupId=", "pdpId=" + pdpId); + return newPDP; + } + + @Override + public void newPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) throws PAPException, + NullPointerException { + StdPDP newPDP = new StdPDP(id, name, description, jmxport); + sendToPAP("PUT", newPDP, null, null, "groupId=" + group.getId(), "pdpId=" + id); + return; + } + + @Override + public void movePDP(EcompPDP pdp, EcompPDPGroup newGroup) throws PAPException { + sendToPAP("POST", null, null, null, "groupId=" + newGroup.getId(), "pdpId=" + pdp.getId()); + return; + } + + @Override + public void updatePDP(EcompPDP pdp) throws PAPException { + EcompPDPGroup group = getPDPGroup(pdp); + sendToPAP("PUT", pdp, null, null, "groupId=" + group.getId(), "pdpId=" + pdp.getId()); + return; + } + + @Override + public void removePDP(EcompPDP pdp) throws PAPException { + EcompPDPGroup group = getPDPGroup(pdp); + sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), "pdpId=" + pdp.getId()); + return; + } + + //Validate the Policy Data + public boolean validatePolicyRequest(PolicyAdapter policyAdapter, String policyType) throws PAPException { + Boolean isValidData = false; +/* StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getConfigName(), + policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getConfigBodyData(), policyAdapter.getPolicyID(), policyAdapter.getRuleID(), + policyAdapter.getRuleCombiningAlgId(), policyAdapter.getParentPath().toString(), policyAdapter.getGitPath().toString(), policyAdapter.getConfigType(), policyAdapter.isEditPolicy()); + */ + + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base"); + + //send JSON object to PAP + isValidData = (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType); + return isValidData; + } + + //create a new policy + @SuppressWarnings("unchecked") + public Map<String, String> createPolicyRequest(PolicyAdapter policyAdapter) throws PAPException { + Map<String, String> successMap = new HashMap<String, String>(); + StdPAPPolicy newPAPPolicy = null; + + if (policyAdapter.getPolicyType().equalsIgnoreCase("Config")) { + + if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Firewall Config")) { + + //create StdPAPPolicy object for Config Firewall Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getJsonBody(), + policyAdapter.getHighestVersion() ,policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Raw")) { + + //create StdPAPPolicy object for BRMS_Raw Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getRiskLevel(), + policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Param")) { + + //create StdPAPPolicy object for BRMS_Param Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getBRMSParamBody(), + policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + + else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Base")) { + + //create StdPAPPolicy object for Config Base Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getConfigName(), policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getConfigType(), + policyAdapter.getConfigBodyData(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(), + policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")) { + + //create StdPAPPolicy object for CloseLoop Fault Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getJsonBody(), policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), null, policyAdapter.isEditPolicy(), + policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(), + policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_PM")) { + + //create StdPAPPolicy object for CloseLoop PM Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getJsonBody(), policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), policyAdapter.getServiceType(), + policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), + policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("DCAE Micro Service")) { + + //create StdPAPPolicy object for DCAE Micro Service Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getConfigName(), policyAdapter.getServiceType(), policyAdapter.getUuid(), policyAdapter.getLocation(), + policyAdapter.getJsonBody(), policyAdapter.getPriority(), null, policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), + policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Action")) { + + //create StdPAPPolicy object for Action Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getDynamicRuleAlgorithmLabels(), policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), + policyAdapter.getDynamicRuleAlgorithmField2(), policyAdapter.getActionPerformer(), policyAdapter.getActionAttribute(), + policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion()); + + } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) { + + //create StdPAPPolicy object for Decision Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getRuleProvider(), + policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getDynamicSettingsMap(), policyAdapter.getDynamicRuleAlgorithmLabels(), + policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), policyAdapter.getDynamicRuleAlgorithmField2(), + policyAdapter.getDropDownMap(), policyAdapter.getDynamicVariableList(), policyAdapter.getDataTypeList(), policyAdapter.isEditPolicy(), + policyAdapter.getDomainDir(), policyAdapter.getHighestVersion()); + + } + + //send JSON object to PAP + successMap = (Map<String, String>) sendToPAP("PUT", newPAPPolicy, null, null, "operation=create", "apiflag=admin", "policyType=" + policyAdapter.getPolicyType()); + return successMap; + + + } + + //update an existing policy + @SuppressWarnings("unchecked") + public Map<String, String> updatePolicyRequest(PolicyAdapter policyAdapter) throws PAPException { + Map<String, String> successMap = new HashMap<String, String>(); + StdPAPPolicy newPAPPolicy = null; + + if (policyAdapter.getPolicyType().equalsIgnoreCase("Config")) { + + if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Firewall Config")) { + + //create StdPAPPolicy object for Firewall Config Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getConfigName(), + policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getPolicyID(), + policyAdapter.getRuleID(), policyAdapter.getVersion(), policyAdapter.getJsonBody(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), + policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Raw")) { + //create StdPAPPolicy object for BRMS_Raw Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getRiskLevel(), + policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Param")) { + //create StdPAPPolicy object for BRMS_Raw Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getBRMSParamBody(), + policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Base")) { + + //create StdPAPPolicy object for Config Base Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getConfigName(), + policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getConfigBodyData(), policyAdapter.getPolicyID(), policyAdapter.getRuleID(), + policyAdapter.getConfigType(), policyAdapter.isEditPolicy(), policyAdapter.getVersion(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), + policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")) { + + //create StdPAPPolicy object for CloseLoop Fault Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getJsonBody(), policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), null, policyAdapter.isEditPolicy(), + policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(), + policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_PM")) { + + //create StdPAPPolicy object for CloseLoop PM Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getJsonBody(), policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), policyAdapter.getServiceType(), + policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), + policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("DCAE Micro Service")) { + + //create StdPAPPolicy object for DCAE Micro Service Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getConfigName(), policyAdapter.getServiceType(), policyAdapter.getUuid(), policyAdapter.getLocation(), + policyAdapter.getJsonBody(), policyAdapter.getPriority(), null, policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(), + policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Action")) { + + //create StdPAPPolicy object for Action Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getDynamicRuleAlgorithmLabels(), policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), + policyAdapter.getDynamicRuleAlgorithmField2(), policyAdapter.getActionPerformer(), policyAdapter.getActionAttribute(), + policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion()); + + } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) { + + //create StdPAPPolicy object for Decision Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getRuleProvider(), + policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getDynamicSettingsMap(), policyAdapter.getDynamicRuleAlgorithmLabels(), + policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), policyAdapter.getDynamicRuleAlgorithmField2(), + policyAdapter.getDropDownMap(), policyAdapter.getDynamicVariableList(), policyAdapter.getDataTypeList(), policyAdapter.isEditPolicy(), + policyAdapter.getDomainDir(), policyAdapter.getHighestVersion()); + + } + + //send JSON object to PAP + successMap = (Map<String, String>) sendToPAP("PUT", newPAPPolicy, null, null, "operation=update", "apiflag=admin", "policyType=" + policyAdapter.getPolicyType()); + return successMap; + } + + @Override + public void publishPolicy(String id, String name, boolean isRoot, + InputStream policy, EcompPDPGroup group) throws PAPException { + + + // copy the (one) file into the target directory on the PAP servlet + copyFile(id, group, policy); + + // adjust the local copy of the group to include the new policy + PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name); + group.getPolicies().add(pdpPolicy); + + // tell the PAP servlet to include the policy in the configuration + updateGroup(group); + + return; + } + + + + /** + * Copy a single Policy file from the input stream to the PAP Servlet. + * Either this works (silently) or it throws an exception. + * + * @param policyId + * @param group + * @param policy + * @return + * @throws PAPException + */ + public void copyFile(String policyId, EcompPDPGroup group, InputStream policy) throws PAPException { + // send the policy file to the PAP Servlet + try { + sendToPAP("POST", policy, null, null, "groupId=" + group.getId(), "policyId="+policyId); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policyId + "', e:" + e; + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + + @Override + public void copyPolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException { + if (policy == null || group == null) { + throw new PAPException("Null input policy="+policy+" group="+group); + } + try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) { + copyFile(policy.getId(), group, is ); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e; + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + + + + @Override + public void removePolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException { + throw new PAPException("NOT IMPLEMENTED"); + + } + + + + /** + * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly + * to get detailed status info. + * + * @param pdp + * @return + * @throws PAPException + */ + + public PDPStatus getStatus(EcompPDP pdp) throws PAPException { + StdPDPStatus status = (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class); + return status; + } + + + + + // + // Internal Operations called by the PAPEngine Interface methods + // + + /** + * Send a request to the PAP Servlet and get the response. + * + * The content is either an InputStream to be copied to the Request OutputStream + * OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream. + * + * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller. + * + * @param method + * @param content - EITHER an InputStream OR an Object to be encoded in JSON + * @param collectionTypeClass + * @param responseContentClass + * @param parameters + * @return + * @throws Exception + */ + private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException { + HttpURLConnection connection = null; + String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + logger.info("User Id is " + papID); + String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + logger.info("Pass is: " + papPass); + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + logger.info("Encoding for the PAP is: " + encoding); + try { + String fullURL = papServletURLString; + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; + } + fullURL += "?" + queryString.substring(1); + } + + // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP + if (method.equals("GET") && (content instanceof EcompPDP) && responseContentClass == StdPDPStatus.class) { + // Adjust the url and properties appropriately + String pdpID =((EcompPDP)content).getId(); + fullURL = pdpID + "?type=Status"; + content = null; + if(CheckPDP.validateID(pdpID)){ + encoding = CheckPDP.getEncoding(pdpID); + } + } + + + URL url = new URL(fullURL); + + // + // Open up the connection + // + connection = (HttpURLConnection)url.openConnection(); + // + // Setup our method and headers + // + connection.setRequestMethod(method); +// connection.setRequestProperty("Accept", "text/x-java-properties"); +// connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setDoOutput(true); + connection.setDoInput(true); + + if (content != null) { + if (content instanceof InputStream) { + try { + // + // Send our current policy configuration + // + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy((InputStream)content, os); + if (logger.isDebugEnabled()) { + logger.debug("copied to output, bytes="+count); + } + } + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e); + throw e; + } + } else { + // The content is an object to be encoded in JSON + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(connection.getOutputStream(), content); + } + } + // + // Do the connect + // + connection.connect(); + if (connection.getResponseCode() == 204) { + logger.info("Success - no content."); + return null; + } else if (connection.getResponseCode() == 200) { + logger.info("Success. We have a return object."); + String isValidData = connection.getHeaderField("isValidData"); + String isSuccess = connection.getHeaderField("successMapKey"); + Map<String, String> successMap = new HashMap<String, String>(); + if (isValidData != null && isValidData.equalsIgnoreCase("true")){ + logger.info("Policy Data is valid."); + return true; + } else if (isValidData != null && isValidData.equalsIgnoreCase("false")) { + logger.info("Policy Data is invalid."); + return false; + } else if (isSuccess != null && isSuccess.equalsIgnoreCase("success")) { + logger.info("Policy Created Successfully!" ); + String finalPolicyPath = connection.getHeaderField("finalPolicyPath"); + successMap.put("success", finalPolicyPath); + return successMap; + } else if (isSuccess != null && isSuccess.equalsIgnoreCase("error")) { + logger.info("There was an error while creating the policy!"); + successMap.put("error", "error"); + return successMap; + } else { + // get the response content into a String + String json = null; + // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) + java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + logger.info("JSON response from PAP: " + json); + + // convert Object sent as JSON into local object + ObjectMapper mapper = new ObjectMapper(); + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + if (collectionTypeClass != null) { + // collection of objects expected + final CollectionType javaType = + mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass); + + Object objectFromJSON = mapper.readValue(json, javaType); + return objectFromJSON; + } else { + // single value object expected + Object objectFromJSON = mapper.readValue(json, responseContentClass); + return objectFromJSON; + } + } + + } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { + // redirection + String newURL = connection.getHeaderField("Location"); + if (newURL == null) { + logger.error("No Location header to redirect to when response code="+connection.getResponseCode()); + throw new IOException("No redirect Location header when response code="+connection.getResponseCode()); + } + int qIndex = newURL.indexOf("?"); + if (qIndex > 0) { + newURL = newURL.substring(0, qIndex); + } + logger.info("Redirect seen. Redirecting " + fullURL + " to " + newURL); + return newURL; + } else { + logger.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); + } + + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e); + throw new PAPException("Request/Response threw :" + e); + } finally { + // cleanup the connection + if (connection != null) { + try { + // For some reason trying to get the inputStream from the connection + // throws an exception rather than returning null when the InputStream does not exist. + InputStream is = null; + try { + is = connection.getInputStream(); + } catch (Exception e1) { + // ignore this + } + if (is != null) { + is.close(); + } + + } catch (IOException ex) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + } + +} + + diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/XacmlAdminUI.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/XacmlAdminUI.java new file mode 100644 index 000000000..aec8a0ac1 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/XacmlAdminUI.java @@ -0,0 +1,266 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.admin; + + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebInitParam; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; + + +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.lib.StoredConfig; +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.openecomp.policy.rest.XACMLRest; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.dao.UserInfoDao; +import org.openecomp.policy.rest.jpa.UserInfo; +import org.openecomp.policy.rest.util.Webapps; +import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; +import org.springframework.beans.factory.annotation.Autowired; + +import com.att.research.xacml.util.XACMLProperties; +import com.google.common.base.Splitter; + + + +public class XacmlAdminUI extends HttpServlet implements PAPNotificationBroadcaster.PAPNotificationBroadcastListener{ + + private static final long serialVersionUID = 1L; + // + // The PAP Engine + // + private PAPPolicyEngine papEngine; + private static Path repositoryPath; + private static Repository repository; + + @Autowired + UserInfoDao userInfoDao; + + @Autowired + SessionFactory sessionfactory; + + @WebServlet(value = "/policy#/*", description = "XACML Admin Console", asyncSupported = true, loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") }) + public static class Servlet extends HttpServlet { + private static final long serialVersionUID = -5274600248961852835L; + + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + // + // Common initialization + // + XACMLRest.xacmlInit(servletConfig); + // + // Initialize GIT repository. + // + XacmlAdminUI.initializeGitRepository(); + // + // Read the Props + // The webapps Action and Config are read when getActionHome or getConfigHome are called + try { + getConfigHome(); + } catch (Exception e) { + throw new ServletException(e); + } + + } + + + @Override + public void destroy() { + if (XacmlAdminUI.repository != null) { + XacmlAdminUI.repository.close(); + } + super.destroy(); + } + } + + private static void initializeGitRepository() throws ServletException { + + try { + XacmlAdminUI.repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY)); + } catch (Exception e) { + XACMLProperties.reloadProperties(); + XacmlAdminUI.repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY)); + } + FileRepositoryBuilder builder = new FileRepositoryBuilder(); + try { + XacmlAdminUI.repository = builder.setGitDir(XacmlAdminUI.repositoryPath.toFile()).readEnvironment().findGitDir().setBare().build(); + if (Files.notExists(XacmlAdminUI.repositoryPath)|| Files.notExists(Paths.get(XacmlAdminUI.repositoryPath.toString(), "HEAD"))) { + // + // Create it if it doesn't exist. As a bare repository + XacmlAdminUI.repository.create(); + // + // Add the magic file so remote works. + // + Path daemon = Paths.get(XacmlAdminUI.repositoryPath.toString(), "git-daemon-export-ok"); + Files.createFile(daemon); + } + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + // + // Make sure the workspace directory is created + // + Path workspace = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE)); + workspace = workspace.toAbsolutePath(); + if (Files.notExists(workspace)) { + try { + Files.createDirectory(workspace); + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + // + // Create the user workspace directory + // + workspace = Paths.get(workspace.toString(), "admin"); + + if (Files.notExists(workspace)) { + try { + Files.createDirectory(workspace); + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + // + // Get the path to where the repository is going to be + // + Path gitPath = Paths.get(workspace.toString(), XacmlAdminUI.repositoryPath.getFileName().toString()); + if (Files.notExists(gitPath)) { + try { + Files.createDirectory(gitPath); + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + // + // Initialize the domain structure + // + String base = null; + String domain = XacmlAdminUI.getDomain(); + if (domain != null) { + for (String part : Splitter.on(':').trimResults().split(domain)) { + if (base == null) { + base = part; + } + Path subdir = Paths.get(gitPath.toString(), part); + if (Files.notExists(subdir)) { + try { + Files.createDirectory(subdir); + Files.createFile(Paths.get(subdir.toString(), ".svnignore")); + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + } + } else { + try { + Files.createFile(Paths.get(workspace.toString(), ".svnignore")); + base = ".svnignore"; + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + try { + // + // These are the sequence of commands that must be done initially to + // finish setting up the remote bare repository. + // + Git git = Git.init().setDirectory(gitPath.toFile()).setBare(false).call(); + git.add().addFilepattern(base).call(); + git.commit().setMessage("Initialize Bare Repository").call(); + StoredConfig config = git.getRepository().getConfig(); + config.setString("remote", "origin", "url", XacmlAdminUI.repositoryPath.toAbsolutePath().toString()); + config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); + config.save(); + git.push().setRemote("origin").add("master").call(); + /* + * This will not work unless + * git.push().setRemote("origin").add("master").call(); is called + * first. Otherwise it throws an exception. However, if the push() + * is called then calling this function seems to add nothing. + * + * git.branchCreate().setName("master") + * .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM) + * .setStartPoint("origin/master").setForce(true).call(); + */ + } catch (GitAPIException | IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + + public UserInfo getUserNameFromUserInfoTable(String createdBy){ + String loginId = createdBy; + Object user = null; + Session session = sessionfactory.openSession(); + user = session.load(UserInfo.class, loginId); + return (UserInfo) user; + } + + @Override + public void updateAllGroups() { + + } + + public PAPPolicyEngine getPapEngine() { + return papEngine; + } + + public void setPapEngine(PAPPolicyEngine papEngine) { + this.papEngine = papEngine; + } + + public static String getConfigHome() { + return Webapps.getConfigHome(); + } + + public static String getDomain() { + return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn"); + } + + // get the repository path from property file + public static Path getRepositoryPath() { + if(repositoryPath == null){ + try { + initializeGitRepository(); + } catch (ServletException e) { + + } + } + return repositoryPath; + } + + +} + diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/ElasticSearchComponent.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/ElasticSearchComponent.java new file mode 100644 index 000000000..35a4d14b8 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/ElasticSearchComponent.java @@ -0,0 +1,426 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.components; + + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.regex.Pattern; + +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.elk.client.ElkConnector; +import org.openecomp.policy.elk.client.ElkConnector.PolicyIndexType; +import org.openecomp.policy.rest.dao.DescriptiveScopeDao; +import org.openecomp.policy.rest.jpa.DescriptiveScope; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.elk.client.Pair; +import org.openecomp.policy.elk.client.PolicyLocator; +import org.springframework.beans.factory.annotation.Autowired; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +public class ElasticSearchComponent { + private static final Logger logger = FlexLogger.getLogger(ElasticSearchComponent.class); + + + private static PolicyVersionDao policyVersionDao; + private static DescriptiveScopeDao descriptiveScopeDao; + + @Autowired + public ElasticSearchComponent(PolicyVersionDao policyVersionDao){ + ElasticSearchComponent.policyVersionDao = policyVersionDao; + } + + @Autowired + public ElasticSearchComponent(DescriptiveScopeDao descriptiveScopeDao){ + ElasticSearchComponent.descriptiveScopeDao = descriptiveScopeDao; + } + + + private volatile static HashMap<Path, String> filteredPolicies = new HashMap<Path, String>(); + + public static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() { + private static final long serialVersionUID = 1L; + { + put(CLFAULT_UIFIELD_D2_SERVICES_TRINITY, CLFAULT_UIJSON_D2_SERVICES_TRINITY); + put(CLFAULT_UIFIELD_D2_SERVICES_VUSP, CLFAULT_UIJSON_D2_SERVICES_VUSP); + put(CLFAULT_UIFIELD_D2_SERVICES_MCR, CLFAULT_UIJSON_D2_SERVICES_MCR); + put(CLFAULT_UIFIELD_D2_SERVICES_GAMMA, CLFAULT_UIJSON_D2_SERVICES_GAMMA); + put(CLFAULT_UIFIELD_D2_SERVICES_VDNS, CLFAULT_UIJSON_D2_SERVICES_VDNS); + + put(CLFAULT_UIFIELD_EMAIL_ADDRESS, CLFAULT_UIJSON_EMAIL_ADDRESS); + put(CLFAULT_UIFIELD_TRIGGER_SIGNATURE, CLFAULT_UIJSON_TRIGGER_SIGNATURE); + put(CLFAULT_UIFIELD_VERIFICATION_SIGNATURE, CLFAULT_UIJSON_VERIFICATION_SIGNATURE); + put(CLFAULT_UIFIELD_CONNECT_ALL_TRAPS, CLFAULT_UIJSON_CONNECT_ALL_TRAPS); + put(CLFAULT_UIFIELD_CONNECT_ALL_FAULTS, CLFAULT_UIJSON_CONNECT_ALL_FAULTS); + + put(CLFAULT_UIFIELD_POLICY_STATUS_INACTIVE, CLFAULT_UIJSON_POLICY_STATUS_ACTIVE); + put(CLFAULT_UIFIELD_POLICY_STATUS_ACTIVE, CLFAULT_UIJSON_POLICY_STATUS_INACTIVE); + + put(CLPM_UIFIELD_ONSET_MESSAGE, CLPM_UIJSON_ONSET_MESSAGE); + put(CLPM_UIFIELD_POLICY_NAME, CLPM_UIJSON_POLICY_NAME); + put(CLPM_UIFIELD_ABATEMENT_MESSAGE, CLPM_UIJSON_ABATEMENT_MESSAGE); + put(CLPM_UIFIELD_GEOLINK, CLPM_UIJSON_GEOLINK); + }}; + + //For AND and OR logical connector AND=0 and OR=1 + private static int connectorSelected; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_TRINITY = "Hosted Voice (Trinity)"; + public static final String CLFAULT_UIJSON_D2_SERVICES_TRINITY = "trinity"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_VUSP = "vUSP"; + public static final String CLFAULT_UIJSON_D2_SERVICES_VUSP = "vUSP"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_MCR = "MCR"; + public static final String CLFAULT_UIJSON_D2_SERVICES_MCR = "mcr"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_GAMMA = "Gamma"; + public static final String CLFAULT_UIJSON_D2_SERVICES_GAMMA = "gama"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_VDNS = "vDNS"; + public static final String CLFAULT_UIJSON_D2_SERVICES_VDNS = "vDNS"; + + public static final String CLFAULT_UIFIELD_EMAIL_ADDRESS = "Email Address"; + public static final String CLFAULT_UIJSON_EMAIL_ADDRESS = "emailAddress"; + + public static final String CLFAULT_UIFIELD_TRIGGER_SIGNATURE = "Trigger Signature"; + public static final String CLFAULT_UIJSON_TRIGGER_SIGNATURE = "triggerSignaturesUsedForUI.signatures"; + + public static final String CLFAULT_UIFIELD_VERIFICATION_SIGNATURE = "Verification Signature"; + public static final String CLFAULT_UIJSON_VERIFICATION_SIGNATURE = "verificationSignaturesUsedForUI.signatures"; + + public static final String CLFAULT_UIFIELD_CONNECT_ALL_TRAPS = "Connect All Traps"; + public static final String CLFAULT_UIJSON_CONNECT_ALL_TRAPS = "triggerSignaturesUsedForUI.connectSignatures"; + + public static final String CLFAULT_UIFIELD_CONNECT_ALL_FAULTS = "Connect All Faults"; + public static final String CLFAULT_UIJSON_CONNECT_ALL_FAULTS = "verificationSignaturesUsedForUI.connectSignatures"; + + public static final String CLFAULT_UIFIELD_POLICY_STATUS_ACTIVE = "Active"; + public static final String CLFAULT_UIJSON_POLICY_STATUS_ACTIVE = "ACTIVE"; + + public static final String CLFAULT_UIFIELD_POLICY_STATUS_INACTIVE = "InActive"; + public static final String CLFAULT_UIJSON_POLICY_STATUS_INACTIVE = "INACTIVE"; + + + public static final String CLPM_UIFIELD_ONSET_MESSAGE = "Onset Message"; + public static final String CLPM_UIJSON_ONSET_MESSAGE = "attributes.OnsetMessage"; + + public static final String CLPM_UIFIELD_POLICY_NAME = "PolicyName"; + public static final String CLPM_UIJSON_POLICY_NAME = "attributes.PolicyName"; + + public static final String CLPM_UIFIELD_ABATEMENT_MESSAGE = "Abatement Message"; + public static final String CLPM_UIJSON_ABATEMENT_MESSAGE = "attributes.AbatementMessage"; + + public static final String CLPM_UIFIELD_GEOLINK = "Geo Link"; + public static final String CLPM_UIJSON_GEOLINK = "geoLink"; + + public static void search(String value){ + String policyType = "all";//(String) self.searchPolicyType.getValue() + + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(); + + String searchText = "";//self.searchTextBox.getValue() + if (searchText == null || searchText.isEmpty()) { + if (policyType == null || policyType.isEmpty() && + !policyType.equals(ElkConnector.PolicyIndexType.closedloop.toString())) { + if (logger.isDebugEnabled()) { + logger.debug("Clearing search filters, nothing to search and not closed loop."); + } + return; + } + } else { + searchText = searchText.trim(); + //Descriptive Scope. + /* + When a item is selected in the "descriptiveScope" comboBox, the name of the item + is added to the Search-Text Box with the prefix "Descriptive-Scope" + User needs to press the "Search" button to perform the search. + */ + if(searchText.contains("Descriptive-Scope=")) + { + if (logger.isDebugEnabled()) { + logger.debug("Inside the Descriptive Scope"); + } + /* + First item is always String "Descriptive-Scope" before the "=", + So taking the second item of "split using =" + */ + String[] dsName= searchText.split("=",2); + /* + Trying to find the search String by traversing different items from the dictionary by Scope-Name + Once when the the "scope-name" is found, we get the search string from dictionary. + */ + for (int i = 0; i < descriptiveScopeDao.getDescriptiveScope().size(); i++) { + DescriptiveScope dsSearch=descriptiveScopeDao.getDescriptiveScope().get(i); + if(dsSearch.getScopeName().equals(dsName[1])){ + searchText=dsSearch.getSearch(); + if (logger.isDebugEnabled()) { + logger.debug("DescriptiveScope Search String is " +searchText ); + } + } + } + } + + if(searchText.contains(":")) + { + String connector="&"; + + if(searchText.contains("&")) + { + connector="&"; + connectorSelected=0; + } + else if(searchText.contains("|")) + { + connector=Pattern.quote("|"); + connectorSelected=1; + } + for (String retval: searchText.split(connector)){ + + int index= retval.indexOf(':'); + String filterKey=null; + String filterValue=null; + + filterKey=retval.substring(0,index); + filterValue= retval.substring(index+1); + + String clSearchBoxFilter=filterKey; + + ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>(); + + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchBoxFilter); + + + ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>(); + clSearchBoxFilterValue_s.add(filterValue); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); + } + } + } + + if (policyType != null && !policyType.isEmpty() && + policyType.equals(ElkConnector.PolicyIndexType.closedloop.toString())) { + + /* closed loop policy type */ + + String clPolicyType = "";//(String) self.cbSearchCLPolicyType.getValue() + if (clPolicyType != null && !clPolicyType.isEmpty()) { + ArrayList<String> clPolicyTypeField_s = new ArrayList<String>(); + clPolicyTypeField_s.add("Policy.PolicyType"); + + ArrayList<String> clPolicyTypeValue_s = new ArrayList<String>(); + clPolicyTypeValue_s.add(clPolicyType); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clPolicyTypeField_s, clPolicyTypeValue_s)); + } + + String clEcompName = "";//(String) self.cbSearchCLEcompName.getValue() + if (clEcompName != null && !clEcompName.isEmpty()) { + clSearchBody(clPolicyType, "ecompname", clEcompName, filter_s); + } + + String clD2Services = "";//(String) self.cbSearchCLD2Services.getValue() + if (clD2Services != null && !clD2Services.isEmpty()) { + switch (clD2Services) { + case CLFAULT_UIFIELD_D2_SERVICES_TRINITY: + case CLFAULT_UIFIELD_D2_SERVICES_VUSP: + case CLFAULT_UIFIELD_D2_SERVICES_MCR: + case CLFAULT_UIFIELD_D2_SERVICES_GAMMA: + case CLFAULT_UIFIELD_D2_SERVICES_VDNS: + clSearchBody(clPolicyType, name2jsonPath.get(clD2Services), "true", filter_s); + break; + default: + if (logger.isWarnEnabled()) + logger.warn("Unexpected D2 Service: " + clD2Services); + break; + } + } + + String clFaultAction = "";//(String) self.cbSearchCLFaultAction.getValue() + if (clFaultAction != null && !clFaultAction.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "actions", clFaultAction, filter_s); + } + } + + String clFaultStatus = "";//(String) self.cbSearchCLFaultStatus.getValue() + if (clFaultStatus != null && !clFaultStatus.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "closedLoopPolicyStatus", clFaultStatus, filter_s); + } + } + + String clFaultVnfTypes = "";//(String) self.cbSearchCLFaultVnfTypes.getValue() + if (clFaultVnfTypes != null && !clFaultVnfTypes.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "vnfType", clFaultVnfTypes, filter_s); + } + } + + String clPMServiceType = "";//(String) self.cbSearchCLPMServiceType.getValue() + if (clPMServiceType != null && !clPMServiceType.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_PM.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_PM.name(), "serviceTypePolicyName", clPMServiceType, filter_s); + } + } + + String clSearchBoxFilter = "";//(String) self.cbSearchCLTextFilter.getValue() + if (clSearchBoxFilter != null && !clSearchBoxFilter.isEmpty() && + searchText != null && !searchText.isEmpty()) { + + if (name2jsonPath.containsKey(clSearchBoxFilter)) { + clSearchBoxFilter = name2jsonPath.get(clSearchBoxFilter); + } + + ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>(); + if (clPolicyType == null || clPolicyType.isEmpty()) { + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter); + } else { + clSearchBoxFilterField_s.add("Policy.Body." + clPolicyType + "_Body." + clSearchBoxFilter); + } + + ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>(); + clSearchBoxFilterValue_s.add(searchText); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); + + // deactivate search all fields in case a searchbox filter is provided + searchText = ""; + } + } + + if ((searchText == null || searchText.isEmpty()) && + (filter_s == null || filter_s.size() <=0) ) { + if (logger.isWarnEnabled()) { + logger.warn("Clearing search filters, closed loop but nothing to search nor filters"); + } + + return; + } + + ArrayList<PolicyLocator> locators; + try { + locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), + searchText, filter_s,connectorSelected); + } catch (Exception ise) { + /*AdminNotification.warn("Search is unavailable: " + ise.getMessage());*/ + return; + } + + synchronized(filteredPolicies) { + if (locators.isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("No match has been found"); + } + //AdminNotification.warn("No match has been found"); + return; + } + + // Retrieve active versions + + HashMap<String, Boolean> policyVersion_s = new HashMap<String, Boolean>(); + for(int i = 0; i < policyVersionDao.getPolicyVersionData().size(); i++) { + PolicyVersion entityVersion = policyVersionDao.getPolicyVersionData().get(i); + String dbPolicy = entityVersion.getPolicyName() + "." + entityVersion.getActiveVersion(); + policyVersion_s.put(dbPolicy, true); + if (logger.isDebugEnabled()) + logger.debug("Map addition: DB Policy Name: " + dbPolicy); + } + + filteredPolicies.clear(); + for (PolicyLocator p: locators) { + String dbPolicyName = p.scope + "/" + p.policyType + "_" + p.policyName; + if (policyVersion_s.containsKey(dbPolicyName)) { + String filterPolicyName = dbPolicyName + ".xml"; + filteredPolicies.put(Paths.get(filterPolicyName), filterPolicyName); + if (logger.isInfoEnabled()) + logger.info("Active Version Policy found in search: " + + dbPolicyName + " -> " + filterPolicyName); + } else { + if (logger.isInfoEnabled()) + logger.info("Inactive Version Policy found in search: " + dbPolicyName); + } + } + + if (filteredPolicies.isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("No match has been found for active versions"); + } + //AdminNotification.warn("No match has been found for active versions"); + return; + } + + //self.policyContainer.setFilter(self.filteredPolicies); + } + /* self.policyContainer.refresh();*/ + } + + + protected static void clSearchBody(String clPolicyType, String bodyField, String bodyValue, + ArrayList<Pair<ArrayList<String>, ArrayList<String>>> filter_s) { + if (logger.isDebugEnabled()) + logger.debug("ENTER: " + clPolicyType + ":" + bodyField + ":" + bodyValue); + + final ArrayList<String> clBodyField_s = new ArrayList<String>(); + final ArrayList<String> clBodyValue_s = new ArrayList<String>(); + + if (clPolicyType == null || clPolicyType.isEmpty()) { + clBodyField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + bodyField); + clBodyField_s.add("Policy.Body."+ ElkConnector.PolicyType.Config_PM.name() + "_Body." + bodyField); + clBodyValue_s.add(bodyValue); + } else { + clBodyField_s.add("Policy.Body." + clPolicyType + "_Body." + bodyField); + clBodyValue_s.add(bodyValue); + } + filter_s.add(new Pair<ArrayList<String>, ArrayList<String>>(clBodyField_s, clBodyValue_s)); + } + + protected static void clSearchFilter(String clType, String clField, String clValue, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) { + if (logger.isDebugEnabled()) + logger.debug("ENTER: " + clType + ":" + clField + ":" + clValue); + + ArrayList<String> clSearchField_s = new ArrayList<String>(); + clSearchField_s.add("Policy.Body." + clType + "_Body." + clField); + + ArrayList<String> clSearchValue_s = new ArrayList<String>(); + clSearchValue_s.add(clValue); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchField_s, clSearchValue_s)); + } + + public static ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException { + if (type == null || type.isEmpty()) + return PolicyIndexType.all; + + return PolicyIndexType.valueOf(type); + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java new file mode 100644 index 000000000..037888b7c --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java @@ -0,0 +1,982 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.components; + + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeSelectorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; + +import org.apache.commons.io.FilenameUtils; +import org.json.JSONObject; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.rest.jpa.FunctionDefinition; +import org.openecomp.policy.utils.XACMLPolicyWriterWithPapNotify; + +import com.att.research.xacml.api.AttributeValue; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAttribute; +import com.att.research.xacml.std.StdAttributeValue; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; +import com.att.research.xacml.util.XACMLPolicyScanner.SimpleCallback; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + + +public class HumanPolicyComponent{ + + private static final Logger logger = FlexLogger.getLogger(HumanPolicyComponent.class); + + // Constants Used in XML Creation + public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"; + public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; + public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; + public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; + public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id"; + public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; + public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; + public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"; + public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"; + public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; + public static final String FUNCTION_STRING_REGEX_MATCH = "org.openecomp.function.regex-match"; + public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"; + public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; + public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; + public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string"; + public static final String URI_DATATYPE = "http://www.w3.org/2001/XMLSchema#anyURI"; + public static final String RULE_VARIABLE = "var:"; + public static final String EMPTY_STRING = ""; + + private static HtmlProcessor htmlProcessor; + + private static File policyFile; + + public static JSONObject DescribePolicy(final File policyFile) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + HumanPolicyComponent.policyFile = policyFile; + return humanPolicyLayout(); + + } + + private static JSONObject humanPolicyLayout() { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + try { + String html = processPolicy(); + JSONObject result = new JSONObject(); + result.put("html", html); + return result; + //ByteArrayInputStream is = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)); + + } catch (IllegalArgumentException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "cannot build html area por policy", e); + /*AdminNotification.warn("An error has occurred. Cannot describe this policy: " + + e.getMessage());*/ + } + return null; + } + + private static String processPolicy() throws IllegalArgumentException { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + FileInputStream pIS = null; + try { + pIS = new FileInputStream(policyFile); + Object policy = XACMLPolicyScanner.readPolicy(pIS); + if (policy == null) + throw new IllegalArgumentException("Policy File " + policyFile.getName() + + " cannot be unmarshalled"); + + HumanPolicyComponent.htmlProcessor = + new HtmlProcessor(HumanPolicyComponent.policyFile, policy); + + Path policyPath = FileSystems.getDefault().getPath(policyFile.getAbsolutePath()); + XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor); + xacmlScanner.scan(); + String html = htmlProcessor.html(); + if (logger.isDebugEnabled()) + logger.debug(policyPath + System.lineSeparator() + html); + + return html; + + } catch (Exception e) { + String msg = "Exception reading policy: " + policyFile.getAbsolutePath() + + ": " + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + msg, e); + throw new IllegalArgumentException(msg); + } finally { + if (pIS != null) { + try { + pIS.close(); + } catch (IOException e) { + logger.warn(e.getMessage(), e); + } + } + } + } + +} + +class HtmlProcessor extends SimpleCallback { + + private static final Logger logger = FlexLogger.getLogger(HtmlProcessor.class); + + private static Map<String, String> function2human; + static { + function2human = new HashMap<String, String>(); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL_IGNORE, "equal"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_ONE_AND_ONLY, "one-and-only"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_REGEX_MATCH, "matching regular expression"); + function2human.put(HumanPolicyComponent.FUNTION_INTEGER_ONE_AND_ONLY, "one-and-only"); + } + + private static Map<String, String> combiningAlgo2human; + static { + combiningAlgo2human = new HashMap<String, String>(); + combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to <i>deny</i>"); + combiningAlgo2human.put("permit-overrides", "to permit if any $placeholder$ below evaluates to <i>permit</i>"); + + combiningAlgo2human.put("ordered-deny-overrides", "to deny if any $placeholder$ below evaluates to <i>deny</i>"); + combiningAlgo2human.put("ordered-permit-overrides", "to permit if any $placeholder$ below evaluates to <i>permit</i>"); + combiningAlgo2human.put("deny-unless-permit", "to permit if any $placeholder$ below evaluates to <i>deny</i> and not <i>indeterminate</i>"); + + combiningAlgo2human.put("permit-unless-deny", "to deny if any $placeholder$ below evaluates to is <i>permit</i> and not <i>indeterminate</i>"); + combiningAlgo2human.put("first-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order"); + combiningAlgo2human.put("only-one-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order"); + } + + private Map<String, AttributeIdentifiers> attributeIdentifiersMap = new HashMap<String, AttributeIdentifiers>(); + + private final StringWriter stringWriter = new StringWriter(); + private final PrintWriter htmlOut = new PrintWriter(stringWriter); + private final String policyName; + private final Object rootPolicyObject; + + public HtmlProcessor(File policyFile, Object policyObject) + throws IllegalArgumentException { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + if (policyFile == null) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File"); + throw new IllegalArgumentException("Null Policy File"); + } + + if (!policyFile.exists() || !policyFile.canRead()) { + String msg = "Can't access " + policyFile.getAbsolutePath(); + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + msg); + throw new IllegalArgumentException(msg); + } + + if (policyObject == null || + (!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) { + String msg = "Invalid unmarshalled object: " + policyObject; + logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + msg); + throw new IllegalArgumentException(msg); + } + + this.policyName = FilenameUtils.removeExtension(policyFile.getName()); + this.rootPolicyObject = policyObject; + + String version = "-"; + if (policyObject instanceof PolicyType) { + PolicyType policy = (PolicyType) policyObject; + version = policy.getVersion(); + htmlOut.println("<h1>Policy: " + policyName + + " (version " + version + ") </h1>"); + + } else { + PolicySetType policySet = (PolicySetType) policyObject; + version = policySet.getVersion(); + htmlOut.println("<h1>Policy Set: " + policyName + + " (v" + version + ") </h1>"); + } + + htmlOut.println("<h3><b>Location: </b>" + policyFile.getPath() + "</h3>"); + htmlOut.println("<hr>"); + + if (rootPolicyObject instanceof PolicySetType) { + if (policyName.startsWith("Config_")) { + htmlOut.println("<p>This is a <b>config</b> policy set.</p>"); + } else if (policyName.startsWith("Action_")) { + htmlOut.println("<p>This is an <b>action</b> policy set.</p>"); + } + htmlOut.println("<dl>"); + } else { + if (policyName.startsWith("Config_")) { + htmlOut.println("<p>This is a <b>config</b> policy.</p>"); + } else if (policyName.startsWith("Action_")) { + htmlOut.println("<p>This is an <b>action</b> policy.</p>"); + } + htmlOut.println("<ol>"); + } + } + + /** + * @return the attributeIdentifiersMap + */ + public Map<String, AttributeIdentifiers> getAttributeIdentifiersMap() { + return attributeIdentifiersMap; + } + + @Override + public void onFinishScan(Object root) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + if (rootPolicyObject instanceof PolicySetType) { + htmlOut.println("</dl>"); + } else { + htmlOut.println("</ol>"); + } + + htmlOut.println("<hr>"); + + htmlOut.println("<h3>Attribute Table:</h3>"); + + htmlOut.println("<table border=\"3\" style=\"width:100%\">"); + htmlOut.println("<tr>"); + htmlOut.print("<th>Category</th>"); + htmlOut.print("<th>Type</th>"); + htmlOut.print("<th>Identifier</th>"); + htmlOut.println("</tr>"); + for(Map.Entry<String, AttributeIdentifiers> entry : this.attributeIdentifiersMap.entrySet()){ + AttributeIdentifiers value = entry.getValue(); + htmlOut.println("<tr>"); + htmlOut.print("<td><a name=\"" + entry.getKey() + "\"></a>" + value.category + "</td>"); + htmlOut.print("<td>" + value.type + "</td>"); + htmlOut.print("<td>" + value.id + "</td>"); + htmlOut.println("</tr>"); + } + htmlOut.println("</table>"); + + htmlOut.println("<p></p>"); + + // Not necessary for the user, uncomment if desired at some point + // writeRawXACML() + + super.onFinishScan(root); + } + + @SuppressWarnings("unused") + private void writeRawXACML() { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + htmlOut.println("<hr>"); + htmlOut.println("<h3>Raw XACML:</h3>"); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + if (rootPolicyObject instanceof PolicySetType) { + XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicySetType) rootPolicyObject); + } else if (rootPolicyObject instanceof PolicyType) { + XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicyType) rootPolicyObject); + } + + String xacml = bos.toString(); + xacml = xacml.replaceAll("<", "<"); + xacml = xacml.replaceAll(">", ">"); + htmlOut.println("<pre>"); + htmlOut.println(xacml); + htmlOut.println("</pre>"); + } + + @Override + public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) { + if (logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policySet.getDescription(); + if (description != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + + " Description: " + policySet.getDescription()); + + if (parent == null) // root + policySet(policySet, "dl"); + else + policySet(policySet, "li"); + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) + htmlOut.println("<ol>"); + + return super.onPreVisitPolicySet(parent, policySet); + } + + @Override + public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) { + if (logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policySet.getDescription(); + if (description != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId() + + " Description: " + policySet.getDescription()); + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) + htmlOut.println("</ol>"); + + htmlOut.println("<p></p>"); + + return super.onPostVisitPolicySet(parent, policySet); + } + + public void policySet(PolicySetType policySet, String htmlListElement) { + if (logger.isTraceEnabled()) + logger.trace("PolicySet: " + policySet.getPolicySetId()); + + String combiningAlgorithm = "-"; + String id = "-"; + String version = "-"; + + + if (policySet.getPolicyCombiningAlgId() != null) + combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":"); + + if (policySet.getPolicySetId() != null) + id = extractLastIdentifier(policySet.getPolicySetId(), ":"); + + if (policySet.getVersion() != null) + version = policySet.getVersion(); + + + htmlOut.println("<" + htmlListElement + "><b>Policy Set ID</b>: <i>" + id + + "</i> (v" + version + ") " + "</" + htmlListElement + ">"); + + if (policySet.getTarget() == null || + policySet.getTarget().getAnyOf() == null || + policySet.getTarget().getAnyOf().size() <= 0) { + htmlOut.println("<p>This policy set applies to all requests.</p>"); + } else { + htmlOut.print("<p>"); + htmlOut.print("This policy set applies to requests with attributes "); + + List<AnyOfType> anyOf_s = policySet.getTarget().getAnyOf(); + target(anyOf_s); + htmlOut.println(".</p>"); + } + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference() != null && + policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) { + String algoDesc = combiningAlgo2human.get(combiningAlgorithm); + if (algoDesc != null) { + algoDesc = algoDesc.replace("$placeholder$", "policy") + " (" + "<i>" + combiningAlgorithm + "</i>)"; + } else { + algoDesc = combiningAlgorithm; + } + + htmlOut.println("<p>The result is " + algoDesc + ": </p>"); + } + } + + @Override + public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) { + if (logger.isTraceEnabled()) + logger.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policy.getPolicyId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policy.getDescription(); + if (description != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policy.getPolicyId() + + " Description: " + policy.getDescription()); + + policy(policy); + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) + htmlOut.println("<ol type=\"i\">"); + + return super.onPreVisitPolicy(parent, policy); + } + + @Override + public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) { + if (logger.isTraceEnabled()) + logger.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("PolicySet: " + policy.getPolicyId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) + htmlOut.println("</ol>"); + + htmlOut.println("<p></p>"); + return super.onPostVisitPolicy(parent, policy); + } + + public void policy(PolicyType policy) { + if (logger.isTraceEnabled()) + logger.trace("Policy: " + policy.getPolicyId()); + + String combiningAlgorithm = "-"; + String id = "-"; + String version = "-"; + + + if (policy.getRuleCombiningAlgId() != null) + combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":"); + + if (policy.getPolicyId() != null) + id = extractLastIdentifier(policy.getPolicyId(), ":"); + + if (policy.getVersion() != null) + version = policy.getVersion(); + + htmlOut.println("<li><b>Policy ID</b>: <i>" + id + + "</i> (v" + version + ") " + "</li>"); + + if (policy.getTarget() == null || + policy.getTarget().getAnyOf() == null || + policy.getTarget().getAnyOf().size() <= 0) { + htmlOut.println("<p>This policy applies to all requests.</p>"); + } else { + htmlOut.print("<p>"); + htmlOut.print("This policy applies to requests with attributes "); + + List<AnyOfType> anyOf_s = policy.getTarget().getAnyOf(); + target(anyOf_s); + htmlOut.println(".</p>"); + } + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() != null && + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) { + String algoDesc = combiningAlgo2human.get(combiningAlgorithm); + if (algoDesc != null) { + algoDesc = algoDesc.replace("$placeholder$", "rule") + " (<i>" + combiningAlgorithm + "</i>)"; + } else { + algoDesc = combiningAlgorithm; + } + htmlOut.println("<p>The result is " + algoDesc + ": </p>"); + } + } + + + @Override + public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) { + if (logger.isTraceEnabled()) + logger.trace("Rule: " + rule.getRuleId()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + + String description = rule.getDescription(); + if (description != null && logger.isTraceEnabled()) { + logger.trace("Rule: " + rule.getRuleId() + + " Description: " + rule.getDescription()); + } + + rule(rule); + + return super.onPreVisitRule(parent, rule); + } + + @Override + public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) { + if (logger.isTraceEnabled()) + logger.trace("Rule: " + rule.getRuleId()); + + if (parent != null && logger.isTraceEnabled()) + logger.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + + return super.onPostVisitRule(parent, rule); + } + + public void rule(RuleType rule) { + if (logger.isTraceEnabled()) + logger.trace("Rule: " + rule.getRuleId()); + + String id = "-"; + + if (rule.getRuleId() != null) + id = extractLastIdentifier(rule.getRuleId(), ":"); + + htmlOut.println("<li><b>Rule ID</b>: <i>" + id + "</i></li>"); + + htmlOut.println("<dl>"); + + htmlOut.print("<p>"); + htmlOut.print(rule.getEffect().value()); + + if (rule.getTarget() == null || + rule.getTarget().getAnyOf() == null || + rule.getTarget().getAnyOf().size() <= 0) { + htmlOut.print(" for all requests"); + } else { + List<AnyOfType> anyOf_s = rule.getTarget().getAnyOf(); + htmlOut.print(" for requests with attributes "); + target(anyOf_s); + } + + if (rule.getCondition() != null) { + htmlOut.print(" when "); + htmlOut.println(this.stringifyCondition(rule.getCondition()) + " "); + } else { + htmlOut.print(" with no conditions "); + } + + if (rule.getAdviceExpressions() != null) { + advice(rule.getAdviceExpressions()); + if (rule.getObligationExpressions() != null) + htmlOut.println(" and "); + } + + if (rule.getObligationExpressions() != null) { + obligation(rule.getObligationExpressions()); + } + + htmlOut.println("</p>"); + } + + private void advice(AdviceExpressionsType adviceExpressions) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + List<AdviceExpressionType> ae = adviceExpressions.getAdviceExpression(); + for (AdviceExpressionType expression : ae) { + htmlOut.println(" with <b>advice</b> (<i>" + expression.getAdviceId() + "</i>) on <i>" + + expression.getAppliesTo().value() + "</i>:" ); + htmlOut.println("<ol type=\"a\">"); + List<AttributeAssignmentExpressionType> assignments = expression.getAttributeAssignmentExpression(); + if (assignments != null) { + processAttributeAssignments(assignments); + } + htmlOut.println("</ol>"); + } + } + + private void obligation(ObligationExpressionsType obligationExpressions) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + List<ObligationExpressionType> oe = obligationExpressions.getObligationExpression(); + for (ObligationExpressionType expression : oe) { + htmlOut.println(" with <b>obligations</b> (<i>" + expression.getObligationId() + "</i>) to be fullfilled on <i>" + + expression.getFulfillOn().value() + "</i>:" ); + htmlOut.println("<ol type=\"a\">"); + List<AttributeAssignmentExpressionType> assignments = expression.getAttributeAssignmentExpression(); + if (assignments != null) { + processAttributeAssignments(assignments); + } + htmlOut.println("</ol>"); + } + } + + /** + * @param assignments + */ + private void processAttributeAssignments(List<AttributeAssignmentExpressionType> assignments) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + for (AttributeAssignmentExpressionType assignment : assignments) { + String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") + + ":" + extractLastIdentifier(assignment.getAttributeId(), ":"); + AttributeIdentifiers attributeIdentifiers = null; + if (!this.attributeIdentifiersMap.containsKey(succintIdentifier)) { + // Note Attribute Assignments do not have an Attribute Type, assume string + // but note this case is unlikely since attributeMap should have been populated + // during parsing of target and conditions, and not in this case for Advice and + // Obligations. + attributeIdentifiers = new AttributeIdentifiers(assignment.getCategory(), + "NA", + assignment.getAttributeId()); + this.attributeIdentifiersMap.put(succintIdentifier, attributeIdentifiers); + } + + htmlOut.print("<li><i><a href=\"#" + succintIdentifier + "\">" + succintIdentifier + "</a></i> is "); + // AttributeValueType + JAXBElement<?> jaxbExp = assignment.getExpression(); + Object assignmentObject = jaxbExp.getValue(); + if (assignmentObject instanceof AttributeValueType) { + AttributeValueType avt = (AttributeValueType) assignmentObject; + if (attributeIdentifiers != null) { + attributeIdentifiers.type = avt.getDataType(); + } + int numContent = avt.getContent().size(); + int countContent = 0; + for (Object c: avt.getContent()) { + countContent++; + htmlOut.print("<i>" + c + "</i>"); + if (countContent < numContent) + htmlOut.print(" or "); + } + htmlOut.println("</li>"); + } else if (assignmentObject instanceof AttributeDesignatorType) { + htmlOut.println("NA"); + } else if (assignmentObject instanceof AttributeSelectorType) { + htmlOut.println("NA"); + } else if (assignmentObject instanceof ApplyType) { + htmlOut.println("NA"); + } else { + htmlOut.println("Unexpected"); + } + } + } + + /** + * + * @param anyOfList + */ + public void target(List<AnyOfType> anyOfList) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + String targetInHuman = ""; + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + Iterator<MatchType> iterMatch = matchList.iterator(); + if (matchList.size() > 1) + targetInHuman += "("; + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Finally down to the actual attribute + // + StdAttribute attribute = null; + AttributeValueType value = match.getAttributeValue(); + String attributeDataType = null; + if (match.getAttributeDesignator() != null && value != null) { + AttributeDesignatorType designator = match.getAttributeDesignator(); + attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), + new IdentifierImpl(designator.getAttributeId()), + new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()), + designator.getIssuer(), + false); + attributeDataType = designator.getDataType(); + } else if (match.getAttributeSelector() != null && value != null) { + AttributeSelectorType selector = match.getAttributeSelector(); + attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), + new IdentifierImpl(selector.getContextSelectorId()), + new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()), + null, + false); + attributeDataType = selector.getDataType(); + } else { + logger.warn("NULL designator/selector or value for match."); + attributeDataType = "NA"; + } + + String functionName = getHumanFunction(match.getMatchId()); + + String succintIdentifier = extractLastIdentifier(attribute.getCategory().stringValue(), ":") + + ":" + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":"); + AttributeIdentifiers ai = new AttributeIdentifiers(attribute.getCategory().stringValue(), + attributeDataType, + attribute.getAttributeId().stringValue()); + this.attributeIdentifiersMap.put(succintIdentifier,ai); + + targetInHuman += "<i><a href=\"#" + succintIdentifier + "\">" + succintIdentifier + "</a></i> " + functionName + " "; + + int numAttributes = attribute.getValues().size(); + int count = 0; + for (AttributeValue<?> v: attribute.getValues()) { + count++; + if (v.getValue() instanceof Collection<?>) { + Collection<?> value_s = (Collection<?>) v.getValue(); + int numValues = value_s.size(); + int countValues = 0; + for (Object o : value_s) { + countValues++; + targetInHuman += " <I>" + o + "</I>"; + if (countValues < numValues) { + targetInHuman += ", or"; + } + } + } else { + targetInHuman += " <I>" + v.getValue() + "</I>"; + if (count < numAttributes) { + targetInHuman += ", or "; + } + } + } + + if (iterMatch.hasNext()) { + targetInHuman += " and "; + } + } // end iterMatch + if (matchList.size() > 1) { + targetInHuman += ")"; + } + } + if (iterAllOf.hasNext()) { + targetInHuman += " or "; + } + } // end iterAllOf + } + if (iterAnyOf.hasNext()) { + targetInHuman = "(" + targetInHuman + ")" + " or "; + } else { + if (anyOfList.size() > 1) { + targetInHuman += ")"; + } + } + } // end iterAnyOf + htmlOut.println(targetInHuman); + } + } + + private String getHumanFunction(String matchId) { + if (HtmlProcessor.function2human.containsKey(matchId)) { + return HtmlProcessor.function2human.get(matchId); + } + + FunctionDefinition function = PolicyController.getFunctionIDMap().get(matchId); + String functionName = function.getShortname(); + + if (logger.isDebugEnabled()) { + logger.debug(functionName + + ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]"); + } + + return extractLastIdentifier(removePrimitives(functionName), ":"); + } + + public String html() { + this.htmlOut.flush(); + return this.stringWriter.toString(); + } + + private String extractLastIdentifier(String in, String separator) { + int lastIndex = in.lastIndexOf(separator); + if (lastIndex < 0) + return in; + else + return in.substring(lastIndex+1); + } + + private String removePrimitives(String in) { + in = in.replace("string-", ""); + in = in.replace("integer-", ""); + in = in.replace("double-", ""); + in = in.replace("boolean-", ""); + return in; + } + + private String stringifyCondition(ConditionType condition) { + if (condition.getExpression() == null) { + return ""; + } + + return stringifyExpression(condition.getExpression().getValue()); + } + + private String stringifyExpression(Object expression) { + if (expression instanceof ApplyType) { + ApplyType apply = (ApplyType) expression; + FunctionDefinition function = PolicyController.getFunctionIDMap().get(apply.getFunctionId()); + String functionName = function.getShortname(); + + if (logger.isDebugEnabled()) { + logger.debug(functionName + + ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]"); + } + + if (functionName.contains("one-and-only")) { + if (logger.isDebugEnabled()) { + logger.debug("one-and-only found: " + functionName); + } + + List<JAXBElement<?>> exps = apply.getExpression(); + if (exps == null || exps.size() == 0) + return ""; + else { + String forResult = ""; + for (JAXBElement<?> e : exps) { + Object v = e.getValue(); + if (logger.isDebugEnabled()) { + logger.debug("one-and-only children: " + v); + } + if (v != null) { + // C: return stringifyExpression(v, result); + forResult += stringifyExpression(v); + } + } + return forResult; + } + } + + final int numExpr = (apply.getExpression() == null) ? -1 : apply.getExpression().size(); + if (numExpr <= 0) { + if (logger.isDebugEnabled()) { + logger.debug(functionName + " 0 expressions: " + numExpr); + } + return ""; + } else if (numExpr == 1) { + // eg: not + if (logger.isDebugEnabled()) { + logger.debug(functionName + " 1 expression: " + numExpr); + } + String applySubresult = ""; + for (JAXBElement<?> e : apply.getExpression()) { + Object v = e.getValue(); + if (v != null) { + applySubresult += this.stringifyExpression(e.getValue()); + } + } + return " " + removePrimitives(functionName) + " (" + applySubresult + ")"; + } else { + // > 1 arguments + if (logger.isDebugEnabled()) { + logger.debug(functionName + " > 1 expressions: " + numExpr); + } + String applySubresult = ""; + int exprCount = 0; + for (JAXBElement<?> e : apply.getExpression()) { + exprCount++; + Object ev = e.getValue(); + if (ev != null) { + if (ev instanceof ApplyType) { + if (((ApplyType) ev).getFunctionId().contains("one-and-only")) { + applySubresult += this.stringifyExpression(e.getValue()); + } else { + applySubresult += "(" + this.stringifyExpression(e.getValue()) + ")"; + } + } else { + applySubresult += this.stringifyExpression(e.getValue()); + } + + if (exprCount < numExpr) { + applySubresult += " " + removePrimitives(functionName) + " "; + } + } + } + return applySubresult; + } + } + if (expression instanceof AttributeDesignatorType) { + AttributeDesignatorType adt = (AttributeDesignatorType) expression; + + String succintIdentifier = extractLastIdentifier(adt.getCategory(), ":") + + ":" + extractLastIdentifier(adt.getAttributeId(), ":"); + AttributeIdentifiers ai = new AttributeIdentifiers(adt.getCategory(), + adt.getDataType(), + adt.getAttributeId()); + this.attributeIdentifiersMap.put(succintIdentifier,ai); + + return "<a href=\"#" + succintIdentifier + "\">" + succintIdentifier + "</a>"; + } + if (expression instanceof AttributeSelectorType) { + AttributeSelectorType ast = (AttributeSelectorType) expression; + + String attrName = ast.getPath(); + if (attrName == null || (attrName.length() == 0)) { + return ""; + } + + String textSelector = "/text()"; + if (attrName.endsWith(textSelector)) { + attrName = attrName.substring(0, attrName.length() - textSelector.length()); + } + + attrName = extractLastIdentifier(attrName, "/"); + attrName = extractLastIdentifier(attrName, ":"); + return " " + attrName; + } + if (expression instanceof AttributeValueType) { + AttributeValueType avt = (AttributeValueType) expression; + List<Object> content = avt.getContent(); + String value_s = ""; + for (Object o: content) { + value_s += " " + o.toString(); + } + return " " + value_s; + } + if (expression instanceof VariableReferenceType) { + // + // Really unknown - the variable may or may not have been defined + // + return " VARIABLEREF-NOT-HANDLED"; + } else { + throw new IllegalArgumentException("Unexpected input expression"); + } + } +} + + +class AttributeIdentifiers { + public final String category; + public String type; + public final String id; + + public AttributeIdentifiers(String category, String type, String id) { + this.category = category; + this.type = type; + this.id = id; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java new file mode 100644 index 000000000..c70e331d0 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java @@ -0,0 +1,226 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.components; + + +/* + * + */ +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Set; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.io.IOUtils; +import org.openecomp.policy.controller.PolicyController; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + + +public class PolicyImportWindow{ + + private static final Logger logger = FlexLogger.getLogger(PolicyImportWindow.class); + private static final int BUFFER_SIZE = 4096; + private static Path directory = PolicyController.getGitPath(); + private Path newfile = null; + private boolean succeeded = false; + public static String CONFIG_HOME = PolicyController.getConfigHome(); + public static String ACTION_HOME = PolicyController.getActionHome(); + private Boolean superadmin = false; + private ArrayList<String> xacmlFiles = new ArrayList<String>(); + /** + * The constructor should first build the main layout, set the + * composition root and then do any custom initialization. + * + * The constructor will not be automatically regenerated by the + * visual editor. + */ + + public OutputStream receiveUpload(String filename, String mimeType) { + + // + // Create its new full path + // + this.newfile = Paths.get(PolicyImportWindow.directory.toString(), filename); + // + // Does it already exist? + // + if (Files.exists(this.newfile)) { + return null; + } + // + // Try to create the output stream + // + try { + return new FileOutputStream(this.newfile.toFile()); + } catch (FileNotFoundException e) { + logger.error("Failed to create uploaded file", e); + } + return null; + } + + public void Upload(){ + TarArchiveEntry entry = null; + TarArchiveInputStream extractFile = null; + try { + extractFile = new TarArchiveInputStream (new FileInputStream(this.newfile.toFile())); + } catch (FileNotFoundException e1) { + e1.printStackTrace(); + } + //Create a loop to read every single entry in TAR file + try { + while ((entry = extractFile.getNextTarEntry()) != null) { + this.superadmin = true; + try{ + copyFileToLocation(extractFile, entry, xacmlFiles, null, superadmin); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception while Importing Polcies"+e); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + + + + + //Copy files to Directorys + public static void copyFileToLocation(TarArchiveInputStream extractFile, TarArchiveEntry entry, ArrayList<String> xacmlFiles, Set<String> finalScopes, Boolean superadminValue ) throws IOException{ + String individualFiles = ""; + int offset = 0; + FileOutputStream outputFile=null; + // Get the name of the file + if(superadminValue){ + individualFiles = entry.getName(); + }else{ + for(int i =0; i< finalScopes.size(); i++){ + if(entry.getName().startsWith(finalScopes.toArray()[i].toString())){ + individualFiles = entry.getName(); + } + } + } + + if(individualFiles.endsWith(".xls")){ + if(individualFiles.contains("\\")){ + individualFiles = individualFiles.replace("\\", File.separator); + }else if(individualFiles.contains("/")){ + individualFiles = individualFiles.replace("/", File.separator); + } + return; + } + + individualFiles = individualFiles.replace("/", File.separator); + individualFiles = individualFiles.replace("\\", File.separator); + + //Create the path with the entry name + String filePath = directory.toAbsolutePath() + File.separator + individualFiles; + String configPath = CONFIG_HOME + File.separator + individualFiles; + String actionPath = ACTION_HOME + File.separator + individualFiles; + logger.info("File Name in TAR File is: " + individualFiles); + logger.info("Xml directory file path: " + filePath); + logger.info("Config Home directory file path: " + configPath); + logger.info("Action Home directory file path: " + actionPath); + + + // Get Size of the file and create a byte array for the size + byte[] content = new byte[(int) entry.getSize()]; + + offset=0; + logger.info("File Name in TAR File is: " + individualFiles); + logger.info("Size of the File is: " + entry.getSize()); + // Read file from the archive into byte array + extractFile.read(content, offset, content.length - offset); + if (!entry.isDirectory()) { + if(!individualFiles.contains(".Config_") || !individualFiles.contains(".Action_")){ + // if the entry is a file, extracts it + String filePath1 = filePath.substring(0, filePath.lastIndexOf(File.separator)); + File newFile = new File(filePath1); + if(!(newFile.exists())) { + File dir = new File(filePath1); + dir.mkdir(); + extractFile(extractFile, filePath); + } + } + } else { + // if the entry is a directory, make the director + File dir = new File(filePath); + dir.mkdir(); + } + // Define OutputStream for writing the file + if(individualFiles.contains(".Config_")){ + outputFile=new FileOutputStream(new File(configPath)); + }else if(individualFiles.contains(".Action_")){ + outputFile=new FileOutputStream(new File(actionPath)); + }else{ + if(filePath != null){ + outputFile=new FileOutputStream(new File(filePath)); + xacmlFiles.add(filePath); + } + } + + // Use IOUtiles to write content of byte array to physical file + IOUtils.write(content,outputFile); + + // Close Output Stream + try { + outputFile.close(); + } catch (IOException e) { + logger.info("IOException:" +e); + e.printStackTrace(); + } + } + + private static void extractFile(TarArchiveInputStream extractFile, String filePath) throws IOException { + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = extractFile.read(bytesIn)) != -1) { + bos.write(bytesIn, 0, read); + } + bos.close(); + + } + + public Path getUploadedFile() { + if (this.succeeded) { + return this.newfile; + } + return null; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/conf/HibernateSession.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/conf/HibernateSession.java new file mode 100644 index 000000000..b3db51df4 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/conf/HibernateSession.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.conf; + +/* + * + * + * */ +import java.util.Properties; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.rest.jpa.SystemLogDB; + +@SuppressWarnings("deprecation") +public class HibernateSession{ + + private static SessionFactory logSessionFactory; + + static { + try { + Properties prop= new Properties(); + prop.setProperty("hibernate.connection.url", PolicyController.logdbUrl); + prop.setProperty("hibernate.connection.username", PolicyController.logdbUserName); + prop.setProperty("hibernate.connection.password", PolicyController.logdbPassword); + prop.setProperty("dialect", PolicyController.logdbDialect); + prop.setProperty("hibernate.connection.driver_class", PolicyController.logdbDriver); + prop.setProperty("show_sql", "false"); + logSessionFactory = new Configuration().addPackage("org.openecomp.policy.*").addProperties(prop) + .addAnnotatedClass(SystemLogDB.class).buildSessionFactory(); + } catch (Throwable ex) { + throw new ExceptionInInitializerError(ex); + } + } + public static Session getSession() throws HibernateException { + return logSessionFactory.openSession(); + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java new file mode 100644 index 000000000..0688846b4 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java @@ -0,0 +1,535 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBElement; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.FunctionDefinitionDao; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.dao.ActionPolicyDictDao; +import org.openecomp.policy.rest.jpa.ActionPolicyDict; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Controller +@RequestMapping({"/"}) +public class ActionPolicyController extends RestrictedBaseController{ + private static final Logger logger = FlexLogger.getLogger(ActionPolicyController.class); + + private static FunctionDefinitionDao functionDefinitionDao; + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static ActionPolicyDictDao actionPolciyDictDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private ActionPolicyController(RuleAlgorithmsDao ruleAlgorithmsDao, ActionPolicyDictDao actionPolciyDictDao, + PolicyVersionDao policyVersionDao, FunctionDefinitionDao functionDefinitionDao, WatchPolicyNotificationDao policyNotificationDao){ + ActionPolicyController.ruleAlgorithmsDao =ruleAlgorithmsDao; + ActionPolicyController.actionPolciyDictDao =actionPolciyDictDao; + ActionPolicyController.policyVersionDao =policyVersionDao; + ActionPolicyController.functionDefinitionDao = functionDefinitionDao; + ActionPolicyController.policyNotificationDao = policyNotificationDao; + } + + public ActionPolicyController(){} + + private String ruleID = ""; + private ArrayList<Object> attributeList; + protected LinkedList<Integer> ruleAlgoirthmTracker; + public static final String PERFORMER_ATTRIBUTEID = "performer"; + protected Map<String, String> performer = new HashMap<String, String>(); + private ArrayList<Object> ruleAlgorithmList; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + + @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("functionDefinitionDatas", mapper.writeValueAsString(functionDefinitionDao.getFunctionDefinitionByName())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + logger.equals(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e); + } + } + + @RequestMapping(value={"/policyController/save_Actionpolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveActionPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Action_" + policyData.getPolicyName(); + List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map<String, String> successMap = new HashMap<String, String>(); + Map<String, String> attributeMap = new HashMap<String, String>(); + + List<String> dynamicRuleAlgorithmLabels = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmCombo = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmField1 = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmField2 = new LinkedList<String>(); + + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString(); + attributeMap.put(key, value); + } + } + } + + if(policyData.getRuleAlgorithmschoices().size() > 0){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); + String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); + dynamicRuleAlgorithmLabels.add(label); + dynamicRuleAlgorithmField1.add(key); + dynamicRuleAlgorithmCombo.add(rule); + dynamicRuleAlgorithmField2.add(value); + } + } + } + + String actionDictValue = policyData.getActionAttributeValue(); + ActionPolicyDict jsonData = ((ActionPolicyDict) actionPolciyDictDao.getActionEntityDatabyId(actionDictValue)); + String actionBodyString = jsonData.getBody(); + String actionDictHeader = jsonData.getHeader(); + String actionDictType = jsonData.getType(); + String actionDictUrl = jsonData.getUrl(); + String actionDictMethod = jsonData.getMethod(); + policyData.setActionDictHeader(actionDictHeader); + policyData.setActionDictType(actionDictType); + policyData.setActionDictUrl(actionDictUrl); + policyData.setActionDictMethod(actionDictMethod); + policyData.setActionAttribute(actionDictValue); + policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); + policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + if (actionBodyString != null) { + policyData.setActionBody(actionBodyString); + } + policyData.setDynamicFieldConfigAttributes(attributeMap); + + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + 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; + } + + public void PrePopulateActionPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList<Object>(); + ruleAlgorithmList = new ArrayList<Object>(); + performer.put("PDP", "PDPAction"); + performer.put("PEP", "PEPAction"); + + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1, policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target != null) { + // under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AntOfType we have AllOfType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOfType we have Mathch. + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic componet at index 0. + Map<String, String> attribute = new HashMap<String, String>(); + attribute.put("option", attributeId); + attribute.put("number", value); + attributeList.add(attribute); + } + } + policyAdapter.setAttributes(attributeList); + } + } + } + } + + List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + // Under rule we have Condition and obligation. + for (Object o : ruleList) { + if (o instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + ruleID = ((RuleType) o).getRuleId(); + ConditionType condition = ((RuleType) o).getCondition(); + ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); + if (condition != null) { + int index = 0; + ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); + ruleAlgoirthmTracker = new LinkedList<Integer>(); + // Populating Rule Algorithms starting from compound. + prePopulateCompoundRuleAlgorithm(index, actionApply); + } + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + // get the Obligation data under the rule for Form elements. + if (obligations != null) { + // Under the obligationExpressions we have obligationExpression. + List<ObligationExpressionType> obligationList = obligations.getObligationExpression(); + if (obligationList != null) { + Iterator<ObligationExpressionType> iterObligation = obligationList.iterator(); + while (iterObligation.hasNext()) { + ObligationExpressionType obligation = iterObligation.next(); + policyAdapter.setActionAttributeValue(obligation.getObligationId()); + // Under the obligationExpression we have attributeAssignmentExpression. + List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation.getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionList != null) { + Iterator<AttributeAssignmentExpressionType> iterAttributeAssignmentExpression = attributeAssignmentExpressionList.iterator(); + while (iterAttributeAssignmentExpression.hasNext()) { + AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression.next(); + String attributeID = attributeAssignmentExpression.getAttributeId(); + AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression.getExpression().getValue(); + if (attributeID.equals(PERFORMER_ATTRIBUTEID)) { + for (String key : performer.keySet()) { + String keyValue = performer.get(key); + if (keyValue.equals(attributeValue.getContent().get(0))) { + policyAdapter.setActionPerformer(key); + } + } + } + } + } + } + } + } + } + } + } + } + } + + private int prePopulateCompoundRuleAlgorithm(int index, ApplyType actionApply) { + boolean isCompoundRule = true; + List<JAXBElement<?>> jaxbActionTypes = actionApply.getExpression(); + for (JAXBElement<?> jaxbElement : jaxbActionTypes) { + // If There is Attribute Value under Action Type that means we came to the final child + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating rule algoirthm: " + index); + } + // Check to see if Attribute Value exists, if yes then it is not a compound rule + if (jaxbElement.getValue() instanceof AttributeValueType) { + prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes); + ruleAlgoirthmTracker.addLast(index); + isCompoundRule = false; + index++; + } + } + if (isCompoundRule) { + // As it's compound rule, Get the Apply types + for (JAXBElement<?> jaxbElement : jaxbActionTypes) { + ApplyType innerActionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateCompoundRuleAlgorithm(index, innerActionApply); + } + // Populate combo box + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating Compound rule algorithm: " + index); + } + Map<String, String> rule = new HashMap<String, String>(); + for (String key : PolicyController.getDropDownMap().keySet()) { + String keyValue = PolicyController.getDropDownMap().get(key); + if (keyValue.equals(actionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", key); + } + } + rule.put("id", "A" + (index +1)); + // Populate Key and values for Compound Rule + rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 )); + ruleAlgoirthmTracker.removeLast(); + rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmList.add(rule); + index++; + } + return index; + } + + private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List<JAXBElement<?>> jaxbActionTypes) { + Map<String, String> ruleMap = new HashMap<String, String>(); + ruleMap.put("id", "A" + (index +1)); + // Populate combo box + Map<String, String> dropDownMap = PolicyController.getDropDownMap(); + for (String key : dropDownMap.keySet()) { + String keyValue = dropDownMap.get(key); + if (keyValue.equals(actionApply.getFunctionId())) { + ruleMap.put("dynamicRuleAlgorithmCombo", key); + } + } + // Populate the key and value fields + // Rule Attribute added as key + if ((jaxbActionTypes.get(0).getValue()) instanceof ApplyType) { + // Get from Attribute Designator + ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue(); + List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + // Rule Attribute added as value + else if (((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType)) { + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + + ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); + List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + } + ruleAlgorithmList.add(ruleMap); + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AdminTabController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AdminTabController.java new file mode 100644 index 000000000..67c2d3080 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AdminTabController.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.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.policy.dao.GlobalRoleSettingsDao; +import org.openecomp.policy.rest.jpa.GlobalRoleSettings; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +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 AdminTabController extends RestrictedBaseController{ + + @Autowired + GlobalRoleSettingsDao globalRoleSettingsDao; + + + + @RequestMapping(value={"/get_LockDownData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("lockdowndata", mapper.writeValueAsString(globalRoleSettingsDao.getGlobalRoleSettings())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/adminTabController/save_LockDownValue.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveAdminTabLockdownValue(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()); + GlobalRoleSettings globalRole = mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); + globalRole.setRole("super-admin"); + globalRoleSettingsDao.update(globalRole); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(this.globalRoleSettingsDao.getGlobalRoleSettings()); + JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + 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-app/src/main/java/org/openecomp/policy/controller/AutoPushController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AutoPushController.java new file mode 100644 index 000000000..699d8ed00 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AutoPushController.java @@ -0,0 +1,433 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URI; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.FilenameUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.policy.adapter.AutoPushTabAdapter; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.model.PDPGroupContainer; +import org.openecomp.policy.model.PDPPolicyContainer; +import org.openecomp.policy.model.Roles; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; + +import com.att.research.xacml.api.pap.PAPException; +//import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPolicy; +import org.openecomp.policy.xacml.std.pap.StdPDPGroup; +import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@Controller +@RequestMapping({"/"}) +public class AutoPushController extends RestrictedBaseController{ + + private static final Logger logger = FlexLogger.getLogger(AutoPushController.class); + + private PDPGroupContainer container; + protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>()); + + private static PDPPolicyContainer policyContainer; + Set<PDPPolicy> selectedPolicies; + + @Autowired + PolicyVersionDao policyVersionDao; + + public synchronized void refreshGroups() { + synchronized(this.groups) { + this.groups.clear(); + try { + this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups()); + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + } + + } + } + + @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){ + try{ + Path gitPath = PolicyController.getGitPath().toAbsolutePath(); + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{data: " + readFileRepository(gitPath,0,0,request).toString() + "}"); + out.write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @SuppressWarnings("rawtypes") + public JSONArray readFileRepository(Path path, int id, int parentid, HttpServletRequest request){ + Set<String> scopes = null; + List<String> roles = null; + String userId = null; + try { + userId = UserUtils.getUserIdFromCookie(request); + } catch (Exception e) { + logger.error("Exception Occured while reading userid from cookie" +e); + } + JSONArray fileJSONArray = new JSONArray(); + File root = new File(path.toString()); + if(parentid==0 ){ + parentid = 1; + } + List<Roles> userRoles = PolicyController.getRoles(userId); + roles = new ArrayList<String>(); + scopes = new HashSet<String>(); + for(Roles userRole: userRoles){ + roles.add(userRole.getRole()); + scopes.add(userRole.getScope()); + } + + for ( File file : root.listFiles()){ + if (!(file.toString().contains(".git") || file.equals(".DS_Store"))) { + if(file.isDirectory()){ + JSONObject el = new JSONObject(); + String fileName = file.getName().toString(); + el.put("categoryId", id+1); + el.put("name", fileName); + el.put("dateModified", lastModified(file)); + el.put("filePath", file.getPath()); + el.put("parentCategoryId", parentid); + el.put("files",readFileRepository(file.toPath(),id+1, id+1, request)); + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) { + fileJSONArray.put(el); + }else{ + String filePath = file.getPath().toString(); + int startIndex = filePath.indexOf("repository") + 11; + filePath = filePath.substring(startIndex, filePath.length()); + if (scopes.contains(filePath)) { + fileJSONArray.put(el); + } + } + }else{ + JSONObject el = new JSONObject(); + String policyName = ""; + String version = ""; + String fileName = file.getName().toString(); + if(fileName.endsWith(".xml")){ + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + //Query the database + String parent = file.toString().substring(file.toString().indexOf("repository")+ 11); + parent = FilenameUtils.removeExtension(parent); + version = parent.substring(parent.indexOf(".")+1); + policyName = parent.substring(0, parent.lastIndexOf(".")); + if(policyName.contains("\\")){ + String scope = policyName.substring(0, policyName.lastIndexOf("\\")); + policyName = scope + "\\" + policyName.substring(policyName.lastIndexOf("\\")); + } + } + el.put("categoryId", id+1); + el.put("name", fileName); + el.put("parentCategoryId", parentid); + el.put("dateModified", lastModified(file)); + el.put("version", version); + el.put("filePath", file.getPath()); + el.put("files",new ArrayList()); + String query = "from PolicyVersion where POLICY_NAME ='" +policyName+"' and ACTIVE_VERSION ='"+version+"'"; + Boolean active = PolicyController.getActivePolicy(query); + if(active){ + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) { + fileJSONArray.put(el); + }else{ + String filePath = file.getPath().toString(); + int startIndex = filePath.indexOf("repository") + 11; + filePath = filePath.substring(startIndex, filePath.length()); + filePath = filePath.substring(0, filePath.lastIndexOf(File.separator)); + if (scopes.contains(filePath)) { + fileJSONArray.put(el); + } + } + } + } + } + } + return fileJSONArray; + } + + public Date lastModified(File file) { + return new Date(file.lastModified()); + } + + public String getVersion(File file) { + try { + return XACMLPolicyScanner.getVersion(Paths.get(file.getAbsolutePath())); + } catch (IOException e) { + return ""; + } + } + + public String getDomain(File file) { + String filePath = file.getAbsolutePath(); + int startIndex = filePath.indexOf("repository") + 11; + return filePath.substring(startIndex, filePath.length()); + } + + + @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { + try { + ArrayList<Object> selectedPDPS = new ArrayList<Object>(); + ArrayList<File> selectedPoliciesInUI = new ArrayList<File>(); + this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups()); + ObjectMapper mapper = new ObjectMapper(); + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + AutoPushTabAdapter adapter = (AutoPushTabAdapter) mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class); + for (Object pdpGroupId : adapter.getPdpDatas()) { + LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId; + for(EcompPDPGroup pdpGroup : this.groups){ + if(pdpGroup.getId().equals(selectedPDP.get("id"))){ + selectedPDPS.add(pdpGroup); + } + } + } + + for (Object policyId : adapter.getPolicyDatas()) { + LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId; + Path file = Paths.get(selected.get("filePath").toString()); + selectedPoliciesInUI.add(file.toFile()); + } + + for (Object pdpDestinationGroupId : selectedPDPS) { + Set<PDPPolicy> currentPoliciesInGroup = new HashSet<PDPPolicy>(); + Set<PDPPolicy> selectedPolicies = new HashSet<PDPPolicy>(); + for (File policyId : selectedPoliciesInUI) { + logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId); + // + // Get the current selection + File selectedItem = policyId; + // + assert (selectedItem != null); + if (selectedItem.isDirectory()) { + //AdminNotification.warn("Select only the Policy"); + return null; + } + // create the id of the target file + // Our standard for file naming is: + // <domain>.<filename>.<version>.xml + // since the file name usually has a ".xml", we need to strip + // that + // before adding the other parts + String name = selectedItem.getName(); + if(name.endsWith(".xml")){ + name = name.substring(0, name.length() - 4); + name = name.substring(0, name.lastIndexOf(".")); + } + String id = name; + if (id.endsWith(".xml")) { + id = id.substring(0, id.length() - 4); + id = id.substring(0, id.lastIndexOf(".")); + } + // add on the version string + String version = getVersion(selectedItem); + id += "." + version; + // put the .xml on the end + id += ".xml"; + // track on the domain in front. Do this one level at a time + // until we + // reach one of the roots + String domain = getDomain(selectedItem); + String mainDomain = domain.substring(0, domain.lastIndexOf(File.separator) ); + logger.info("print the main domain value"+mainDomain); + String path = mainDomain.replace('\\', '.'); + if(path.contains("/")){ + path = mainDomain.replace('/', '.'); + logger.info("print the path:" +path); + } + id = path + "." + id; + // Default policy to be Root policy; user can change to deferred + // later + URI selectedURI = selectedItem.toURI(); + StdPDPPolicy selectedPolicy = null; + try { + // + // Create the policy + selectedPolicy = new StdPDPPolicy(id, true, name, selectedURI); + } catch (IOException e) { + logger.error("Unable to create policy '" + id + "': "+ e.getMessage()); + //AdminNotification.warn("Unable to create policy '" + id + "': " + e.getMessage()); + } + StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId; + if (selectedPolicy != null) { + // Add Current policies from container + for (EcompPDPGroup group : container.getGroups()) { + if (group.getId().equals(selectedGroup.getId())) { + currentPoliciesInGroup.addAll(group.getPolicies()); + } + } + // copy policy to PAP + try { + PolicyController.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId); + } catch (PAPException e) { + e.printStackTrace(); + return null; + } + selectedPolicies.add(selectedPolicy); + } + } + StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId; + StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory()); + updatedGroupObject.setEcompPdps(pdpGroup.getEcompPdps()); + updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs()); + updatedGroupObject.setStatus(pdpGroup.getStatus()); + + // replace the original set of Policies with the set from the + // container (possibly modified by the user) + // do not allow multiple copies of same policy + Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator(); + logger.debug("policyIterator....." + selectedPolicies); + while (policyIterator.hasNext()) { + PDPPolicy existingPolicy = policyIterator.next(); + for (PDPPolicy selPolicy : selectedPolicies) { + if (selPolicy.getName().equals(existingPolicy.getName())) { + if (selPolicy.getVersion().equals(existingPolicy.getVersion())) { + if (selPolicy.getId().equals(existingPolicy.getId())) { + policyIterator.remove(); + logger.debug("Removing policy: " + selPolicy); + break; + } + } else { + policyIterator.remove(); + logger.debug("Removing Old Policy version: "+ selPolicy); + break; + } + } + } + } + + currentPoliciesInGroup.addAll(selectedPolicies); + updatedGroupObject.setPolicies(currentPoliciesInGroup); + this.container.updateGroup(updatedGroupObject); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + 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={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { + try { + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class); + JsonNode removePolicyData = root.get("data"); + policyContainer = new PDPPolicyContainer(group); + if(removePolicyData.size() > 0){ + for(int i = 0 ; i < removePolicyData.size(); i++){ + String data = removePolicyData.get(i).toString(); + AutoPushController.policyContainer.removeItem(data); + } + Set<PDPPolicy> changedPolicies = new HashSet<PDPPolicy>(); + changedPolicies.addAll((Collection<PDPPolicy>) AutoPushController.policyContainer.getItemIds()); + StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null); + updatedGroupObject.setPolicies(changedPolicies); + updatedGroupObject.setEcompPdps(group.getEcompPdps()); + updatedGroupObject.setPipConfigs(group.getPipConfigs()); + updatedGroupObject.setStatus(group.getStatus()); + this.container.updateGroup(updatedGroupObject); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + + 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; + } + +}
\ No newline at end of file diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java new file mode 100644 index 000000000..7a2b24e84 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java @@ -0,0 +1,723 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBElement; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.dao.BRMSParamTemplateDao; +import org.openecomp.policy.rest.jpa.BRMSParamTemplate; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Controller +@RequestMapping("/") +public class CreateBRMSParamController extends RestrictedBaseController { + private static final Logger logger = FlexLogger.getLogger(CreateBRMSParamController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static BRMSParamTemplateDao bRMSParamTemplateDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreateBRMSParamController(RuleAlgorithmsDao ruleAlgorithmsDao, BRMSParamTemplateDao bRMSParamTemplateDao, PolicyVersionDao policyVersionDao, + WatchPolicyNotificationDao policyNotificationDao){ + CreateBRMSParamController.policyVersionDao = policyVersionDao; + CreateBRMSParamController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateBRMSParamController.bRMSParamTemplateDao = bRMSParamTemplateDao; + CreateBRMSParamController.policyNotificationDao = policyNotificationDao; + } + + public CreateBRMSParamController(){} + protected PolicyAdapter policyAdapter = null; + private ArrayList<Object> attributeList; + private String ruleID = ""; + + private HashMap<String, String> dynamicLayoutMap; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + dynamicLayoutMap = new HashMap<String, String>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String rule = findRule(root.get("policyData").toString().replaceAll("^\"|\"$", "")); + generateUI(rule); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(dynamicLayoutMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + + protected String findRule(String ruleTemplate) { + for (BRMSParamTemplate bRMSParamTemplate: bRMSParamTemplateDao.getBRMSParamTemplateData()){ + if(bRMSParamTemplate.getRuleName().equals(ruleTemplate)){ + return bRMSParamTemplate.getRule(); + } + } + return null; + } + + protected void generateUI(String rule) { + if(rule!=null){ + try { + String params = ""; + Boolean flag = false; + Boolean comment = false; + String lines[] = rule.split("\n"); + for(String line : lines){ + if (line.isEmpty() || line.startsWith("//")) { + continue; + } + if (line.startsWith("/*")) { + comment = true; + continue; + } + if (line.contains("//")) { + line = line.split("\\/\\/")[0]; + } + if (line.contains("/*")) { + comment = true; + if (line.contains("*/")) { + try { + comment = false; + line = line.split("\\/\\*")[0] + + line.split("\\*\\/")[1].replace("*/", ""); + } catch (Exception e) { + line = line.split("\\/\\*")[0]; + } + } else { + line = line.split("\\/\\*")[0]; + } + } + if (line.contains("*/")) { + comment = false; + try { + line = line.split("\\*\\/")[1].replace("*/", ""); + } catch (Exception e) { + line = ""; + } + } + if (comment) { + continue; + } + if (flag) { + params = params + line; + } + if (line.contains("declare Params")) { + params = params + line; + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = params.replace("declare Params", "").replace("end", "") + .replaceAll("\\s+", ""); + String[] components = params.split(":"); + String caption = ""; + for (int i = 0; i < components.length; i++) { + String type = ""; + if (i == 0) { + caption = components[i]; + } + if(caption.equals("")){ + break; + } + String nextComponent = ""; + try { + nextComponent = components[i + 1]; + } catch (Exception e) { + nextComponent = components[i]; + } + if (nextComponent.startsWith("String")) { + type = "String"; + createField(caption, type); + caption = nextComponent.replace("String", ""); + } else if (nextComponent.startsWith("int")) { + type = "int"; + createField(caption, type); + caption = nextComponent.replace("int", ""); + } + } + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + } + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + private void createField(String caption, String type) { + dynamicLayoutMap.put(caption, type); + } + + @RequestMapping(value={"/policyController/save_BRMSParamPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveBRMSParamPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_BRMS_Param_" + policyData.getPolicyName(); + List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map<String, String> successMap = new HashMap<String, String>(); + Map<String, String> attributeMap = new HashMap<String, String>(); + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString(); + attributeMap.put(key, value); + } + } + } + + policyData.setEcompName("DROOLS"); + policyData.setConfigName("BRMS_PARAM_RULE"); + policyData.setDynamicFieldConfigAttributes(attributeMap); + //convert drl rule and UI parameters into a map + Map<String, String> drlRuleAndUIParams = new HashMap<String, String>(); + // If there is any dynamic field create the matches here + String key="templateName"; + String value=(String) policyData.getRuleName(); + drlRuleAndUIParams.put(key, value); + System.out.println(policyData.getRuleData()); + if(policyData.getRuleData().size() > 0){ + for(Object keyValue: policyData.getRuleData().keySet()){ + drlRuleAndUIParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString()); + } + } + policyData.setBRMSParamBody(drlRuleAndUIParams); + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + 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; + } + + public void PrePopulateBRMSParamPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList<Object>(); + dynamicLayoutMap = new HashMap<String, String>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + // policy name value is the policy name without any prefix and + // Extensions. + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") +11, policyAdapter.getPolicyName().lastIndexOf(".")); + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Set Attributes. + AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); + for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){ + for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){ + if(attributeAssignment.getAttributeId().startsWith("key:")){ + Map<String, String> attribute = new HashMap<String, String>(); + String key = attributeAssignment.getAttributeId().replace("key:", ""); + attribute.put("key", key); + JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression(); + String value = (String) attributevalue.getValue().getContent().get(0); + attribute.put("value", value); + attributeList.add(attribute); + } + } + policyAdapter.setAttributes(attributeList); + } + String ruleConfigName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + ".txt"; + policyAdapter.setConfigBodyPath(ruleConfigName); + paramUIGenerate(policyAdapter); + // Get the target data under policy. + policyAdapter.setDynamicLayoutMap(dynamicLayoutMap); + if(policyAdapter.getDynamicLayoutMap().size() > 0){ + LinkedHashMap<String,String> drlRule = new LinkedHashMap<String, String>(); + for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){ + drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue).toString()); + } + policyAdapter.setRuleData(drlRule); + } + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + int index = 0; + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + + if (index == 3){ + policyAdapter.setRiskType(value); + } + + if (index == 4){ + policyAdapter.setRiskLevel(value); + } + + if (index == 5){ + policyAdapter.setGuard(value); + } + if (index == 6 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + + index++; + } + } + } + } + } + } + } + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + // This method generates the UI from rule configuration + private void paramUIGenerate(PolicyAdapter policyAdapter) { + String fileLocation = null; + String fileName = policyAdapter.getConfigBodyPath(); + if (fileName != null) { + fileLocation = PolicyController.getConfigHome(); + } + if (logger.isDebugEnabled()) { + logger.debug("Attempting to read file from the location: " + fileLocation); + } + if (fileLocation == null) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error with the FileName: " + fileName); + return; + } + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName) + && file.toString().endsWith(".txt")) { + // Reading the file + try { + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage()); + } + String params = ""; + Boolean flag = false; + Boolean comment = false; + for (String line : Files.readAllLines(Paths.get(file.toString()))) { + if (line.isEmpty() || line.startsWith("//")) { + continue; + } + if(line.contains("<$%BRMSParamTemplate=")){ + String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>")); + value = value.replace("<$%BRMSParamTemplate=", ""); + policyAdapter.setRuleName(value); + } + if (line.startsWith("/*")) { + comment = true; + continue; + } + if (line.contains("//")) { + if(!(line.contains("http://") || line.contains("https://"))){ + line = line.split("\\/\\/")[0]; + } + } + if (line.contains("/*")) { + comment = true; + if (line.contains("*/")) { + try { + comment = false; + line = line.split("\\/\\*")[0] + + line.split("\\*\\/")[1].replace( + "*/", ""); + } catch (Exception e) { + line = line.split("\\/\\*")[0]; + } + } else { + line = line.split("\\/\\*")[0]; + } + } + if (line.contains("*/")) { + comment = false; + try { + line = line.split("\\*\\/")[1] + .replace("*/", ""); + } catch (Exception e) { + line = ""; + } + } + if (comment) { + continue; + } + if (flag) { + params = params + line; + } + if (line.contains("rule \"Params\"")) { + params = params + line; + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = params.replaceAll("\\s+", "").replace("rule\"Params\"salience1000whenthenParamsparams=newParams();","") + .replace("insert(params);end", "") + .replace("params.set", ""); + String[] components = params.split(";"); + if(components!= null && components.length > 0){ + for (int i = 0; i < components.length; i++) { + String value = null; + String caption = components[i].substring(0, + components[i].indexOf("(")); + caption = caption.substring(0, 1).toLowerCase() + caption.substring(1); + if (components[i].contains("(\"")) { + value = components[i] + .substring(components[i].indexOf("(\""), + components[i].indexOf("\")")) + .replace("(\"", "").replace("\")", ""); + } else { + value = components[i] + .substring(components[i].indexOf("("), + components[i].indexOf(")")) + .replace("(", "").replace(")", ""); + } + dynamicLayoutMap.put(caption, value); + + } + } + } catch (FileNotFoundException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); + } catch (IOException e1) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e1.getMessage()); + } + } + } + } + + // set View Rule + @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView setViewRule(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()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + + String body = ""; + + body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " + + "<$%BRMSParamTemplate=" + policyData.getRuleName() + "%$> \n */ \n"; + body = body + findRule((String) policyData.getRuleName()) + "\n"; + String generatedRule = "rule \"Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();"; + + if(policyData.getRuleData().size() > 0){ + for(Object keyValue: policyData.getRuleData().keySet()){ + String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1); + if (keyValue.equals("String")) { + generatedRule = generatedRule + "\n\t\tparams.set" + + key + "(\"" + + policyData.getRuleData().get(keyValue).toString() + "\");"; + } else { + generatedRule = generatedRule + "\n\t\tparams.set" + + key + "(" + + policyData.getRuleData().get(keyValue).toString() + ");"; + } + } + } + generatedRule = generatedRule + + "\n\t\tinsert(params);\nend"; + logger.info("New rule generated with :" + generatedRule); + body = body + generatedRule; + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(body); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + return null; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java new file mode 100644 index 000000000..6dcd8400b --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java @@ -0,0 +1,440 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBElement; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Controller +@RequestMapping("/") +public class CreateBRMSRawController extends RestrictedBaseController { + + private static final Logger logger = FlexLogger.getLogger(CreateBRMSRawController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreateBRMSRawController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){ + CreateBRMSRawController.policyVersionDao = policyVersionDao; + CreateBRMSRawController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateBRMSRawController.policyNotificationDao = policyNotificationDao; + } + + public CreateBRMSRawController(){} + protected PolicyAdapter policyAdapter = null; + private ArrayList<Object> attributeList; + private String ruleID = ""; + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + + + @RequestMapping(value={"/policyController/save_BRMSRawPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveBRMSRawPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_BRMS_Raw_" + policyData.getPolicyName(); + List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map<String, String> successMap = new HashMap<String, String>(); + Map<String, String> attributeMap = new HashMap<String, String>(); + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString(); + attributeMap.put(key, value); + } + } + } + + + policyData.setEcompName("DROOLS"); + policyData.setConfigName("BRMS_RAW_RULE"); + policyData.setDynamicFieldConfigAttributes(attributeMap); + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + 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; + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + public void PrePopulateBRMSRawPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList<Object>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + // policy name value is the policy name without any prefix and + // Extensions. + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") +9, policyAdapter.getPolicyName().lastIndexOf(".")); + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Set Attributes. + AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); + for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){ + for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){ + if(attributeAssignment.getAttributeId().startsWith("key:")){ + Map<String, String> attribute = new HashMap<String, String>(); + String key = attributeAssignment.getAttributeId().replace("key:", ""); + attribute.put("key", key); + JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression(); + String value = (String) attributevalue.getValue().getContent().get(0); + attribute.put("value", value); + attributeList.add(attribute); + } + } + policyAdapter.setAttributes(attributeList); + } + String ruleConfigName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + "."; + policyAdapter.setConfigBodyPath(ruleConfigName); + // Get the target data under policy. + policyAdapter.setConfigBodyData(readFile(policyAdapter)); + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + int index = 0; + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + + if (index == 3){ + policyAdapter.setRiskType(value); + } + + if (index == 4){ + policyAdapter.setRiskLevel(value); + } + + if (index == 5){ + policyAdapter.setGuard(value); + } + if (index == 6 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + + index++; + } + } + } + } + } + } + } + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + // Here we are reading the configurations file + protected String readFile(PolicyAdapter policyAdapter) { + String fileLocation = null; + String fileName = policyAdapter.getConfigBodyPath(); + if (fileName != null ) { + fileLocation = PolicyController.getConfigHome(); + } + if (fileLocation == null) { + return fileLocation; + } + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName) && file.toString().endsWith(".txt")) { + // Reading the file + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + return sb.toString(); + } catch (FileNotFoundException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); + } catch (IOException e1) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e1.getMessage()); + } + } + } + return null; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java new file mode 100644 index 000000000..b41f7e0ef --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java @@ -0,0 +1,889 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonReader; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.ClosedLoopFaultBody; +import org.openecomp.policy.adapter.ClosedLoopFaultTriggerUISignatures; +import org.openecomp.policy.adapter.ClosedLoopSignatures; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.dao.VarbindDictionaryDao; +import org.openecomp.policy.rest.jpa.EcompName; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.policy.rest.jpa.VarbindDictionary; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreateClosedLoopFaultController extends RestrictedBaseController{ + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static VarbindDictionaryDao varbindDictionaryDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreateClosedLoopFaultController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, VarbindDictionaryDao varbindDictionaryDao, + WatchPolicyNotificationDao policyNotificationDao){ + CreateClosedLoopFaultController.policyVersionDao = policyVersionDao; + CreateClosedLoopFaultController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateClosedLoopFaultController.varbindDictionaryDao = varbindDictionaryDao; + CreateClosedLoopFaultController.policyNotificationDao = policyNotificationDao; + } + + public CreateClosedLoopFaultController(){} + protected PolicyAdapter policyAdapter = null; + private String ruleID = ""; + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/policyController/save_Faultpolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveFaultPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + TrapDatas trapDatas = mapper.readValue(root.get("trapData").toString(), TrapDatas.class); + TrapDatas faultDatas = mapper.readValue(root.get("faultData").toString(), TrapDatas.class); + ClosedLoopGridJSONData policyJsonData = mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class); + ClosedLoopFaultBody jsonBody = mapper.readValue(root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + ArrayList<Object> trapSignatureDatas = new ArrayList<Object>(); + if(trapDatas.getTrap1() != null){ + trapSignatureDatas.add(trapDatas); + } + ArrayList<Object> faultSignatureDatas = new ArrayList<Object>(); + if(faultDatas.getTrap1() != null){ + faultSignatureDatas.add(faultDatas); + } + + String resultBody = ""; + if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){ + resultBody = resultBody + "("; + for(int i = policyJsonData.getConnecttriggerSignatures().size()-1; i>=0 ; i--){ + String connectBody = connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(), trapSignatureDatas.get(0)); + resultBody = resultBody + connectBody; + } + resultBody = resultBody + ")"; + }else{ + if(!trapSignatureDatas.isEmpty()){ + resultBody = callTrap("nill", trapSignatureDatas.get(0)); + } + } + ClosedLoopSignatures triggerSignatures = new ClosedLoopSignatures(); + triggerSignatures.setSignatures(resultBody); + if(policyData.getClearTimeOut() != null){ + triggerSignatures.setTimeWindow(Integer.parseInt(policyData.getClearTimeOut())); + triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge())); + ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures(); + if(!trapSignatureDatas.isEmpty()){ + uiTriggerSignatures.setSignatures(getUITriggerSignature("Trap", trapSignatureDatas.get(0))); + if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){ + uiTriggerSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures())); + } + } + jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures); + jsonBody.setTriggerTimeWindowUsedForUI(Integer.parseInt(policyData.getClearTimeOut())); + jsonBody.setTrapMaxAgeUsedForUI(Integer.parseInt(policyData.getTrapMaxAge())); + } + + jsonBody.setTriggerSignatures(triggerSignatures); + String faultBody = ""; + if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){ + faultBody = faultBody + "("; + for(int i = policyJsonData.getConnectVerificationSignatures().size()-1; i>=0 ; i--){ + String connectBody = connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(), faultSignatureDatas.get(0)); + faultBody = faultBody + connectBody; + } + faultBody = faultBody + ")"; + }else{ + if(!faultSignatureDatas.isEmpty()){ + faultBody = callTrap("nill", faultSignatureDatas.get(0)); + } + } + ClosedLoopSignatures faultSignatures = new ClosedLoopSignatures(); + faultSignatures.setSignatures(faultBody); + if(policyData.getVerificationclearTimeOut() != null){ + faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut())); + ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures(); + if(!faultSignatureDatas.isEmpty()){ + uifaultSignatures.setSignatures(getUITriggerSignature("Fault", faultSignatureDatas.get(0))); + if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){ + uifaultSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnectVerificationSignatures())); + } + } + + jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures); + jsonBody.setVerfificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut())); + } + jsonBody.setVerificationSignatures(faultSignatures); + ObjectWriter om = new ObjectMapper().writer(); + String json = om.writeValueAsString(jsonBody); + policyData.setJsonBody(json); + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_Fault_" + policyData.getPolicyName(); + List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map<String, String> successMap = new HashMap<String, String>(); + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List<RuleAlgorithms> ruleAlgorithsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List<PolicyVersion> versionlist = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionlist.size() > 0) { + for(int i = 0; i < versionlist.size(); i++) { + PolicyVersion entityItem = versionlist.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + 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; + } + + //connect traps data set to JSON Body as String + @SuppressWarnings("rawtypes") + private String getUIConnectTraps(ArrayList<Object> connectTrapSignatures) { + String resultBody = ""; + String connectMainBody = ""; + for(int j = 0; j < connectTrapSignatures.size(); j++){ + Map<String, String> connectTraps = (Map<String, String>)connectTrapSignatures.get(j); + String connectBody = ""; + Object object = connectTraps; + if(object instanceof LinkedHashMap<?, ?>){ + String notBox = ""; + if(((LinkedHashMap) object).keySet().contains("notBox")){ + notBox = ((LinkedHashMap) object).get("notBox").toString(); + } + String connectTrap1 = ((LinkedHashMap) object).get("connectTrap1").toString(); + String trapCount1 = ((LinkedHashMap) object).get("trapCount1").toString(); + String operatorBox = ((LinkedHashMap) object).get("operatorBox").toString(); + String connectTrap2 = ((LinkedHashMap) object).get("connectTrap2").toString(); + String trapCount2 = ((LinkedHashMap) object).get("trapCount2").toString(); + connectBody = notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!" + connectTrap2 + "@!" + trapCount2 + "#!?!"; + } + resultBody = resultBody + connectBody; + } + connectMainBody = connectMainBody + resultBody; + return connectMainBody; + } + + + + // get Trigger signature from JSON body + private String getUITriggerSignature(String trap, Object object2) { + String triggerBody = ""; + TrapDatas trapDatas = (TrapDatas) object2; + ArrayList<Object> attributeList = new ArrayList<>(); + // Read the Trap + if(trap.startsWith("Trap")){ + if(trapDatas.getTrap1()!= null){ + attributeList.add(trapDatas.getTrap1()); + } + if(trapDatas.getTrap2()!= null){ + attributeList.add(trapDatas.getTrap2()); + } + if(trapDatas.getTrap3()!= null){ + attributeList.add(trapDatas.getTrap3()); + } + if(trapDatas.getTrap4()!= null){ + attributeList.add(trapDatas.getTrap4()); + } + if(trapDatas.getTrap5()!= null){ + attributeList.add(trapDatas.getTrap5()); + } + if(trapDatas.getTrap6()!= null){ + attributeList.add(trapDatas.getTrap6()); + } + }else{ + if(trap.equals("Fault")){ + if(trapDatas.getTrap1()!= null){ + attributeList.add(trapDatas.getTrap1()); + } + if(trapDatas.getTrap2()!= null){ + attributeList.add(trapDatas.getTrap2()); + } + if(trapDatas.getTrap3()!= null){ + attributeList.add(trapDatas.getTrap3()); + } + if(trapDatas.getTrap4()!= null){ + attributeList.add(trapDatas.getTrap4()); + } + if(trapDatas.getTrap5()!= null){ + attributeList.add(trapDatas.getTrap5()); + } + if(trapDatas.getTrap6()!= null){ + attributeList.add(trapDatas.getTrap6()); + } + } + } + + for(int j = 0; j < attributeList.size(); j++){ + String signatureBody = ""; + ArrayList<Object> connectTraps = (ArrayList<Object>) attributeList.get(j); + for(int i =0 ; i < connectTraps.size(); i++){ + String connectBody = ""; + Object object = connectTraps.get(i); + if(object instanceof LinkedHashMap<?, ?>){ + String notBox = ""; + if(((LinkedHashMap) object).keySet().contains("notBox")){ + notBox = ((LinkedHashMap) object).get("notBox").toString(); + } + String trigger1 = ((LinkedHashMap) object).get("trigger1").toString(); + String operatorBox = ((LinkedHashMap) object).get("operatorBox").toString(); + String trigger2 = ((LinkedHashMap) object).get("trigger2").toString(); + connectBody = notBox + "@!" + trigger1 + "@!" + operatorBox + "@!" + trigger2 + "#!"; + } + signatureBody = signatureBody + connectBody; + } + triggerBody = triggerBody + signatureBody + "?!"; + } + + return triggerBody; + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + private String callTrap(String trap, Object object) { + String signatureBody = ""; + TrapDatas trapDatas = (TrapDatas) object; + ArrayList<Object> attributeList = new ArrayList<>(); + // Read the Trap + if(!trap.equals("nill")){ + try{ + if(trap.startsWith("Trap")){ + if(trap.equals("Trap1")){ + attributeList = trapDatas.getTrap1(); + }else if(trap.equals("Trap2")){ + attributeList = trapDatas.getTrap2(); + }else if(trap.equals("Trap3")){ + attributeList = trapDatas.getTrap3(); + }else if(trap.equals("Trap4")){ + attributeList = trapDatas.getTrap4(); + }else if(trap.equals("Trap5")){ + attributeList = trapDatas.getTrap5(); + }else if(trap.equals("Trap6")){ + attributeList = trapDatas.getTrap6(); + } + }else{ + if(trap.equals("Fault")){ + if(trap.equals("Fault1")){ + attributeList = trapDatas.getTrap1(); + }else if(trap.equals("Fault2")){ + attributeList = trapDatas.getTrap2(); + }else if(trap.equals("Fault3")){ + attributeList = trapDatas.getTrap3(); + }else if(trap.equals("Fault4")){ + attributeList = trapDatas.getTrap4(); + }else if(trap.equals("Fault5")){ + attributeList = trapDatas.getTrap5(); + }else if(trap.equals("Fault6")){ + attributeList = trapDatas.getTrap6(); + } + } + } + } catch(Exception e){ + return "(" + trap + ")"; + } + }else{ + if(trapDatas.getTrap1()!=null){ + attributeList = trapDatas.getTrap1(); + }else{ + return ""; + } + } + signatureBody = signatureBody + "(" + readAttributes(attributeList, attributeList.size()-1) + ")"; + return signatureBody; + } + + private String readAttributes(ArrayList<Object> object, int index) { + String attributes = ""; + Map<String, String> trapSignatures = (Map<String, String>) object.get(index); + // Read the Elements. + Object notBox = ""; + if(trapSignatures.keySet().contains("notBox")){ + notBox = trapSignatures.get("notBox"); + } + if(notBox!=null){ + attributes = attributes + notBox.toString(); + } + Object trapName1 = trapSignatures.get("trigger1"); + if(trapName1!=null){ + String attrib = trapName1.toString(); + if(attrib.startsWith("A")){ + try{ + int iy = Integer.parseInt(attrib.substring(1))-1; + attributes = attributes + "(" + readAttributes(object, iy) + ")"; + }catch(NumberFormatException e){ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")"; + } catch (UnsupportedEncodingException e1) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1); + } + } + }else{ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")"; + } catch (UnsupportedEncodingException e) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e); + } + } + }else{ + return ""; + } + Object comboBox = trapSignatures.get("operatorBox"); + if(comboBox!=null){ + attributes = attributes + comboBox.toString(); + }else{ + return attributes; + } + Object trapName2 = trapSignatures.get("trigger2"); + if(trapName2!=null){ + String attrib = trapName2.toString(); + if(attrib.startsWith("A")){ + try{ + int iy = Integer.parseInt(attrib.substring(1))-1; + attributes = attributes + "(" + readAttributes(object, iy) + ")"; + }catch(NumberFormatException e){ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")"; + } catch (UnsupportedEncodingException e1) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1); + } + } + }else{ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")"; + } catch (UnsupportedEncodingException e) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e); + } + } + } + return attributes; + } + + private String getVarbindOID(String attrib) { + VarbindDictionary varbindId = varbindDictionaryDao.getVarbindEntityByName(attrib).get(0); + return varbindId.getVarbindOID(); + } + + private String connectTriggerSignature(int index, ArrayList<Object> triggerSignatures, Object object) { + String resultBody = ""; + Map<String, String> connectTraps = (Map<String, String>) triggerSignatures.get(index); + try{ + String notBox = ""; + if(connectTraps.keySet().contains("notBox")){ + notBox = connectTraps.get("notBox"); + } + resultBody = resultBody + "(" + notBox; + }catch(NullPointerException e){ + resultBody = resultBody + "("; + } + String connectTrap1 = connectTraps.get("connectTrap1"); + if(connectTrap1.startsWith("Trap") || connectTrap1.startsWith("Fault")){ + String trapBody = callTrap(connectTrap1, object); + if(trapBody!=null){ + resultBody = resultBody + trapBody; + } + }else if(connectTrap1.startsWith("C")){ + for(int i=0; i<= triggerSignatures.size(); i++){ + Map<String,String> triggerSignature = (Map<String, String>) triggerSignatures.get(i); + if(triggerSignature.get("id").equals(connectTrap1)){ + resultBody = resultBody + "("; + String connectBody = connectTriggerSignature(i, triggerSignatures, object); + resultBody = resultBody + connectBody + ")"; + }else{ + i++; + } + } + } + try{ + String trapCount1 = connectTraps.get("trapCount1"); + resultBody = resultBody + ", Time = " + trapCount1 + ")"; + }catch(NullPointerException e){ + } + try{ + String operatorBox = connectTraps.get("operatorBox"); + resultBody = resultBody + operatorBox +"("; + }catch (NullPointerException e){ + } + try{ + String connectTrap2 = connectTraps.get("connectTrap2"); + if(connectTrap2.startsWith("Trap") || connectTrap2.startsWith("Fault")){ + String trapBody = callTrap(connectTrap2, object); + if(trapBody!=null){ + resultBody = resultBody + trapBody; + } + }else if(connectTrap2.startsWith("C")){ + for(int i=0; i<= triggerSignatures.size(); i++){ + Map<String,String> triggerSignature = (Map<String, String>) triggerSignatures.get(i); + if(triggerSignature.get("id").equals(connectTrap2)){ + resultBody = resultBody + "("; + String connectBody = connectTriggerSignature(i, triggerSignatures, object); + resultBody = resultBody + connectBody + ")"; + }else{ + i++; + } + } + } + }catch(NullPointerException e){ + } + try{ + String trapCount2 = connectTraps.get("trapCount2"); + resultBody = resultBody + ", Time = " + trapCount2 + ")"; + }catch(NullPointerException e){ + } + return resultBody; + } + + public void PrePopulateClosedLoopFaultPolicyData(PolicyAdapter policyAdapter) { + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("Fault_") +6 , policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + int index = 0; + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + + // First match in the target is EcompName, so set that value. + if (index == 1) { + policyAdapter.setEcompName(value); + EcompName ecompName = new EcompName(); + ecompName.setEcompName(value); + policyAdapter.setEcompNameField(ecompName); + } + if (index == 2){ + policyAdapter.setRiskType(value); + } + + if (index == 3){ + policyAdapter.setRiskLevel(value); + } + + if (index == 4){ + policyAdapter.setGuard(value); + } + if (index == 5 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + index++; + } + } + } + } + } + } + } + String jsonBodyName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + "."; + policyAdapter.setConfigBodyPath(jsonBodyName); + readClosedLoopJSONFile(policyAdapter); + } + + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + private String readClosedLoopJSONFile(PolicyAdapter policyAdapter) { + String fileLocation = null; + String fileName = policyAdapter.getConfigBodyPath(); + if (fileName != null ) { + fileLocation = PolicyController.getConfigHome(); + } + if (fileLocation == null) { + return fileLocation; + } + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName)) { + FileInputStream inputStream = null; + String location = file.toString(); + try { + inputStream = new FileInputStream(location); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + if (location.endsWith("json")) { + JsonReader jsonReader = null; + jsonReader = Json.createReader(inputStream); + ObjectMapper mapper = new ObjectMapper(); + try { + ClosedLoopFaultBody closedLoopBody = mapper.readValue(jsonReader.read().toString(), ClosedLoopFaultBody.class); + if(closedLoopBody.getClosedLoopPolicyStatus().equalsIgnoreCase("ACTIVE")){ + closedLoopBody.setClosedLoopPolicyStatus("Active"); + }else{ + closedLoopBody.setClosedLoopPolicyStatus("InActive"); + } + policyAdapter.setJsonBodyData(closedLoopBody); + if(closedLoopBody.getTrapMaxAgeUsedForUI() != null){ + policyAdapter.setTrapMaxAge(closedLoopBody.getTrapMaxAgeUsedForUI().toString()); + } + if(closedLoopBody.getTriggerTimeWindowUsedForUI() != null){ + policyAdapter.setClearTimeOut(closedLoopBody.getTriggerTimeWindowUsedForUI().toString()); + } + if(closedLoopBody.getVerfificationTimeWindowUsedForUI() != null){ + policyAdapter.setVerificationclearTimeOut(closedLoopBody.getVerfificationTimeWindowUsedForUI().toString()); + } + + } catch (Exception e) { + e.printStackTrace(); + } + jsonReader.close(); + } + } + } + return null; + } + +} + +class ClosedLoopGridJSONData{ + + private String clearTimeOut; + private String trapMaxAge; + private String verificationclearTimeOut; + private ArrayList<Object> connecttriggerSignatures; + private ArrayList<Object> connectVerificationSignatures; + + public String getClearTimeOut() { + return clearTimeOut; + } + public void setClearTimeOut(String clearTimeOut) { + this.clearTimeOut = clearTimeOut; + } + public String getTrapMaxAge() { + return trapMaxAge; + } + public void setTrapMaxAge(String trapMaxAge) { + this.trapMaxAge = trapMaxAge; + } + public String getVerificationclearTimeOut() { + return verificationclearTimeOut; + } + public void setVerificationclearTimeOut(String verificationclearTimeOut) { + this.verificationclearTimeOut = verificationclearTimeOut; + } + + + public ArrayList<Object> getConnecttriggerSignatures() { + return connecttriggerSignatures; + } + public void setConnecttriggerSignatures(ArrayList<Object> connecttriggerSignatures) { + this.connecttriggerSignatures = connecttriggerSignatures; + } + public ArrayList<Object> getConnectVerificationSignatures() { + return connectVerificationSignatures; + } + public void setConnectVerificationSignatures(ArrayList<Object> connectVerificationSignatures) { + this.connectVerificationSignatures = connectVerificationSignatures; + } +} + +class TrapDatas{ + private ArrayList<Object> trap1; + private ArrayList<Object> trap2; + private ArrayList<Object> trap3; + private ArrayList<Object> trap4; + private ArrayList<Object> trap5; + private ArrayList<Object> trap6; + public ArrayList<Object> getTrap1() { + return trap1; + } + public void setTrap1(ArrayList<Object> trap1) { + this.trap1 = trap1; + } + public ArrayList<Object> getTrap2() { + return trap2; + } + public void setTrap2(ArrayList<Object> trap2) { + this.trap2 = trap2; + } + public ArrayList<Object> getTrap3() { + return trap3; + } + public void setTrap3(ArrayList<Object> trap3) { + this.trap3 = trap3; + } + public ArrayList<Object> getTrap4() { + return trap4; + } + public void setTrap4(ArrayList<Object> trap4) { + this.trap4 = trap4; + } + public ArrayList<Object> getTrap5() { + return trap5; + } + public void setTrap5(ArrayList<Object> trap5) { + this.trap5 = trap5; + } + public ArrayList<Object> getTrap6() { + return trap6; + } + public void setTrap6(ArrayList<Object> trap6) { + this.trap6 = trap6; + } +}
\ No newline at end of file diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java new file mode 100644 index 000000000..f5e0557f8 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java @@ -0,0 +1,422 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonReader; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.ClosedLoopPMBody; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreateClosedLoopPMController extends RestrictedBaseController{ + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreateClosedLoopPMController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){ + CreateClosedLoopPMController.policyVersionDao = policyVersionDao; + CreateClosedLoopPMController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateClosedLoopPMController.policyNotificationDao = policyNotificationDao; + } + + public CreateClosedLoopPMController(){} + + protected PolicyAdapter policyAdapter = null; + private String ruleID = ""; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/policyController/save_PMPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePMPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_PM_" + policyData.getPolicyName(); + List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + + + if(policyData.getServiceTypePolicyName() != null){ + policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); + } + + ObjectMapper jsonMapper = new ObjectMapper(); + String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData()); + jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\","); + jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType()); + policyData.setJsonBody(jsonBody); + + Map<String, String> successMap = new HashMap<String, String>(); + + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + 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; + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + public void PrePopulateClosedLoopPMPolicyData(PolicyAdapter policyAdapter) { + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") +3 , policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + int index = 0; + Iterator<MatchType> iterMatch = matchList.iterator(); + while (matchList.size()>1 && iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + + // First match in the target is EcompName, so set that value. + if (index == 0) { + policyAdapter.setEcompName(value); + } + + if (index == 1){ + policyAdapter.setRiskType(value); + } + + if (index == 2){ + policyAdapter.setRiskLevel(value); + } + + if (index == 3){ + policyAdapter.setGuard(value); + } + + if (index == 4 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + if (index == 5){ + LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>(); + String key = "serviceTypePolicyName"; + serviceTypePolicyName1.put(key, value); + policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1); + } + index++; + } + } + } + } + } + } + } + String jsonBodyName = policyAdapter.getDirPath().replace(File.separator, ".")+"."+ policyAdapter.getOldPolicyFileName() + "."; + policyAdapter.setConfigBodyPath(jsonBodyName); + readClosedLoopJSONFile(policyAdapter); + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + protected String readClosedLoopJSONFile(PolicyAdapter policyAdapter) { + String fileLocation = null; + String fileName = policyAdapter.getConfigBodyPath(); + if (fileName != null ) { + fileLocation = PolicyController.getConfigHome(); + } + if (fileLocation == null) { + return fileLocation; + } + + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName)) { + FileInputStream inputStream = null; + String location = file.toString(); + try { + inputStream = new FileInputStream(location); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + if (location.endsWith("json")) { + JsonReader jsonReader = null; + jsonReader = Json.createReader(inputStream); + ObjectMapper mapper = new ObjectMapper(); + try { + ClosedLoopPMBody closedLoopBody = mapper.readValue(jsonReader.read().toString(), ClosedLoopPMBody.class); + policyAdapter.setJsonBodyData(closedLoopBody); + } catch (IOException e) { + e.printStackTrace(); + /*logger.error("JSON Body Mapping Error");*/ + } + jsonReader.close(); + } + } + } + return null; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java new file mode 100644 index 000000000..c4d4cfd50 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java @@ -0,0 +1,987 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.TreeMap; + +import javax.json.Json; +import javax.json.JsonReader; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RemoteCatalogValuesDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.dao.GroupPolicyScopeListDao; +import org.openecomp.policy.rest.dao.MicroServiceModelsDao; +import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; +import org.openecomp.policy.rest.jpa.MicroServiceModels; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RemoteCatalogValues; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.policy.utils.ConfigurableRESTUtils; +import org.openecomp.policy.utils.ConfigurableRESTUtils.RESQUEST_METHOD; +import org.openecomp.policy.utils.ConfigurableRESTUtils.REST_RESPONSE_FORMAT; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.base.Joiner; +import com.google.common.base.Splitter; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Controller +@RequestMapping("/") +public class CreateDcaeMicroServiceController extends RestrictedBaseController { + private static final Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static RemoteCatalogValuesDao remoteCatalogValuesDao; + private static MicroServiceModelsDao microServiceModelsDao; + private static PolicyVersionDao policyVersionDao; + private static GroupPolicyScopeListDao groupPolicyScopeListDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreateDcaeMicroServiceController(RuleAlgorithmsDao ruleAlgorithmsDao, RemoteCatalogValuesDao remoteCatalogValuesDao, + MicroServiceModelsDao microServiceModelsDao, PolicyVersionDao policyVersionDao, GroupPolicyScopeListDao groupPolicyScopeListDao, + WatchPolicyNotificationDao policyNotificationDao){ + CreateDcaeMicroServiceController.groupPolicyScopeListDao = groupPolicyScopeListDao; + CreateDcaeMicroServiceController.policyVersionDao = policyVersionDao; + CreateDcaeMicroServiceController.microServiceModelsDao = microServiceModelsDao; + CreateDcaeMicroServiceController.remoteCatalogValuesDao = remoteCatalogValuesDao; + CreateDcaeMicroServiceController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateDcaeMicroServiceController.policyNotificationDao = policyNotificationDao; + } + + public CreateDcaeMicroServiceController(){} + + protected PolicyAdapter policyAdapter = null; + private String ruleID = ""; + private int priorityCount; + private Map<String, String> attributesListRefMap = new HashMap<String, String>(); + private Map<String, LinkedList<String>> arrayTextList = new HashMap<String, LinkedList<String>>(); + + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + + @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); + String servicename = value.toString().split("-v")[0]; + String version = null; + if (value.toString().contains("-v")){ + version = value.toString().split("-v")[1]; + } + MicroServiceModels returnModel = getAttributeObject(servicename, version); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + List<Object> list = new ArrayList<>(); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(returnModel); + JSONObject j = new JSONObject("{dcaeModelData: " + responseString +"}"); + list.add(j); + out.write(list.toString()); + return null; + } + + private MicroServiceModels getAttributeObject(String name, String version) { + MicroServiceModels workingModel = new MicroServiceModels(); + List<MicroServiceModels> microServiceModelsData = microServiceModelsDao.getMicroServiceModelsData(); + for (int i = 0; i < microServiceModelsData.size(); i++) { + workingModel = microServiceModelsData.get(i); + if (version!=null && workingModel.getVersion()!=null){ + if (workingModel.getModelName().equals(name) && workingModel.getVersion().equals(version)){ + break; + } + }else{ + if (workingModel.getModelName().equals(name) && workingModel.getVersion() == null){ + break; + } + } + } + return workingModel; + } + + @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + List<String> priorityList = new ArrayList<String>(); + priorityCount = 10; + for (int i = 1; i < priorityCount; i++) { + priorityList.add(String.valueOf(i)); + } + model.put("priorityDatas", mapper.writeValueAsString(priorityList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + + @RequestMapping(value={"/policyController/save_DCAEMSPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveDCAEMSPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String jsonContent = null; + try{ + jsonContent = decodeContent(root.get("policyJSON")).toString(); + }catch(Exception e){ + logger.error("Error while decoding microservice content"); + } + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + if(policyData.isEditPolicy){ + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_MS_" + policyData.getPolicyName(); + List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + policyData.setEcompName(policyData.getEcompName()); + //get the jsonBody + String jsonBody = null; + try { + jsonBody = constructJson(policyData, jsonContent); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + policyData.setJsonBody(jsonBody); + Map<String, String> successMap = new HashMap<String, String>(); + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + + System.out.println(root); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + 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; + } + + private JSONObject decodeContent(JsonNode jsonNode){ + Iterator<JsonNode> jsonElements = jsonNode.elements(); + Iterator<String> jsonKeys = jsonNode.fieldNames(); + Map<String,String> element = new TreeMap<String,String>(); + while(jsonElements.hasNext() && jsonKeys.hasNext()){ + element.put(jsonKeys.next(), jsonElements.next().toString()); + } + JSONObject jsonResult = new JSONObject(); + JSONArray jsonArray = null; + String oldValue = null; + String nodeKey = null; + String arryKey = null; + Boolean isArray = false; + JsonNodeFactory nodeFactory = JsonNodeFactory.instance; + ObjectNode node = nodeFactory.objectNode(); + String prevKey = null; + String presKey = null; + for(String key: element.keySet()){ + if(key.contains(".")){ + presKey = key.substring(0,key.indexOf(".")); + }else if(key.contains("@")){ + presKey = key.substring(0,key.indexOf("@")); + }else{ + presKey = key; + } + // first check if we are different from old. + System.out.println(key+"\n"); + if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){ + if(!oldValue.equals(key.substring(0,key.indexOf("@")))){ + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){ + jsonResult.put(oldValue, jsonArray); + isArray = false; + jsonArray = new JSONArray(); + } + /*if(node.size()!=0 && key.contains("@")){ + + }else{ + if(node.size()!=0){ + + } + }*/ + prevKey = presKey; + // + if(key.contains(".")){ + if(nodeKey==null){ + nodeKey = key.substring(0,key.indexOf(".")); + } + if(nodeKey.equals(key.substring(0,key.indexOf(".")))){ + node.put(key.substring(key.indexOf(".")+1), element.get(key)); + }else{ + if(node.size()!=0){ + if(nodeKey.contains("@")){ + if(arryKey==null){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + if(nodeKey.endsWith("@0")){ + isArray = true; + jsonArray = new JSONArray(); + } + if(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ + jsonArray.put(decodeContent(node)); + } + if(key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))){ + jsonResult.put(arryKey, jsonArray); + jsonArray = new JSONArray(); + }else if(!key.contains("@")){ + jsonResult.put(arryKey, jsonArray); + jsonArray = new JSONArray(); + } + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + }else{ + isArray = false; + jsonResult.put(nodeKey, decodeContent(node)); + } + node = nodeFactory.objectNode(); + } + nodeKey = key.substring(0,key.indexOf(".")); + if(nodeKey.contains("@")){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + node.put(key.substring(key.indexOf(".")+1), element.get(key)); + } + }else if(node.size()!=0){ + if(nodeKey.contains("@")){ + if(arryKey==null){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + if(nodeKey.endsWith("@0")){ + isArray = true; + jsonArray = new JSONArray(); + } + if(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ + jsonArray.put(decodeContent(node)); + } + jsonResult.put(arryKey, jsonArray); + jsonArray = new JSONArray(); + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + }else{ + isArray = false; + jsonResult.put(nodeKey, decodeContent(node)); + } + node = nodeFactory.objectNode(); + if(key.contains("@")){ + isArray = true; + if(key.endsWith("@0")|| jsonArray==null){ + jsonArray = new JSONArray(); + } + }else if(!key.contains("@")){ + isArray = false; + } + if(isArray){ + if(oldValue==null){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue!=prevKey){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue.equals(key.substring(0,key.indexOf("@")))){ + jsonArray.put(element.get(key)); + }else{ + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + oldValue = key.substring(0,key.indexOf("@")); + }else{ + jsonResult.put(key, element.get(key)); + } + }else{ + if(key.contains("@")){ + isArray = true; + if(key.endsWith("@0")|| jsonArray==null){ + jsonArray = new JSONArray(); + } + }else if(!key.contains("@")){ + isArray = false; + } + if(isArray){ + if(oldValue==null){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue!=prevKey){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue.equals(key.substring(0,key.indexOf("@")))){ + jsonArray.put(element.get(key)); + }else{ + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + oldValue = key.substring(0,key.indexOf("@")); + }else{ + jsonResult.put(key, element.get(key)); + } + } + } + if(node.size()>0){ + if(nodeKey.contains("@")){ + if(jsonArray==null){ + jsonArray = new JSONArray(); + } + if(arryKey==null){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + jsonArray.put(decodeContent(node)); + jsonResult.put(arryKey, jsonArray); + isArray = false;; + }else{ + jsonResult.put(nodeKey, decodeContent(node)); + } + } + if(isArray && jsonArray.length() > 0){ + jsonResult.put(oldValue, jsonArray); + } + return jsonResult; + } + + public void PrePopulateDCAEMSPolicyData(PolicyAdapter policyAdapter) { + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3 , policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + String jsonBodyName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + "."; + policyAdapter.setConfigBodyPath(jsonBodyName); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + int index = 0; + Iterator<MatchType> iterMatch = matchList.iterator(); + while (matchList.size()>1 && iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + + // First match in the target is EcompName, so set that value. + if (index == 0) { + policyAdapter.setEcompName(value); + } + if (index == 1){ + policyAdapter.setConfigName(value); + } + if (index == 2){ + if(value != null){ + readFile(policyAdapter); + } + } + if (index == 3){ + policyAdapter.setUuid(value); + } + if (index == 4){ + policyAdapter.setLocation(value); + } + if (index == 5){ + policyAdapter.setRiskType(value); + } + + if (index == 6){ + policyAdapter.setRiskLevel(value); + } + + if (index == 7){ + policyAdapter.setGuard(value); + } + if (index == 8 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + index++; + } + } + } + } + } + } + } + } + + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + @SuppressWarnings("unchecked") + private String readFile(PolicyAdapter policyAdapter) { + String fileLocation = null; + String policyScopeName = null; + String fileName = policyAdapter.getConfigBodyPath(); + if (fileName != null ) { + fileLocation = PolicyController.getConfigHome(); + } + if (fileLocation == null) { + return fileLocation; + } + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName)) { + FileInputStream inputStream = null; + String location = file.toString(); + try { + inputStream = new FileInputStream(location); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + if (location.endsWith("json")) { + JsonReader jsonReader = null; + jsonReader = Json.createReader(inputStream); + ObjectMapper mapper = new ObjectMapper(); + try { + DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(jsonReader.read().toString(), DCAEMicroServiceObject.class); + policyScopeName = getPolicyScope(msBody.getPolicyScope()); + policyAdapter.setPolicyScope(policyScopeName); + + policyAdapter.setPriority(msBody.getPriority()); + + if (msBody.getVersion()!= null){ + policyAdapter.setServiceType(msBody.getService() + "-v" + msBody.getVersion()); + }else{ + policyAdapter.setServiceType(msBody.getService()); + } + if(msBody.getContent() != null){ + LinkedHashMap<String, Object> data = new LinkedHashMap<String, Object>(); + LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent(); + readRecursivlyJSONContent(map, data); + policyAdapter.setRuleData(data); + } + + } catch (Exception e) { + e.printStackTrace(); + } + jsonReader.close(); + } + } + } + return fileName; + + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){ + for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { + Object key = iterator.next(); + Object value = map.get(key); + if(value instanceof LinkedHashMap<?, ?>){ + readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, data); + }else if(value instanceof ArrayList){ + ArrayList<?> jsonArrayVal = (ArrayList<?>)value; + for(int i = 0; i < jsonArrayVal.size(); i++){ + Object arrayvalue = jsonArrayVal.get(i); + if(arrayvalue instanceof LinkedHashMap<?, ?>){ + LinkedHashMap<String, Object> newData = new LinkedHashMap<String, Object>(); + readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData); + for(String objKey: newData.keySet()){ + data.put(key+"@"+i+"." +objKey, newData.get(objKey)); + } + }else if(arrayvalue instanceof ArrayList){ + ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value; + for(int j = 0; j < jsonArrayVal1.size(); j++){ + Object arrayvalue1 = jsonArrayVal1.get(i); + data.put(key+"@"+j, arrayvalue1.toString()); + } + }else{ + data.put(key+"@"+i, arrayvalue.toString()); + } + } + }else{ + data.put(key.toString(), value.toString()); + } + } + } + + private String getPolicyScope(String value) { + GroupPolicyScopeList pScope = new GroupPolicyScopeList(); + List<GroupPolicyScopeList> groupList= groupPolicyScopeListDao.getGroupPolicyScopeListData(); + if(groupList.size() > 0){ + for(int i = 0 ; i < groupList.size() ; i ++){ + pScope = groupList.get(i); + if (pScope.getGroupList().equals(value)){ + break; + } + } + } + return pScope.getGroupName(); + } + + private GroupPolicyScopeList getPolicyObject(String policyScope) { + GroupPolicyScopeList pScope = new GroupPolicyScopeList(); + List<GroupPolicyScopeList> groupList = groupPolicyScopeListDao.getGroupPolicyScopeListData(); + if(groupList.size() > 0){ + for(int i = 0 ; i < groupList.size() ; i ++){ + pScope = groupList.get(i); + if (pScope.getGroupName().equals(policyScope)){ + break; + } + } + } + return pScope; + } + + private String constructJson(PolicyAdapter policyAdapter, String jsonContent) { + ObjectWriter om = new ObjectMapper().writer(); + String json=""; + DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject(); + + microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS)); + if(policyAdapter.getServiceType() !=null){ + microServiceObject.setService(policyAdapter.getServiceType().toString().split("-v")[0]); + if (policyAdapter.getServiceType().toString().contains("-v")){ + microServiceObject.setVersion(policyAdapter.getServiceType().toString().split("-v")[1]); + } + } + if(policyAdapter.getUuid()!=null){ + microServiceObject.setUuid(policyAdapter.getUuid()); + } + + if(policyAdapter.getLocation()!=null){ + microServiceObject.setLocation(policyAdapter.getLocation()); + } + if(policyAdapter.getPolicyName()!=null){ + microServiceObject.setPolicyName(policyAdapter.getPolicyName()); + } + + if(policyAdapter.getConfigName()!=null){ + microServiceObject.setConfigName(policyAdapter.getConfigName()); + } + if(policyAdapter.getPolicyDescription()!=null){ + microServiceObject.setDescription(policyAdapter.getPolicyDescription()); + } + if (policyAdapter.getPriority()!=null){ + microServiceObject.setPriority(policyAdapter.getPriority()); + }else { + microServiceObject.setPriority("9999"); + } + microServiceObject.setContent(jsonContent); + GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope()); + microServiceObject.setPolicyScope(policyScopeValue.getGroupList()); + try { + json = om.writeValueAsString(microServiceObject); + } catch (JsonProcessingException e) { + logger.error("Error writing out the object"); + } + System.out.println(json); + String cleanJson = cleanUPJson(json); + return cleanJson; + } + + private String cleanUPJson(String json) { + String cleanJason = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"}); + cleanJason = StringUtils.replaceEach(json, new String[]{"\\\\\\"}, new String[]{"\\"}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"}); + + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"[", "]\""}, new String[]{"[", "]"}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"{", "}\""}, new String[]{"{", "}"}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\\\""}, new String[]{""}); + return cleanJason; + } + + //Convert the map values and set into JSON body + public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) { + Map<String, String> attribute = new HashMap<String, String>(); + String temp = null; + String key; + String value; + for (Entry<String, String> entry : attributesMap.entrySet()) { + key = entry.getKey(); + value = entry.getValue(); + attribute.put(key, value); + } + for (Entry<String, String> entryRef : attributesRefMap.entrySet()) { + key = entryRef.getKey(); + value = entryRef.getValue().toString(); + attribute.put(key, value); + } + for (Entry<String, String> entryList : attributesListRefMap.entrySet()) { + key = entryList.getKey(); + value = entryList.getValue().toString(); + attribute.put(key, value); + } + for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){ + key = arrayList.getKey(); + temp = null; + for (Object textList : arrayList.getValue()){ + if (temp == null){ + temp = "[" + textList; + }else{ + temp = temp + "," + textList; + } + } + attribute.put(key, temp+ "]"); + } + + return attribute; + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } +} + +class DCAEMicroServiceObject { + + public String service; + public String location; + public String uuid; + public String policyName; + public String description; + public String configName; + public String templateVersion; + public String version; + public String priority; + public String policyScope; + + public String getPolicyScope() { + return policyScope; + } + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + + public String getPriority() { + return priority; + } + public void setPriority(String priority) { + this.priority = priority; + } + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } + private Object content; + + + public String getPolicyName() { + return policyName; + } + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getConfigName() { + return configName; + } + public void setConfigName(String configName) { + this.configName = configName; + } + public Object getContent() { + return content; + } + public void setContent(Object content) { + this.content = content; + } + + public String getService() { + return service; + } + public void setService(String service) { + this.service = service; + } + public String getLocation() { + return location; + } + public void setLocation(String location) { + this.location = location; + } + + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getTemplateVersion() { + return templateVersion; + } + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + +}
\ No newline at end of file diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java new file mode 100644 index 000000000..6d7c0c752 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java @@ -0,0 +1,1292 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.json.JSONObject; +import org.openecomp.policy.adapter.AddressGroupJson; +import org.openecomp.policy.adapter.AddressJson; +import org.openecomp.policy.adapter.AddressMembers; +import org.openecomp.policy.adapter.DeployNowJson; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.adapter.PrefixIPList; +import org.openecomp.policy.adapter.ServiceGroupJson; +import org.openecomp.policy.adapter.ServiceListJson; +import org.openecomp.policy.adapter.ServiceMembers; +import org.openecomp.policy.adapter.ServicesJson; +import org.openecomp.policy.adapter.Term; +import org.openecomp.policy.adapter.TermCollector; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.dao.AddressGroupDao; +import org.openecomp.policy.rest.dao.FirewallDictionaryListDao; +import org.openecomp.policy.rest.dao.PrefixListDao; +import org.openecomp.policy.rest.dao.SecurityZoneDao; +import org.openecomp.policy.rest.dao.ServiceGroupDao; +import org.openecomp.policy.rest.dao.ServiceListDao; +import org.openecomp.policy.rest.dao.TermListDao; +import org.openecomp.policy.rest.jpa.AddressGroup; +import org.openecomp.policy.rest.jpa.FirewallDictionaryList; +import org.openecomp.policy.rest.jpa.GroupServiceList; +import org.openecomp.policy.rest.jpa.PREFIXLIST; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.policy.rest.jpa.SecurityZone; +import org.openecomp.policy.rest.jpa.ServiceList; +import org.openecomp.policy.rest.jpa.TermList; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +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; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreateFirewallController extends RestrictedBaseController { + private static Logger logger = FlexLogger.getLogger(CreateFirewallController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static PrefixListDao prefixListDao; + private static ServiceListDao serviceListDao; + private static TermListDao termListDao; + private static ServiceGroupDao serviceGroupDao; + private static AddressGroupDao addressGroupDao; + private static SecurityZoneDao securityZoneDao; + private static SessionFactory sessionFactory; + private static FirewallDictionaryListDao fwDictionaryListDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + List<String> expandablePrefixIPList = new ArrayList<String>(); + List<String> expandableServicesList= new ArrayList<String>(); + + private String parentSecurityZone; + + + public String getParentSecurityZone() { + return parentSecurityZone; + } + + public void setParentSecurityZone(String parentSecurityZone) { + this.parentSecurityZone = parentSecurityZone; + } + + + + @Autowired + private CreateFirewallController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, PrefixListDao prefixListDao, + ServiceListDao serviceListDao, TermListDao termListDao, ServiceGroupDao serviceGroupDao, AddressGroupDao addressGroupDao, SecurityZoneDao securityZoneDao, SessionFactory sessionFactory + ,FirewallDictionaryListDao fwDictionaryListDao, WatchPolicyNotificationDao policyNotificationDao){ + CreateFirewallController.addressGroupDao = addressGroupDao; + CreateFirewallController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateFirewallController.policyVersionDao = policyVersionDao; + CreateFirewallController.prefixListDao = prefixListDao; + CreateFirewallController.serviceListDao = serviceListDao; + CreateFirewallController.termListDao = termListDao; + CreateFirewallController.serviceGroupDao = serviceGroupDao; + CreateFirewallController.securityZoneDao = securityZoneDao; + CreateFirewallController.sessionFactory = sessionFactory; + CreateFirewallController.fwDictionaryListDao = fwDictionaryListDao; + CreateFirewallController.policyNotificationDao = policyNotificationDao; + } + + public CreateFirewallController(){} + protected PolicyAdapter policyAdapter = null; + private List<String> termCollectorList; + private List<FirewallDictionaryList> parentDictionaryList; + private String ruleID = ""; + private String jsonBody; + private ArrayList<Object> attributeList; + private ArrayList<Object> fwAttributeList; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/get_FWParentListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getFWParentListEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + String query= "select distinct parent from fwparent"; + model.put("fwParentListDictionaryDatas", mapper.writeValueAsString(queryToDatabase(query))); + + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @SuppressWarnings("unchecked") + private List<String> queryToDatabase(String query) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = null; + try { + SQLQuery sqlquery=session.createSQLQuery(query); + //Query hbquery = session.createQuery(query); + data = sqlquery.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Qurying Parent Child Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + + } + + @SuppressWarnings("unchecked") + private void updateToDatabase(String updateQuery) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = null; + try { + SQLQuery sqlquery=session.createSQLQuery(updateQuery); + sqlquery.executeUpdate(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating FWChildParent Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + + @RequestMapping(value={"/policyController/save_FirewallPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveFirewallPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + termCollectorList = new ArrayList<String>(); + parentDictionaryList= new ArrayList<FirewallDictionaryList>(); + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + this.policyAdapter = policyData; + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_FW_" + policyData.getPolicyName(); + List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + if(policyData.getFwPolicyType().equalsIgnoreCase("Parent Policy")){ + String comboNames=""; + int i=0; + for(Object fwattribute : policyData.getFwattributes()){ + if(fwattribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) fwattribute).get("option").toString(); + if(i>0){ + comboNames = comboNames+","+ key; + } + else{ + comboNames = key; + } + i++; + } + } + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"+"@comboList:"+comboNames); + } + else{ + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + } + + //policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map<String, String> successMap = new HashMap<String, String>(); + + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); + termCollectorList.add(key); + } + } + } + if(policyData.getFwattributes()!=null){ + if(policyData.getFwattributes().size() > 0){ + for(Object fwattribute : policyData.getFwattributes()){ + if(fwattribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) fwattribute).get("option").toString(); + FirewallDictionaryList fwDictValue = fwDictionaryListDao.getFWDictionaryDataById(key); + parentDictionaryList.add(fwDictValue); + if(fwDictValue.getAddressList().contains(",")) { + for(String individualAddressObject:fwDictValue.getAddressList().split(",") ){ + expandablePrefixIPList.add(individualAddressObject); + } + } + else{ + expandablePrefixIPList.add(fwDictValue.getAddressList()); + } + + if(fwDictValue.getServiceList().contains(",")) { + for(String individualAddressObject:fwDictValue.getServiceList().split(",") ){ + expandableServicesList.add(individualAddressObject); + } + } + else{ + expandableServicesList.add(fwDictValue.getServiceList()); + } + } + } + } + } + + jsonBody = constructJson(); + if (jsonBody != null || jsonBody.equalsIgnoreCase("")) { + policyAdapter.setJsonBody(jsonBody); + + } else { + policyAdapter.setJsonBody("{}"); + } + policyData.setJsonBody(jsonBody); + + + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + removeExtension=removeExtension.replace(File.separator, "."); + //PC Feature + if(policyAdapter.getFwPolicyType().equalsIgnoreCase("Parent Policy")){ + //Reads the SecurityZone from the Parent UI and then gets the value from the DB + //Stores the Parent Policy Name and securityZone value to the fwparent table. + String parentSecurityZoneValue= getParentSecurityZone(); + String parentQuery= "INSERT INTO FWPARENT(PARENT,SECURITYZONE) VALUES ('"; + parentQuery=parentQuery+removeExtension+"','"+ parentSecurityZoneValue +"')"; + updateToDatabase(parentQuery); + } + else{ + String updateQuery = ""; + if(policyAdapter.isEditPolicy()){ + updateQuery= "UPDATE FWCHILDTOPARENT SET PARENT='"+policyAdapter.getParentForChild()+"' WHERE CHILD='"+removeExtension+"'"; + } + else{ + updateQuery= "INSERT INTO FWCHILDTOPARENT(CHILD,PARENT) VALUES ('"; + updateQuery =updateQuery+removeExtension+"','"+ policyAdapter.getParentForChild() +"')"; + } + updateToDatabase(updateQuery); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + 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; + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + private String constructJson() { + int ruleCount=1; + //Maps to assosciate the values read from the TermList dictionary + Map<Integer, String> srcIP_map =null; + Map<Integer, String> destIP_map=null; + Map<Integer, String> srcPort_map =null; + Map<Integer, String> destPort_map =null; + Map<Integer, String> action_map=null; + Map<Integer, String> fromZone_map=null; + Map<Integer, String> toZone_map=null; + + String ruleDesc=null; + String ruleFromZone=null; + String ruleToZone=null; + String ruleSrcPrefixList=null; + String ruleDestPrefixList=null; + String ruleSrcPort=null; + String ruleDestPort=null; + String ruleAction=null; + + String json = null; + + + List<String> expandableList = new ArrayList<String>(); + TermList jpaTermList; + SecurityZone jpaSecurityZone; + List<Term> termList = new ArrayList<Term>(); + + ServiceListJson targetSl=null; + try{ + + for (int tl = 0 ; tl< termCollectorList.size(); tl++) { + expandableList.add(termCollectorList.get(tl)); + Term targetTerm = new Term(); + //targetSl= new ServiceListJson(); + targetTerm.setRuleName(termCollectorList.get(tl)); + List<TermList> termListData = termListDao.getTermListData(); + for (int j =0; j < termListData.size(); j++) { + jpaTermList = termListData.get(j); + if (jpaTermList.getTermName().equals(termCollectorList.get(tl))){ + ruleDesc=jpaTermList.getTermDescription(); + if ((ruleDesc!=null)&& (!ruleDesc.isEmpty())){ + targetTerm.setDescription(ruleDesc); + } + ruleFromZone=jpaTermList.getFromZone(); + + if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())){ + fromZone_map = new HashMap<Integer, String>(); + fromZone_map.put(tl, ruleFromZone); + } + ruleToZone=jpaTermList.getToZone(); + + if ((ruleToZone != null) && (!ruleToZone.isEmpty())){ + toZone_map = new HashMap<Integer, String>(); + toZone_map.put(tl, ruleToZone); + } + ruleSrcPrefixList=jpaTermList.getSrcIPList(); + + if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())){ + srcIP_map = new HashMap<Integer, String>(); + srcIP_map.put(tl, ruleSrcPrefixList); + } + + ruleDestPrefixList= jpaTermList.getDestIPList(); + if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())){ + destIP_map = new HashMap<Integer, String>(); + destIP_map.put(tl, ruleDestPrefixList); + } + + ruleSrcPort=jpaTermList.getSrcPortList(); + + if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())){ + srcPort_map = new HashMap<Integer, String>(); + srcPort_map.put(tl, ruleSrcPort); + } + + ruleDestPort= jpaTermList.getDestPortList(); + + if (ruleDestPort!= null && (!jpaTermList.getDestPortList().isEmpty())){ + destPort_map = new HashMap<Integer, String>(); + destPort_map.put(tl, ruleDestPort); + } + + ruleAction=jpaTermList.getAction(); + + if (( ruleAction!= null) && (!ruleAction.isEmpty())){ + action_map = new HashMap<Integer, String>(); + action_map.put(tl, ruleAction); + } + } + } + targetTerm.setEnabled(true); + targetTerm.setLog(true); + targetTerm.setNegateSource(false); + targetTerm.setNegateDestination(false); + + if(action_map!=null){ + targetTerm.setAction(action_map.get(tl)); + } + + //FromZone arrays + if(fromZone_map!=null){ + List<String> fromZone= new ArrayList<String>(); + for(String fromZoneStr:fromZone_map.get(tl).split(",") ){ + fromZone.add(fromZoneStr); + } + targetTerm.setFromZones(fromZone); + } + + //ToZone arrays + if(toZone_map!=null){ + List<String> toZone= new ArrayList<String>(); + for(String toZoneStr:toZone_map.get(tl).split(",") ){ + toZone.add(toZoneStr); + } + targetTerm.setToZones(toZone); + } + + //Destination Services. + if(destPort_map!=null){ + Set<ServicesJson> destServicesJsonList= new HashSet<ServicesJson>(); + for(String destServices:destPort_map.get(tl).split(",") ){ + ServicesJson destServicesJson= new ServicesJson(); + destServicesJson.setType("REFERENCE"); + if(destServices.equals("ANY")){ + destServicesJson.setName("any"); + destServicesJsonList.add(destServicesJson); + break; + }else{ + if(destServices.startsWith("Group_")){ + destServicesJson.setName(destServices.substring(6,destServices.length())); + } else{ + destServicesJson.setName(destServices); + } + destServicesJsonList.add(destServicesJson); + } + } + targetTerm.setDestServices(destServicesJsonList); + } + //ExpandableServicesList + if((srcPort_map!=null) && (destPort_map!=null)){ + String servicesCollateString = (srcPort_map.get(tl) + "," + destPort_map.get(tl)); + expandableServicesList.add(servicesCollateString); + }else if (srcPort_map!=null){ + expandableServicesList.add(srcPort_map.get(tl)); + }else if (destPort_map!=null){ + expandableServicesList.add(destPort_map.get(tl)); + } + + if(srcIP_map!=null){ + //Source List + List<AddressJson> sourceListArrayJson= new ArrayList<AddressJson>(); + for(String srcList:srcIP_map.get(tl).split(",") ){ + AddressJson srcListJson= new AddressJson(); + if(srcList.equals("ANY")){ + srcListJson.setType("any"); + sourceListArrayJson.add(srcListJson); + break; + }else{ + srcListJson.setType("REFERENCE"); + if(srcList.startsWith("Group_")){ + srcListJson.setValue(srcList.substring(6,srcList.length())); + }else{ + srcListJson.setValue(srcList); + } + sourceListArrayJson.add(srcListJson); + } + } + targetTerm.setSourceList(sourceListArrayJson); + } + if(destIP_map!=null){ + //Destination List + List<AddressJson> destListArrayJson= new ArrayList<AddressJson>(); + for(String destList:destIP_map.get(tl).split(",")){ + AddressJson destListJson= new AddressJson(); + if(destList.equals("ANY")){ + destListJson.setType("any"); + destListArrayJson.add(destListJson); + break; + }else{ + destListJson.setType("REFERENCE"); + if(destList.startsWith("Group_")){ + destListJson.setValue(destList.substring(6,destList.length())); + }else{ + destListJson.setValue(destList); + } + destListArrayJson.add(destListJson); + } + } + targetTerm.setDestinationList(destListArrayJson); + } + //ExpandablePrefixIPList + if ((srcIP_map!=null) && (destIP_map!=null)) + { + String collateString = (srcIP_map.get(tl) + "," + destIP_map + .get(tl)); + expandablePrefixIPList.add(collateString); + } + else if(srcIP_map!=null){ + expandablePrefixIPList.add(srcIP_map.get(tl)); + } + else if(destIP_map!=null){ + expandablePrefixIPList.add(destIP_map.get(tl)); + } + termList.add(targetTerm); + targetTerm.setPosition("" + (ruleCount++)); + } + TermCollector tc = new TermCollector(); + List<SecurityZone> securityZoneData = securityZoneDao.getSecurityZoneData(); + for (int j =0 ; j< securityZoneData.size() ; j++){ + jpaSecurityZone = securityZoneData.get(j); + if (jpaSecurityZone.getZoneName().equals(policyAdapter.getSecurityZone())){ + tc.setSecurityZoneId(jpaSecurityZone.getZoneValue()); + setParentSecurityZone(jpaSecurityZone.getZoneValue());//For storing the securityZone IDs to the DB + break; + } + } + + tc.setServiceTypeId("/v0/firewall/pan"); + tc.setConfigName(policyAdapter.getConfigName()); + + if(policyAdapter.getFwPolicyType().equalsIgnoreCase("Child Policy")){ + String securityZoneQuery="SELECT SECURITYZONE FROM FWPARENT WHERE PARENT='"; + securityZoneQuery=securityZoneQuery+policyAdapter.getParentForChild()+"'"; + List<String> securityZoneValue= queryToDatabase(securityZoneQuery); + tc.setPrimaryParentZoneId(securityZoneValue.get(0)); + } + //Astra is rejecting the packet when it sees a new JSON field, so removing it for now. + //tc.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_FW)); + + DeployNowJson deployNow= new DeployNowJson(); + deployNow.setDeployNow(false); + + tc.setDeploymentOption(deployNow); + + Set<ServiceListJson> servListArray = new HashSet<ServiceListJson>(); + Set<ServiceGroupJson> servGroupArray= new HashSet<ServiceGroupJson>(); + Set<AddressGroupJson> addrGroupArray= new HashSet<AddressGroupJson>(); + + ServiceGroupJson targetSg= null; + AddressGroupJson addressSg=null; + ServiceListJson targetAny= null; + ServiceListJson targetAnyTcp=null; + ServiceListJson targetAnyUdp=null; + + for(String serviceList:expandableServicesList){ + for(String t: serviceList.split(",")){ + if((!t.startsWith("Group_"))){ + if(!t.equals("ANY")){ + ServiceList sl = new ServiceList(); + targetSl= new ServiceListJson(); + sl= mappingServiceList(t); + targetSl.setName(sl.getServiceName()); + targetSl.setDescription(sl.getServiceDescription()); + targetSl.setTransportProtocol(sl.getServiceTransProtocol()); + targetSl.setType(sl.getServiceType()); + targetSl.setPorts(sl.getServicePorts()); + servListArray.add(targetSl); + }else{ + //Any for destinationServices. + //Add names any, any-tcp, any-udp to the serviceGroup object. + targetAny= new ServiceListJson(); + targetAny.setName("any"); + targetAny.setType("SERVICE"); + targetAny.setTransportProtocol("any"); + targetAny.setPorts("any"); + + servListArray.add(targetAny); + + targetAnyTcp= new ServiceListJson(); + targetAnyTcp.setName("any-tcp"); + targetAnyTcp.setType("SERVICE"); + targetAnyTcp.setTransportProtocol("tcp"); + targetAnyTcp.setPorts("any"); + + servListArray.add(targetAnyTcp); + + targetAnyUdp= new ServiceListJson(); + targetAnyUdp.setName("any-udp"); + targetAnyUdp.setType("SERVICE"); + targetAnyUdp.setTransportProtocol("udp"); + targetAnyUdp.setPorts("any"); + + servListArray.add(targetAnyUdp); + } + }else{//This is a group + GroupServiceList sg= new GroupServiceList(); + targetSg= new ServiceGroupJson(); + sg= mappingServiceGroup(t); + + String name=sg.getGroupName(); + //Removing the "Group_" prepending string before packing the JSON + targetSg.setName(name.substring(6,name.length())); + List<ServiceMembers> servMembersList= new ArrayList<ServiceMembers>(); + + for(String groupString: sg.getServiceList().split(",")){ + ServiceMembers serviceMembers= new ServiceMembers(); + serviceMembers.setType("REFERENCE"); + serviceMembers.setName(groupString); + servMembersList.add(serviceMembers); + //Expand the group Name + ServiceList expandGroupSl = new ServiceList(); + targetSl= new ServiceListJson(); + expandGroupSl= mappingServiceList(groupString); + + targetSl.setName(expandGroupSl.getServiceName()); + targetSl.setDescription(expandGroupSl.getServiceDescription()); + targetSl.setTransportProtocol(expandGroupSl.getServiceTransProtocol()); + targetSl.setType(expandGroupSl.getServiceType()); + targetSl.setPorts(expandGroupSl.getServicePorts()); + servListArray.add(targetSl); + } + + targetSg.setMembers(servMembersList); + servGroupArray.add(targetSg); + + } + } + } + + Set<PrefixIPList> prefixIPList = new HashSet<PrefixIPList>(); + for(String prefixList:expandablePrefixIPList){ + for(String prefixIP: prefixList.split(",")){ + if((!prefixIP.startsWith("Group_"))){ + if(!prefixIP.equals("ANY")){ + List<AddressMembers> addMembersList= new ArrayList<AddressMembers>(); + List<String> valueDesc= new ArrayList<String>(); + PrefixIPList targetAddressList = new PrefixIPList(); + AddressMembers addressMembers= new AddressMembers(); + targetAddressList.setName(prefixIP); + + valueDesc = mapping(prefixIP); + targetAddressList.setDescription(valueDesc.get(1)); + + addressMembers.setType("SUBNET"); + addressMembers.setValue(valueDesc.get(0)); + + addMembersList.add(addressMembers); + + targetAddressList.setMembers(addMembersList); + prefixIPList.add(targetAddressList); + } + } + else{//This is a group + AddressGroup ag= new AddressGroup(); + addressSg= new AddressGroupJson(); + ag= mappingAddressGroup(prefixIP); + + String name=ag.getGroupName(); + //Removing the "Group_" prepending string before packing the JSON + addressSg.setName(name.substring(6,name.length())); + + List<AddressMembers> addrMembersList= new ArrayList<AddressMembers>(); + for(String groupString: ag.getPrefixList().split(",")){ + List<String> valueDesc= new ArrayList<String>(); + AddressMembers addressMembers= new AddressMembers(); + valueDesc= mapping (groupString); + if(valueDesc.size() > 0){ + addressMembers.setValue(valueDesc.get(0)); + } + addressMembers.setType("SUBNET"); + addrMembersList.add(addressMembers); + //Expand the group Name + } + addressSg.setMembers(addrMembersList); + addrGroupArray.add(addressSg); + } + + + } + } + + Set<Object> serviceGroup= new HashSet<Object>(); + + for(Object obj1:servGroupArray){ + serviceGroup.add(obj1); + } + + for(Object obj:servListArray){ + serviceGroup.add(obj); + } + + Set<Object> addressGroup= new HashSet<Object>(); + + for(Object addObj:prefixIPList){ + addressGroup.add(addObj); + } + + for(Object addObj1:addrGroupArray){ + addressGroup.add(addObj1); + } + + tc.setServiceGroups(serviceGroup); + tc.setAddressGroups(addressGroup); + tc.setFirewallRuleList(termList); + + + ObjectWriter om = new ObjectMapper().writer(); + try { + json = om.writeValueAsString(tc); + } catch (JsonGenerationException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + }catch (Exception e) { + e.printStackTrace(); + } + + return json; + } + + private List<String> mapping(String expandableList) { + String value = new String(); + String desc = new String(); + List <String> valueDesc= new ArrayList<String>(); + List<PREFIXLIST> prefixListData = prefixListDao.getPREFIXLISTData(); + for (int i = 0; i< prefixListData.size(); i++) { + PREFIXLIST prefixList = prefixListData.get(i); + if (prefixList.getPrefixListName().equals(expandableList)) { + value = prefixList.getPrefixListValue(); + valueDesc.add(value); + desc= prefixList.getDescription(); + valueDesc.add(desc); + break; + } + } + return valueDesc; + } + + private ServiceList mappingServiceList(String expandableList) { + ServiceList serviceList=null; + List<ServiceList> serviceListData = serviceListDao.getServiceListData(); + for (int i = 0; i< serviceListData.size(); i++) { + serviceList = serviceListData.get(i); + if (serviceList.getServiceName().equals(expandableList)) { + break; + } + } + return serviceList; + } + + private GroupServiceList mappingServiceGroup(String expandableList) { + + GroupServiceList serviceGroup=null; + List<GroupServiceList> serviceGroupData = serviceGroupDao.getGroupServiceListData(); + for (int i = 0; i< serviceGroupData.size(); i++) { + serviceGroup = serviceGroupData.get(i); + if (serviceGroup.getGroupName().equals(expandableList)) { + break; + } + } + return serviceGroup; + } + + private AddressGroup mappingAddressGroup(String expandableList) { + + AddressGroup addressGroup=null; + List<AddressGroup> addressGroupData = addressGroupDao.getAddressGroupData(); + for (int i = 0; i< addressGroupData.size(); i++) { + addressGroup = addressGroupData.get(i); + if (addressGroup.getGroupName().equals(expandableList)) { + break; + } + } + return addressGroup; + } + + public void PrePopulateFWPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList<Object>(); + fwAttributeList = new ArrayList<Object>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + // policy name value is the policy name without any prefix and Extensions. + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") +3, policyAdapter.getPolicyName().lastIndexOf(".")); + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating form data for Config Policy selected:"+ policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + + ObjectMapper mapper = new ObjectMapper(); + + TermCollector tc1=null; + BufferedReader br=null; + try { + //Json conversion. + String data=null; + SecurityZone jpaSecurityZone; + File file = new File(PolicyController.getConfigHome()+ File.separator+ policyAdapter.getDirPath().replace(File.separator, ".")+"."+ policyAdapter.getOldPolicyFileName() +".json"); + // Get data from this file using a file reader. + FileReader fr = new FileReader(file); + // To store the contents read via File Reader + br = new BufferedReader(fr); + // Read br and store a line in 'data', print data + data = br.readLine(); + tc1 = (TermCollector)mapper.readValue(data, TermCollector.class); + List<SecurityZone> securityZoneData = securityZoneDao.getSecurityZoneData(); + for (int i = 0; i < securityZoneData.size() ; i++) { + jpaSecurityZone = securityZoneData.get(i); + if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())){ + policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName()); + break; + } + } + if(tc1.getPrimaryParentZoneId()!=null)//Child policy + { + policyAdapter.setFwPolicyType("Child Policy"); + + String pathName=policyAdapter.getParentPath().toString(); + String scope= pathName.substring(pathName.lastIndexOf(File.separator)+1); + String fullPathName=scope+".Config_FW_"+policyNameValue; + + String query= "select parent from FWChildToParent where child='"; + query=query+fullPathName+"'"; + + List<String> parentName=queryToDatabase(query); + policyAdapter.setParentForChild(parentName.get(0)); + + } + else{//Parent Policy + policyAdapter.setFwPolicyType("Parent Policy"); + //Retrieving the Dictionary combo list. + String desc = policy.getDescription(); + String descripComboList = desc.substring(desc.indexOf("@comboList:")+11,desc.length()) ; + Map<String, String> parentMap = new HashMap<String, String>(); + for(String value : descripComboList.split(",")){ + parentMap.put("option", value); + fwAttributeList.add(parentMap); + } + policyAdapter.setFwattributes(fwAttributeList); + } + } + catch(Exception e) { + logger.error("Exception Caused while Retriving the JSON body data" +e); + } + finally { + try { + if (br != null)br.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + for (Term t : tc1.getFirewallRuleList()) { + Map<String, String> termMap = new HashMap<String, String>(); + termMap.put("option", t.getRuleName()); + attributeList.add(termMap); + } + policyAdapter.setAttributes(attributeList); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + int index = 0; + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + if (index == 1) { + policyAdapter.setConfigName(value); + } + if (index == 2){ + policyAdapter.setRiskType(value); + } + + if (index == 3){ + policyAdapter.setRiskLevel(value); + } + + if (index == 4){ + policyAdapter.setGuard(value); + } + if (index == 5 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + index++; + } + } + } + } + } + } + } + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + @RequestMapping(value={"/policyController/ViewFWPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView setFWViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + termCollectorList = new ArrayList<String>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").toString(), PolicyAdapter.class); + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); + termCollectorList.add(key); + } + } + } + TermList jpaTermList; + String ruleSrcList=null; + String ruleDestList=null; + String ruleSrcPort=null; + String ruleDestPort=null; + String ruleAction=null; + List <String> valueDesc= new ArrayList<String>(); + StringBuffer displayString = new StringBuffer(); + for (String id : termCollectorList) { + jpaTermList = termListDao.getTermListValueByName(id); + if (jpaTermList != null){ + ruleSrcList= ((TermList) jpaTermList).getSrcIPList(); + if ((ruleSrcList!= null) && (!ruleSrcList.isEmpty()) && !ruleSrcList.equals("null")){ + displayString.append("Source IP List: " + ((TermList) jpaTermList).getSrcIPList()); + displayString.append(" ; \t\n"); + for(String srcList:ruleSrcList.split(",")){ + if(srcList.startsWith("Group_")){ + AddressGroup ag= new AddressGroup(); + ag= mappingAddressGroup(srcList); + displayString.append("\n\t"+"Group has :"+ag.getPrefixList()+"\n"); + for(String groupItems:ag.getPrefixList().split(",")){ + valueDesc=mapping(groupItems); + displayString.append("\n\t"+"Name: "+groupItems); + if(!valueDesc.isEmpty()){ + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + } + displayString.append("\n"); + } + }else{ + if(!srcList.equals("ANY")){ + valueDesc=mapping(srcList); + displayString.append("\n\t"+"Name: "+srcList); + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + displayString.append("\n"); + } + } + } + displayString.append("\n"); + } + ruleDestList= ((TermList) jpaTermList).getDestIPList(); + if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& !ruleDestList.equals("null")){ + displayString.append("Destination IP List: " + ((TermList) jpaTermList).getDestIPList()); + displayString.append(" ; \t\n"); + for(String destList:ruleDestList.split(",")){ + if(destList.startsWith("Group_")){ + AddressGroup ag= new AddressGroup(); + ag= mappingAddressGroup(destList); + displayString.append("\n\t"+"Group has :"+ag.getPrefixList()+"\n"); + for(String groupItems:ag.getPrefixList().split(",")){ + valueDesc=mapping(groupItems); + displayString.append("\n\t"+"Name: "+groupItems); + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + displayString.append("\n\t"); + } + }else{ + if(!destList.equals("ANY")){ + valueDesc=mapping(destList); + displayString.append("\n\t"+"Name: "+destList); + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + displayString.append("\n\t"); + } + } + } + displayString.append("\n"); + } + + ruleSrcPort=((TermList) jpaTermList).getSrcPortList(); + if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !ruleSrcPort.equals("null")) { + displayString.append("\n"+"Source Port List:" + + ruleSrcPort); + displayString.append(" ; \t\n"); + } + + ruleDestPort= ((TermList) jpaTermList).getDestPortList(); + if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !ruleDestPort.equals("null")) { + displayString.append("\n"+"Destination Port List:" + + ruleDestPort); + displayString.append(" ; \t\n"); + for(String destServices:ruleDestPort.split(",")){ + if(destServices.startsWith("Group_")){ + GroupServiceList sg= new GroupServiceList(); + sg= mappingServiceGroup(destServices); + displayString.append("\n\t"+"Service Group has :"+sg.getServiceList()+"\n"); + for(String groupItems:sg.getServiceList().split(",")){ + ServiceList sl= new ServiceList(); + sl= mappingServiceList(groupItems); + displayString.append("\n\t"+"Name: "+ + sl.getServiceName()); + displayString.append("\n\t"+"Description: "+ + sl.getServiceDescription()); + displayString.append("\n\t"+"Transport-Protocol: "+ + sl.getServiceTransProtocol()); + displayString.append("\n\t"+"Ports: "+ + sl.getServicePorts()); + displayString.append("\n"); + } + } + else{ + if(!destServices.equals("ANY")){ + ServiceList sl= new ServiceList(); + sl= mappingServiceList(destServices); + displayString.append("\n\t"+"Name: "+ + sl.getServiceName()); + displayString.append("\n\t"+"Description: "+ + sl.getServiceDescription()); + displayString.append("\n\t"+"Transport-Protocol: "+ + sl.getServiceTransProtocol()); + displayString.append("\n\t"+"Ports: "+ + sl.getServicePorts()); + displayString.append("\n"); + } + } + } + displayString.append("\n"); + } + + ruleAction=(jpaTermList).getAction(); + if ( ruleAction!= null && (!ruleAction.isEmpty())) { + displayString.append("\n"+"Action List:" + + ruleAction); + displayString.append(" ; \t\n"); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(displayString); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + return null; + } + + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java new file mode 100644 index 000000000..f5c0a576c --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java @@ -0,0 +1,484 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreatePolicyController extends RestrictedBaseController{ + private static Logger logger = FlexLogger.getLogger(CreatePolicyController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreatePolicyController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){ + CreatePolicyController.policyVersionDao = policyVersionDao; + CreatePolicyController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreatePolicyController.policyNotificationDao = policyNotificationDao; + } + + public CreatePolicyController(){} + + protected PolicyAdapter policyAdapter = null; + private String ruleID = ""; + private ArrayList<Object> attributeList; + boolean isValidForm = false; + private int riskLevelCount; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/get_RiskLevelValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getRiskLevelValuesData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + List<String> riskLevelList = new ArrayList<String>(); + riskLevelCount = 5; + for (int i = 1; i <= riskLevelCount; i++) { + riskLevelList.add(String.valueOf(i)); + } + model.put("riskLevelDatas", mapper.writeValueAsString(riskLevelList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/get_GuardlValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getGuardValuesData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + List<String> guardList = new ArrayList<String>(); + guardList.add("True"); + guardList.add("False"); + model.put("guardDatas", mapper.writeValueAsString(guardList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + + @RequestMapping(value={"/policyController/save_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL, false); + policyData.setTtlDate(newDate); + } + + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_" + policyData.getPolicyName(); + List<PolicyVersion> policyVersionlist = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionlist.size() > 0) { + for(int i = 0; i < policyVersionlist.size(); i++) { + PolicyVersion entityItem = policyVersionlist.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + + Map<String, String> successMap = new HashMap<String, String>(); + Map<String, String> attributeMap = new HashMap<String, String>(); + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List<RuleAlgorithms> ruleAlgorithmList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString(); + attributeMap.put(key, value); + } + } + } + policyData.setDynamicFieldConfigAttributes(attributeMap); + + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + 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; + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + public void PrePopulateBaseConfigPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList<Object>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + policyAdapter.setConfigBodyData(readBaseConfigJSONFile(policyAdapter)); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1 , policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + int index = 0; + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is EcompName, so set that value. + if (index == 1) { + policyAdapter.setEcompName(value); + } + if (index == 2){ + policyAdapter.setRiskType(value); + } + + if (index == 3){ + policyAdapter.setRiskLevel(value); + } + + if (index == 4){ + policyAdapter.setGuard(value); + } + if (index == 5 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + if (index == 6){ + policyAdapter.setConfigName(value); + } + // After Ecomp and Config it is optional to have attributes, so + // check weather dynamic values or there or not. + if (index >= 7) { + Map<String, String> attribute = new HashMap<String, String>(); + attribute.put("option", attributeId); + attribute.put("number", value); + attributeList.add(attribute); + } + index++; + } + } + } + } + } + } + + policyAdapter.setAttributes(attributeList); + } + List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + for (Object o : ruleList) { + if (o instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + policyAdapter.setRuleID(((RuleType) o).getRuleId()); + } + } + } + } + + private String readBaseConfigJSONFile(PolicyAdapter policyAdapter) { + String fileName = policyAdapter.getPolicyName(); + String fileLocation = null; + if (fileName != null && fileName.contains("Config")) { + fileLocation = PolicyController.getConfigHome(); + } + if (logger.isDebugEnabled()) { + logger.debug("Attempting to read file from the location: " + fileLocation); + } + + if (fileLocation == null) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error with the FileName: " + fileName); + return fileLocation; + } + + + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + String extension = null; + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName)) { + // For config form we have set the ConfigType Based on the extention. + if (fileName.contains("Config")) { + extension = file.getName().substring(file.getName().lastIndexOf('.') + 1); + // Based on file type set Combobox config value + if (extension.equals("txt")) { + policyAdapter.setConfigType("OTHER"); + } else { + policyAdapter.setConfigType(extension.toUpperCase()); + } + } + // Reading the file + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + return sb.toString(); + } catch (FileNotFoundException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); + } catch (IOException e1) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e1.getMessage()); + } + } + } + return null; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DashboardController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DashboardController.java new file mode 100644 index 000000000..301c824f0 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DashboardController.java @@ -0,0 +1,430 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.management.AttributeNotFoundException; +import javax.management.InstanceNotFoundException; +import javax.management.MBeanException; +import javax.management.MalformedObjectNameException; +import javax.management.ObjectName; +import javax.management.ReflectionException; +import javax.management.remote.JMXConnector; +import javax.management.remote.JMXConnectorFactory; +import javax.management.remote.JMXServiceURL; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.openecomp.policy.dao.SystemLogDbDao; +import org.openecomp.policy.model.PDPGroupContainer; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDP; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping({"/"}) +public class DashboardController extends RestrictedBaseController{ + private static final Logger logger = FlexLogger.getLogger(DashboardController.class); + @Autowired + SystemLogDbDao systemDAO; + + private int pdpCount; + private PDPGroupContainer pdpConatiner; + private ArrayList<Object> pdpStatusData; + private ArrayList<Object> papStatusData; + private ArrayList<Object> policyActivityData; + + + + @RequestMapping(value={"/get_DashboardLoggingData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/get_DashboardSystemAlertData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/get_DashboardPAPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + addPAPToTable(); + model.put("papTableDatas", mapper.writeValueAsString(papStatusData)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/get_DashboardPDPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + this.pdpConatiner = new PDPGroupContainer(PolicyController.getPapEngine()); + addPDPToTable(); + model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/get_DashboardPolicyActivityData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + this.pdpConatiner = new PDPGroupContainer(PolicyController.getPapEngine()); + addPolicyToTable(); + model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + /* + * Add the PAP information to the PAP Table + */ + public void addPAPToTable(){ + papStatusData = new ArrayList<Object>(); + File folder = new File(PolicyController.getGitPath().toAbsolutePath().toString()); + String papStatus = null; + try { + Set<EcompPDPGroup> groups = PolicyController.getPapEngine().getEcompPDPGroups(); + if (groups == null) { + papStatus = "UNKNOWN"; + throw new PAPException("PAP not running"); + }else { + papStatus = "IS_OK"; + } + } catch (PAPException | NullPointerException e1) { + papStatus = "CANNOT_CONNECT"; + logger.error("Error getting PAP status, PAP not responding to requests"); + } + String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + JSONObject object = new JSONObject(); + object.put("system", papURL); + object.put("status", papStatus); + object.put("noOfPolicy", countFilesInDirectory(folder)); + object.put("noOfConnectedTrap", pdpCount); + papStatusData.add(0, object); + } + + private int countFilesInDirectory(File directory) { + int count = 0; + for (File file : directory.listFiles()) { + if (file.isFile() && file.getName().endsWith(".xml")) { + count++; + } + if (file.isDirectory()) { + count += countFilesInDirectory(file); + } + } + return count; + } + /** + * Add PDP Information to the PDP Table + * + */ + public void addPDPToTable(){ + pdpCount = 0; + pdpStatusData = new ArrayList<Object>(); + long naCount; + long denyCount = 0; + long permitCount = 0; + for (PDPGroup group : this.pdpConatiner.getGroups()){ + for (PDP pdp : group.getPdps()){ + naCount = -1; + if (pdp.getStatus().getStatus().toString() == "UP_TO_DATE" && ((EcompPDP) pdp).getJmxPort() != 0){ + String pdpIpAddress = parseIPSystem(pdp.getId()); + int port = ((EcompPDP) pdp).getJmxPort(); + if (port != 0) + logger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port); + naCount = getRequestCounts(pdpIpAddress, port, "pdpEvaluationNA"); + permitCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationPermit"); + denyCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationDeny"); + } + if (naCount == -1){ + JSONObject object = new JSONObject(); + object.put("id", pdp.getId()); + object.put("name", pdp.getName()); + object.put("groupname", group.getName()); + object.put("status", pdp.getStatus().getStatus().toString()); + object.put("description", pdp.getDescription()); + object.put("permitCount", "NA"); + object.put("denyCount", "NA"); + object.put("naCount", "NA"); + pdpStatusData.add(object); + }else{ + JSONObject object = new JSONObject(); + object.put("id", pdp.getId()); + object.put("name", pdp.getName()); + object.put("groupname", group.getName()); + object.put("status", pdp.getStatus().getStatus().toString()); + object.put("description", pdp.getDescription()); + object.put("permitCount", permitCount); + object.put("denyCount", denyCount); + object.put("naCount", naCount); + pdpStatusData.add(object); + } + pdpCount++; + } + } + } + + private static String parseIPSystem(String line) { + Pattern pattern = Pattern.compile("://(.+?):"); + Matcher ip = pattern.matcher(line); + if (ip.find()) + { + return ip.group(1); + } + return null; + } + + /* + * Contact JMX Connector Sever and return the value of the given jmxAttribute + */ + @SuppressWarnings("rawtypes") + private long getRequestCounts(String host, int port, String jmxAttribute) { + + logger.debug("Create an RMI connector client and connect it to the JMX connector server"); + HashMap map = new HashMap(); + map = null; + JMXConnector jmxConnection; + try { + jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map); + jmxConnection.connect(); + Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute); + jmxConnection.close(); + logger.debug("pdpEvaluationNA value retreived: " + o); + return (long) o; + } catch (MalformedURLException e) { + logger.error("MalformedURLException for JMX connection"); + } catch (IOException e) { + logger.error("Error in reteriving" + jmxAttribute + " from JMX connection"); + } catch (AttributeNotFoundException e) { + logger.error("AttributeNotFoundException " + jmxAttribute + " for JMX connection"); + } catch (InstanceNotFoundException e) { + logger.error("InstanceNotFoundException " + host + " for JMX connection"); + } catch (MalformedObjectNameException e) { + logger.error("MalformedObjectNameException for JMX connection"); + } catch (MBeanException e) { + logger.error("MBeanException for JMX connection"); + e.printStackTrace(); + } catch (ReflectionException e) { + logger.error("ReflectionException for JMX connection"); + } + + return -1; + } + + private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException{ + return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"); + } + + + /* + * Add the information to the Policy Table + */ + private void addPolicyToTable() { + policyActivityData = new ArrayList<Object>(); + int i = 1; + String policyID = null; + int policyFireCount = 0; + Map<String, String> policyMap = new HashMap<>(); + Object policyList = null; + //get list of policy + + for (PDPGroup group : this.pdpConatiner.getGroups()){ + for (PDPPolicy policy : group.getPolicies()){ + try{ + policyMap.put(policy.getPolicyId().replace(" ", ""), policy.getId()); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+policy.getName() +e); + } + } + + for (PDP pdp : group.getPdps()){ + // Add rows to the Policy Table + policyList = null; + if (pdp.getStatus().getStatus().toString() == "UP_TO_DATE" && ((EcompPDP) pdp).getJmxPort() != 0){ + String pdpIpAddress = parseIPSystem(pdp.getId()); + policyList = getPolicy(pdpIpAddress, ((EcompPDP) pdp).getJmxPort(), "policyCount"); + } + if (policyList != null && policyList.toString().length() > 3){ + String[] splitPolicy = policyList.toString().split(","); + for (String policyKeyValue : splitPolicy){ + policyID = urnPolicyID(policyKeyValue); + policyFireCount = countPolicyID(policyKeyValue); + if (policyID != null ){ + if (policyMap.containsKey(policyID)){ + JSONObject object = new JSONObject(); + object.put("policyId", policyMap.get(policyID)); + object.put("fireCount", policyFireCount); + object.put("system", pdp.getId()); + policyActivityData.add(i, object); + i++; + } + } + } + }else { + if (policyList != null){ + JSONObject object = new JSONObject(); + object.put("policyId", "Unable to retrieve policy information"); + object.put("fireCount", "NA"); + object.put("system", pdp.getId()); + policyActivityData.add(i, object); + i++; + }else{ + JSONObject object = new JSONObject(); + object.put("policyId", "Unable to access PDP JMX Server"); + object.put("fireCount", "NA"); + object.put("system", pdp.getId()); + policyActivityData.add(i, object); + i++; + } + } + + } + } + } + + /* + * Contact JMX Connector Sever and return the list of {policy id , count} + */ + @SuppressWarnings("rawtypes") + private Object getPolicy(String host, int port, String jmxAttribute){ + logger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host); + HashMap map = new HashMap(); + map = null; + JMXConnector jmxConnection; + try { + jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map); + jmxConnection.connect(); + Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap"); + jmxConnection.close(); + logger.debug("policyMap value retreived: " + o); + return o; + } catch (MalformedURLException e) { + logger.error("MalformedURLException for JMX connection"); + } catch (IOException e) { + logger.error("AttributeNotFoundException for policyMap" ); + } catch (AttributeNotFoundException e) { + logger.error("AttributeNotFoundException for JMX connection"); + } catch (InstanceNotFoundException e) { + logger.error("InstanceNotFoundException " + host + " for JMX connection"); + } catch (MalformedObjectNameException e) { + logger.error("MalformedObjectNameException for JMX connection"); + } catch (MBeanException e) { + logger.error("MBeanException for JMX connection"); + e.printStackTrace(); + } catch (ReflectionException e) { + logger.error("ReflectionException for JMX connection"); + } + + return null; + + } + + private static String urnPolicyID(String line){ + String[] splitLine = line.toString().split("="); + String removeSpaces = splitLine[0].replaceAll("\\s+", ""); + return removeSpaces.replace("{", ""); + } + + private static Integer countPolicyID(String line){ + String[] splitLine = line.toString().split("="); + String sCount = splitLine[1].replace("}", ""); + int intCount = Integer.parseInt(sCount); + return intCount; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java new file mode 100644 index 000000000..20cde7f43 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java @@ -0,0 +1,507 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBElement; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.servlet.ModelAndView; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; + +@Controller +@RequestMapping("/") +public class DecisionPolicyController extends RestrictedBaseController { + private static final Logger logger = FlexLogger.getLogger(DecisionPolicyController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private DecisionPolicyController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){ + DecisionPolicyController.policyVersionDao = policyVersionDao; + DecisionPolicyController.ruleAlgorithmsDao = ruleAlgorithmsDao; + DecisionPolicyController.policyNotificationDao = policyNotificationDao; + } + + public DecisionPolicyController(){} + + protected PolicyAdapter policyAdapter = null; + private static String ruleID = ""; + private ArrayList<Object> attributeList; + private ArrayList<Object> decisionList; + private ArrayList<Object> ruleAlgorithmList; + protected LinkedList<Integer> ruleAlgoirthmTracker; + public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/policyController/save_DecisionPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveDecisionPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Decision_" + policyData.getPolicyName(); + List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map<String, String> successMap = new HashMap<String, String>(); + Map<String, String> attributeMap = new HashMap<String, String>(); + Map<String, String> settingsMap = new HashMap<String, String>(); + + List<String> dynamicRuleAlgorithmLabels = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmCombo = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmField1 = new LinkedList<String>(); + List<String> dynamicRuleAlgorithmField2 = new LinkedList<String>(); + List<Object> dynamicVariableList = new LinkedList<Object>(); + List<String> dataTypeList = new LinkedList<String>(); + + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString(); + attributeMap.put(key, value); + } + } + } + + if(policyData.getSettings().size() > 0){ + for(Object settingsData : policyData.getSettings()){ + if(settingsData instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) settingsData).get("option").toString(); + String value = ((LinkedHashMap<?, ?>) settingsData).get("number").toString(); + settingsMap.put(key, value); + } + } + } + + if(policyData.getRuleAlgorithmschoices().size() > 0){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); + String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); + dynamicRuleAlgorithmLabels.add(label); + dynamicRuleAlgorithmField1.add(key); + dynamicRuleAlgorithmCombo.add(rule); + dynamicRuleAlgorithmField2.add(value); + } + } + } + + policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); + policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + policyData.setDynamicVariableList(dynamicVariableList); + policyData.setDynamicSettingsMap(settingsMap); + policyData.setDynamicFieldConfigAttributes(attributeMap); + policyData.setDataTypeList(dataTypeList); + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List<PolicyVersion> vesionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (vesionList.size() > 0) { + for(int i = 0; i < vesionList.size(); i++) { + PolicyVersion entityItem = vesionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + 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; + } + + public void PrePopulateDecisionPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList<Object>(); + decisionList = new ArrayList<Object>(); + ruleAlgorithmList = new ArrayList<Object>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1, policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target != null) { + // under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AntOfType we have AllOfType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOfType we have Mathch. + List<MatchType> matchList = allOf.getMatch(); + int index = 0; + if (matchList != null) { + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is EcompName, so set that value. + if (index == 0) { + policyAdapter.setEcompName(value); + } + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic componet at index 0. + if (index >= 1) { + Map<String, String> attribute = new HashMap<String, String>(); + attribute.put("option", attributeId); + attribute.put("number", value); + attributeList.add(attribute); + } + index++; + } + } + policyAdapter.setAttributes(attributeList); + } + } + } + } + + List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + int index = 0; + for (Object object : ruleList) { + if (object instanceof VariableDefinitionType) { + VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object; + Map<String, String> settings = new HashMap<String, String>(); + settings.put("option", variableDefinitionType.getVariableId()); + JAXBElement<AttributeValueType> attributeValueTypeElement = (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression(); + if (attributeValueTypeElement != null) { + AttributeValueType attributeValueType = attributeValueTypeElement.getValue(); + settings.put("number", attributeValueType.getContent().get(0).toString()); + } + decisionList.add(settings); + } else if (object instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + ruleID = ((RuleType) object).getRuleId(); + if (((RuleType) object).getEffect().equals(EffectType.PERMIT)) { + ConditionType condition = ((RuleType) object).getCondition(); + if (condition != null) { + ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); + ruleAlgoirthmTracker = new LinkedList<Integer>(); + // Populating Rule Algorithms starting from compound. + prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } + }else if(((RuleType) object).getEffect().equals(EffectType.DENY)) { + if(((RuleType) object).getAdviceExpressions()!=null){ + if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("AAF")){ + policyAdapter.setRuleProvider("AAF"); + break; + } + }else{ + policyAdapter.setRuleProvider("Custom"); + } + } + } + } + } + policyAdapter.setSettings(decisionList); + } + + } + + private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, List<JAXBElement<?>> jaxbDecisionTypes) { + Map<String, String> ruleMap = new HashMap<String, String>(); + ruleMap.put("id", "A" + (index +1)); + Map<String, String> dropDownMap = PolicyController.getDropDownMap(); + for (String key : dropDownMap.keySet()) { + String keyValue = dropDownMap.get(key); + if (keyValue.equals(decisionApply.getFunctionId())) { + ruleMap.put("dynamicRuleAlgorithmCombo", key); + } + } + // Populate the key and value fields + if (((jaxbDecisionTypes.get(0).getValue()) instanceof AttributeValueType)) { + ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue(); + List<JAXBElement<?>> jaxbInnerDecisionTypes = innerDecisionApply.getExpression(); + if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) { + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(0).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) { + VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", "S_"+ variableReference.getVariableId()); + + + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + ruleAlgorithmList.add(ruleMap); + } + + private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) { + boolean isCompoundRule = true; + List<JAXBElement<?>> jaxbDecisionTypes = decisionApply.getExpression(); + for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) { + // If There is Attribute Value under Decision Type that means we came to the final child + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating rule algoirthm: " + index); + } + // Check to see if Attribute Value exists, if yes then it is not a compound rule + if(jaxbElement.getValue() instanceof AttributeValueType) { + prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes); + ruleAlgoirthmTracker.addLast(index); + isCompoundRule = false; + index++; + } + } + if (isCompoundRule) { + // As it's compound rule, Get the Apply types + for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) { + ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply); + } + // Populate combo box + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating Compound rule algorithm: " + index); + } + Map<String, String> rule = new HashMap<String, String>(); + for (String key : PolicyController.getDropDownMap().keySet()) { + String keyValue = PolicyController.getDropDownMap().get(key); + if (keyValue.equals(decisionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", key); + } + } + + rule.put("id", "A" + (index +1)); + // Populate Key and values for Compound Rule + rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 )); + ruleAlgoirthmTracker.removeLast(); + rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmList.add(rule); + index++; + } + return index; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PDPController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PDPController.java new file mode 100644 index 000000000..add650b1e --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PDPController.java @@ -0,0 +1,302 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.dao.GroupEntityDao; +import org.openecomp.policy.dao.PDPEntityDao; +import org.openecomp.policy.model.PDPGroupContainer; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPGroup; +import org.openecomp.policy.xacml.std.pap.StdPDP; +import org.openecomp.policy.xacml.std.pap.StdPDPGroup; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping({"/"}) +public class PDPController extends RestrictedBaseController { + private static final Logger logger = FlexLogger.getLogger(PDPController.class); + + @Autowired + GroupEntityDao groupDAO; + + @Autowired + PDPEntityDao pdpDAO; + + protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>()); + private PDPGroupContainer container; + + public synchronized void refreshGroups() { + synchronized(this.groups) { + this.groups.clear(); + try { + this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups()); + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Pap Engine is Null" + message); + } + + } + } + + @RequestMapping(value={"/get_PDPGroupContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPDPGroupContainerData(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group Container data" + e); + } + } + + @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group data" + e); + } + } + + @RequestMapping(value={"/pdp_Group/save_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePDPGroup(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()); + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class); + try { + if(pdpGroupData.getId() == null){ + this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription()); + }else{ + this.container.updateGroup(pdpGroupData); + } + + } catch (Exception e) { + String message = "Unable to create Group. Reason:\n" + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message); + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePDPGroup(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()); + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class); + if(pdpGroupData.getName().equals("Default")) { + throw new UnsupportedOperationException("You can't remove the Default Group."); + }else{ + this.container.removeGroup(pdpGroupData, null); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePDPToGroup(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()); + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + String update = root.get("update").toString(); + PdpData pdpGroupData = (PdpData)mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class); + StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); + try { + + if(update.contains("false")){ + this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort()); + }else{ + this.container.updateGroup(activeGroupData); + } + } catch (Exception e) { + String message = "Unable to create Group. Reason:\n" + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message); + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePDPFromGroup(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()); + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class); + StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); + + this.container.removePDP(deletePdp, activeGroupData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + String responseString = mapper.writeValueAsString(groups); + JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} + +class PdpData{ + String id; + int jmxPort; + String name; + String description; + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public int getJmxPort() { + return jmxPort; + } + public void setJmxPort(int jmxPort) { + this.jmxPort = jmxPort; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyController.java new file mode 100644 index 000000000..c4b254c8e --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyController.java @@ -0,0 +1,418 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.annotation.PostConstruct; +import javax.mail.MessagingException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.json.JSONObject; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.FunctionDefinitionDao; +import org.openecomp.policy.dao.PolicyEditorScopesDao; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RolesDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.model.PDPGroupContainer; +import org.openecomp.policy.model.Roles; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.XacmlAdminAuthorization; +import org.openecomp.policy.rest.dao.UserInfoDao; +import org.openecomp.policy.rest.jpa.Datatype; +import org.openecomp.policy.rest.jpa.FunctionDefinition; +import org.openecomp.policy.rest.jpa.PolicyEditorScopes; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.util.Webapps; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.http.MediaType; +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.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; + +import com.att.research.xacml.api.pap.PAPEngine; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@Controller +@RequestMapping("/") +public class PolicyController extends RestrictedBaseController { + private static final Logger LOGGER = FlexLogger.getLogger(PolicyController.class); + private static UserInfoDao userInfoDao; + private static PolicyVersionDao policyVersionDao; + private static RolesDao rolesDao; + private static PolicyEditorScopesDao policyEditorScopesDao; + private static WatchPolicyNotificationDao watchPolicyNotificationDao; + // Our authorization object + // + XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization(); + // + // The PAP Engine + // + private static PAPPolicyEngine papEngine; + private Path repositoryPath = null; + private static Path workspacePath; + private static Path gitPath; + public static String logTableLimit; + public static String systemAlertTableLimit; + public static String CONFIG_HOME = PolicyController.getConfigHome(); + public static String ACTION_HOME = PolicyController.getActionHome(); + protected static Map<String, String> dropDownMap = new HashMap<String, String>(); + public static Map<String, String> getDropDownMap() { + return dropDownMap; + } + + public static void setDropDownMap(Map<String, String> dropDownMap) { + PolicyController.dropDownMap = dropDownMap; + } + + public static String getDomain() { + return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn"); + } + + private static final Object mapAccess = new Object(); + private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null; + private static Map<String, FunctionDefinition> mapID2Function = null; + + private static FunctionDefinitionDao functionDefinitionDao; + + //Smtp Java Mail Properties + public static String smtpHost = null; + public static String smtpPort = null; + public static String smtpUsername = null; + public static String smtpPassword = null; + public static String smtpApplicationName = null; + public static String smtpEmailExtension = null; + //log db Properties + public static String logdbDriver = null; + public static String logdbUrl = null; + public static String logdbUserName = null; + public static String logdbPassword = null; + public static String logdbDialect = null; + + + @Autowired + private PolicyController(UserInfoDao userinfoDao, PolicyVersionDao policyVersionDao, FunctionDefinitionDao functionDefinitionDao, + RolesDao rolesDao, PolicyEditorScopesDao policyEditorScopesDao, WatchPolicyNotificationDao watchPolicyNotificationDao){ + PolicyController.userInfoDao = userinfoDao; + PolicyController.policyVersionDao = policyVersionDao; + PolicyController.functionDefinitionDao = functionDefinitionDao; + PolicyController.rolesDao = rolesDao; + PolicyController.policyEditorScopesDao = policyEditorScopesDao; + PolicyController.watchPolicyNotificationDao = watchPolicyNotificationDao; + } + + public PolicyController() { + } + + @PostConstruct + public void init(){ + Properties prop = new Properties(); + InputStream input = null; + try { + input = new FileInputStream("xacml.admin.properties"); + // load a properties file + prop.load(input); + // get the property values + smtpHost = prop.getProperty("ecomp.smtp.host"); + smtpPort = prop.getProperty("ecomp.smtp.port"); + smtpUsername = prop.getProperty("ecomp.smtp.userName"); + smtpPassword = prop.getProperty("ecomp.smtp.password"); + smtpApplicationName = prop.getProperty("ecomp.application.name"); + smtpEmailExtension = prop.getProperty("ecomp.smtp.emailExtension"); + //Log Database Properties + logdbDriver = prop.getProperty("xacml.log.db.driver"); + logdbUrl = prop.getProperty("xacml.log.db.url"); + logdbUserName = prop.getProperty("xacml.log.db.user"); + logdbPassword = prop.getProperty("xacml.log.db.password"); + logdbDialect = prop.getProperty("ecomp.dialect"); + //Get the Property Values for Dashboard tab Limit + try{ + logTableLimit = prop.getProperty("xacml.ecomp.dashboard.logTableLimit"); + systemAlertTableLimit = prop.getProperty("xacml.ecomp.dashboard.systemAlertTableLimit"); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e); + logTableLimit = "5000"; + systemAlertTableLimit = "2000"; + } + repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY)); + PolicyController.workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE), getDefaultWorkspace()); + setGitPath(Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString())); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties"); + } catch (IOException ex) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e); + } + } + } + + //Initialize the FunctionDefinition table at Server Start up + Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap(); + for (Datatype id : functionMap.keySet()) { + List<FunctionDefinition> functionDefinations = (List<FunctionDefinition>) functionMap.get(id); + for (FunctionDefinition functionDef : functionDefinations) { + dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); + } + } + + } + + public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() { + synchronized(mapAccess) { + if (mapDatatype2Function == null) { + buildFunctionMaps(); + } + } + return mapDatatype2Function; + } + + public static Map<String, FunctionDefinition> getFunctionIDMap() { + synchronized(mapAccess) { + if (mapID2Function == null) { + buildFunctionMaps(); + } + } + return mapID2Function; + } + + private static void buildFunctionMaps() { + mapDatatype2Function = new HashMap<Datatype, List<FunctionDefinition>>(); + mapID2Function = new HashMap<String, FunctionDefinition>(); + List<FunctionDefinition> functiondefinitions = functionDefinitionDao.getFunctionDefinition(); + for (int i = 0; i < functiondefinitions.size(); i ++) { + FunctionDefinition value = functiondefinitions.get(i); + mapID2Function.put(value.getXacmlid(), value); + if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) { + mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>()); + } + mapDatatype2Function.get(value.getDatatypeBean()).add(value); + } + } + + public static Map<String, Roles> getUserRoles(String userId) { + Map<String, Roles> scopes = new HashMap<String, Roles>(); + List<Roles> roles = rolesDao.getUserRoles(userId); + if (roles != null && roles.size() > 0) { + for (Roles role : roles) { + scopes.put(role.getScope(), role); + } + } + return scopes; + } + + public static List<String> getRolesOfUser(String userId) { + List<String> rolesList = new ArrayList<String>(); + List<Roles> roles = rolesDao.getUserRoles(userId); + for (Roles role: roles) { + rolesList.add(role.getRole()); + } + return rolesList; + } + + public static List<Roles> getRoles(String userId) { + return rolesDao.getUserRoles(userId); + } + + //Get List of User Roles + @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + String userId = UserUtils.getUserIdFromCookie(request); + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + //Policy tabs Model and View + @RequestMapping(value= {"/policy", "/policy/*" }, method = RequestMethod.GET) + public ModelAndView view(HttpServletRequest request){ + String myRequestURL = request.getRequestURL().toString(); + try { + // + // Set the URL for the RESTful PAP Engine + // + setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); + new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e); + } + Map<String, Object> model = new HashMap<String, Object>(); + return new ModelAndView("policy_Editor","model", model); + } + + public static String getDefaultWorkspace() { + return "admin"; + } + + public static PAPPolicyEngine getPapEngine() { + return papEngine; + } + + public void setPapEngine(PAPPolicyEngine papEngine) { + PolicyController.papEngine = papEngine; + } + + //Config and Action Directory's + public static String getConfigHome() { + return Webapps.getConfigHome(); + } + + public static String getActionHome() { + return Webapps.getActionHome(); + } + + public static Path getGitPath() { + return gitPath; + } + + public static void setGitPath(Path gitPath) { + PolicyController.gitPath = gitPath; + } + + public static String getUserName(String createdBy) { + String loginId = createdBy; + return userInfoDao.getUserName(loginId); + } + + public static boolean getActivePolicy(String query) { + if(policyVersionDao.getActiveVersionPolicy(query).size() > 0){ + return true; + }else{ + return false; + } + + } + + //Get the Active Version of Policy List from Policy Version table + public static List<PolicyVersion> getListOfActivePolicies(String query){ + return policyVersionDao.getActiveVersionPolicy(query); + } + + public static void updatePolicyVersion(String query) { + policyVersionDao.updateQuery(query); + } + + public static void SaveToPolicyVersion(PolicyVersion policyversion) { + policyVersionDao.Save(policyversion); + } + + public static PolicyVersion getPolicyEntityFromPolicyVersion(String query){ + PolicyVersion policyVersionEntity = policyVersionDao.getPolicyVersionEntityByName(query).get(0); + return policyVersionEntity; + } + + public static void SavePolicyScope(PolicyEditorScopes policyScope){ + policyEditorScopesDao.Save(policyScope); + } + + public static List<PolicyEditorScopes> getListOfPolicyEditorScopes(String query){ + return policyEditorScopesDao.getListOfPolicyScopes(query); + } + + public static void updatePolicyScopeEditorWithQuery(String policyScopeQuery) { + policyEditorScopesDao.updateQuery(policyScopeQuery); + + } + + public static void updatePolicyScopeEditor(PolicyEditorScopes policyScopeQuery) { + policyEditorScopesDao.update(policyScopeQuery); + + } + + public void WatchPolicyFunction(PolicyVersion entity, String policyName, String mode){ + PolicyNotificationMail email = new PolicyNotificationMail(); + try { + email.sendMail(entity, policyName, mode, watchPolicyNotificationDao); + } catch (MessagingException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e); + } + } + + //Switch Version + public JSONObject SwitchVersionPolicyContent(File policyFile) { + Path parent = Paths.get(policyFile.toString().substring(0, policyFile.toString().lastIndexOf(File.separator))); + String policyName = policyFile.toString().substring(policyFile.toString().indexOf("repository") +11); + String removeExtension = policyName.replace(".xml", ""); + String activeVersion = removeExtension.substring(removeExtension.lastIndexOf(".")+1); + String dbPolicyName = removeExtension.substring(0, removeExtension.lastIndexOf(".")); + String filterPolicyName = dbPolicyName.substring(dbPolicyName.lastIndexOf(File.separator)+1); + FileFilter fileFilter = new WildcardFileFilter(filterPolicyName + "." + "*" + ".xml"); + File[] files = ((File) parent.toFile()).listFiles(fileFilter); + List<String> av = new ArrayList<String>(); + for(File file : files){ + String fileName = file.toString().substring(file.toString().indexOf("repository") +11); + String removeXMLExtension = fileName.replace(".xml", ""); + String availableVersion = removeXMLExtension.substring(removeXMLExtension.lastIndexOf(".")+1); + av.add(availableVersion); + } + PolicyVersion entity = (PolicyVersion) policyVersionDao.getPolicyVersionEntityByName(dbPolicyName).get(0); + String highestVersion = Integer.toString(entity.getHigherVersion()); + JSONObject el = new JSONObject(); + el.put("activeVersion", activeVersion); + el.put("availableVersions", av); + el.put("highestVersion", highestVersion); + return el; + } + + public static Path getUserWorkspace() { + return PolicyController.workspacePath; + } + +} + diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java new file mode 100644 index 000000000..76fadb59d --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java @@ -0,0 +1,563 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyExportAdapter; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.elk.client.ElkConnector; +import org.openecomp.policy.model.Roles; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.utils.XACMLPolicyWriterWithPapNotify; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.servlet.ModelAndView; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@Controller +@RequestMapping("/") +public class PolicyExportAndImportController extends RestrictedBaseController { + private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class); + private ArrayList<File> selectedPolicy; + public static String CONFIG_HOME = PolicyController.getConfigHome(); + public static String ACTION_HOME = PolicyController.getActionHome(); + + private Set<String> scopes = null; + private List<String> roles = null; + private Boolean superadmin = false; + private Boolean showMessage = false; + private static final int BUFFER_SIZE = 4096; + private Path directory = PolicyController.getGitPath(); + + //Scopes Which Super Editor can't import + private Set<String> sEditorScopesCantCreate = new HashSet<String>(); + //List of scopes in Tar file + private Set<String> listOfTarNewScopes = new HashSet<String>(); + //List of xml policies + private ArrayList<String> xacmlFiles = new ArrayList<String>(); + //Scopes of the User based on the Roles + private List<String> userScopes = null; + //Directory names from tar file + private Set<String> directoryNames = new HashSet<String>(); + //compare the scopes of the user and tar file get unique + private Set<String> finalScopesToImport = new HashSet<String>(); + //final scopes User can import + private Set<String> finalScopes = new HashSet<String>(); + //User don't have permissions to import to scopes + private Set<String> roleIsNotSufficient = new HashSet<String>(); + //User don't have access to import new scopes + private Set<String> userDontHavePermission = new HashSet<String>(); + + private Map<String, Roles> scopeAndRoles = null; + + private static PolicyVersionDao policyVersionDao; + + @Autowired + ServletContext servletContext; + + @Autowired + private PolicyExportAndImportController(PolicyVersionDao policyVersionDao){ + PolicyExportAndImportController.policyVersionDao = policyVersionDao; + } + + public PolicyExportAndImportController(){} + + @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView ExportPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try{ + selectedPolicy = new ArrayList<File>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyExportAdapter adapter = mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class); + for (Object policyId : adapter.getPolicyDatas()) { + LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId; + Path file = Paths.get(selected.get("filePath").toString()); + selectedPolicy.add(file.toFile()); + } + // Grab our working repository + // + final Path repoPath = PolicyController.getGitPath().toAbsolutePath(); + if(CONFIG_HOME == null || ACTION_HOME == null ){ + CONFIG_HOME = PolicyController.getConfigHome(); + ACTION_HOME = PolicyController.getActionHome(); + } + Path configPath = Paths.get(CONFIG_HOME); + Path actionPath = Paths.get(ACTION_HOME); + String tempDir = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp"; + File temPath = new File(tempDir); + if(!temPath.exists()){ + temPath.mkdir(); + } + final Path tarFile = Paths.get(tempDir, "Repository.tar"); + try (OutputStream os = Files.newOutputStream(tarFile)) { + try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(os)) { + tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); + Files.walkFileTree(configPath, new SimpleFileVisitor<Path>() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + for (File policyId : selectedPolicy) { + // Get the current selection + String policyDir = policyId.toString(); + policyDir = policyDir.substring(policyDir.indexOf("repository")+11); + String path = policyDir.replace('\\', '.'); + if(path.contains("/")){ + path = policyDir.replace('/', '.'); + logger.info("print the path:" +path); + } + path = FilenameUtils.removeExtension(path); + if (path.endsWith(".xml")) { + path = path.substring(0, path.length() - 4); + } + File configFile = new File(path); + String fileName = FilenameUtils.removeExtension(file.getFileName().toString()); + File configHome = new File(fileName); + if(configFile.equals(configHome)) { + Path relative = configPath.relativize(file); + TarArchiveEntry entry = new TarArchiveEntry(relative.toFile()); + entry.setSize(Files.size(file)); + tarOut.putArchiveEntry(entry); + try { + IOUtils.copy(Files.newInputStream(file), tarOut); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + tarOut.closeArchiveEntry(); + return super.visitFile(file, attrs); + } + } + return super.visitFile(file, attrs); + } + }); + + Files.walkFileTree(actionPath, new SimpleFileVisitor<Path>() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + for (File policyId : selectedPolicy) { + // Get the current selection + String policyDir = policyId.toString(); + policyDir = policyDir.substring(policyDir.indexOf("repository")+11); + String path = policyDir.replace('\\', '.'); + if(path.contains("/")){ + path = policyDir.replace('/', '.'); + logger.info("print the path:" +path); + } + path = FilenameUtils.removeExtension(path); + if (path.endsWith(".xml")) { + path = path.substring(0, path.length() - 4); + } + File actionFile = new File(path); + String fileName = FilenameUtils.removeExtension(file.getFileName().toString()); + File actionHome = new File(fileName); + if(actionFile.equals(actionHome)) { + Path relative = actionPath.relativize(file); + TarArchiveEntry entry = new TarArchiveEntry(relative.toFile()); + entry.setSize(Files.size(file)); + tarOut.putArchiveEntry(entry); + try { + IOUtils.copy(Files.newInputStream(file), tarOut); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + tarOut.closeArchiveEntry(); + return super.visitFile(file, attrs); + } + } + return super.visitFile(file, attrs); + } + }); + + Files.walkFileTree(repoPath, new SimpleFileVisitor<Path>() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (file.getFileName().toString().endsWith(".xml") == false) { + return super.visitFile(file, attrs); + } + for (File policyId : selectedPolicy) { + // Get the current selection + if(policyId.getAbsoluteFile().getName().equals(file.getFileName().toString())) { + Path relative = repoPath.relativize(file); + TarArchiveEntry entry = new TarArchiveEntry(relative.toFile()); + entry.setSize(Files.size(file)); + tarOut.putArchiveEntry(entry); + try { + IOUtils.copy(Files.newInputStream(file), tarOut); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + tarOut.closeArchiveEntry(); + return super.visitFile(file, attrs); + } + } + return super.visitFile(file, attrs); + } + }); + + tarOut.closeArchiveEntry(); + tarOut.finish(); + logger.debug("closing the tar file"); + } + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "getting IOexception"); + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + logger.info("trying to send tar file "+tarFile.toAbsolutePath().toString()); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + String successMap = tarFile.toString().substring(tarFile.toString().lastIndexOf("webapps")+8); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{data: " + responseString + "}"); + out.write(j.toString()); + + + return null; + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e); + } + return null; + } + + //Policy Import + public JSONObject ImportRepositoryFile(String file, HttpServletRequest request){ + TarArchiveEntry entry = null; + TarArchiveInputStream extractFile = null; + try { + extractFile = new TarArchiveInputStream (new FileInputStream(file)); + } catch (FileNotFoundException e1) { + e1.printStackTrace(); + } + String userId = null; + try { + userId = UserUtils.getUserIdFromCookie(request); + } catch (Exception e) { + logger.error("Exception Occured while reading userid from cookie" +e); + } + scopeAndRoles = PolicyController.getUserRoles(userId); + //Check if the Role and Scope Size are Null get the values from db. + List<Roles> userRoles = PolicyController.getRoles(userId); + roles = new ArrayList<String>(); + scopes = new HashSet<String>(); + for(Roles userRole: userRoles){ + roles.add(userRole.getRole()); + scopes.add(userRole.getScope()); + } + //Create a loop to read every single entry in TAR file + try { + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) { + while ((entry = extractFile.getNextTarEntry()) != null) { + this.superadmin = true; + try{ + copyFileToLocation(extractFile, entry, xacmlFiles, null, superadmin); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception while Importing Polcies"+e); + } + } + }else{ + this.showMessage = true; + //get the directory names from tar file and add to the list + while ((entry = extractFile.getNextTarEntry()) != null) { + if(entry.getName().endsWith(".xls")) { + this.superadmin = true; + try{ + copyFileToLocation(extractFile, entry, xacmlFiles, finalScopes, superadmin); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception while Importing Polcies"+e); + } + } + if(entry.getName().endsWith(".xml")){ + String filename = null; + if(entry.getName().contains("\\")){ + filename = entry.getName().replace("\\", File.separator); + }else{ + filename = entry.getName().replace("/", File.separator); + } + directoryNames.add(filename.substring(0, filename.lastIndexOf(File.separator))); + } + + //get the matching scopes on comparing user scopes and tar file scopes + for(int i=0;i< userScopes.size(); i++){ + for(int j=0; j<directoryNames.size(); j++){ + if(userScopes.toArray()[i].equals(directoryNames.toArray()[j])){ + finalScopesToImport.add(userScopes.toArray()[i].toString()); + } + } + } + //get the scopes for which the user have permission to import + if(finalScopesToImport.size() != 0){ + for(int i = 0; i < finalScopesToImport.size() ; i++){ + String role = scopeAndRoles.get(finalScopesToImport.toArray()[i]).getRole(); + if(role.equalsIgnoreCase("editor") || role.equalsIgnoreCase("admin")){ + finalScopes.add(finalScopesToImport.toArray()[i].toString()); + if(role.equalsIgnoreCase("super-guest") || role.equalsIgnoreCase("guest")){ + roleIsNotSufficient.remove(finalScopesToImport.toArray()[i].toString()); + } + }else{ + roleIsNotSufficient.add(finalScopesToImport.toArray()[i].toString()); + } + } + } + //if final Scopes to import set is not 0, then copy the files + if(finalScopes.size() != 0) { + this.superadmin = false; + try{ + copyFileToLocation(extractFile, entry, xacmlFiles, finalScopes, superadmin); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception while Importing Polcies"+e); + } + } + } + } + } catch (Exception e1) { + logger.info(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception:" +e1); + e1.printStackTrace(); + } + // Close TarAchiveInputStream + try { + extractFile.close(); + } catch (IOException e) { + logger.info(XACMLErrorConstants.ERROR_PROCESS_FLOW+"IO Exception:"+e); + e.printStackTrace(); + } + + File tarFile1 = new File(file.toString()); + tarFile1.delete(); + + for (String xacmlFile: xacmlFiles) { + String policyName = xacmlFile.substring(xacmlFile.indexOf("repository")+11); + if(policyName.endsWith(".xml")){ + policyName = policyName.replace(".xml", ""); + String version = policyName.substring(policyName.lastIndexOf(".")+1); + String finalPolicyName = policyName.substring(0, policyName.lastIndexOf(".")); + PolicyVersion policyVersion = new PolicyVersion(); + policyVersion.setPolicyName(finalPolicyName); + policyVersion.setActiveVersion(Integer.parseInt(version)); + policyVersion.setHigherVersion(Integer.parseInt(version)); + policyVersion.setCreatedBy(userId); + policyVersion.setModifiedBy(userId); + policyVersionDao.Save(policyVersion); + } + + //send to pap + if(!XACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(xacmlFile)){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Failed adding imported policy to database: "+xacmlFile); + //throw new Exception("Failed adding imported policy to database: "+xacmlFile); + } + try { + File f = new File(xacmlFile); + ElkConnector.singleton.update(f); + } catch (Exception e) { + logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": Cannot ELK import: " + xacmlFile + " " + + e.getMessage(), e); + } + } + + //Filter the Set on Removing the Scopes which are imported + for(int j=0; j< finalScopesToImport.size(); j++){ + for(int i = 0; i < directoryNames.size(); i++){ + if(roles.contains("admin") || roles.contains("editor")){ + if(!((directoryNames.toArray()[i]).toString()).startsWith(finalScopesToImport.toArray()[j].toString())){ + userDontHavePermission.add(directoryNames.toArray()[i].toString()); + } + } + } + } + + //Show the Warn message to the User, if any of the policies are not Imported to teh Scopes + if(showMessage){ + if(roleIsNotSufficient.size() == 0 && userDontHavePermission.size() != 0){ + logger.warn(" User don't have Permissions to Import Policies to following Scopes:'"+userDontHavePermission+"'"); + } + else if(roleIsNotSufficient.size() != 0 && userDontHavePermission.size() == 0){ + logger.warn("Please Contact Super-Admin to Import the New Scopes:'"+roleIsNotSufficient+"'"); + } + else if(roleIsNotSufficient.size() != 0 && userDontHavePermission.size() != 0){ + logger.warn("Please Contact Super-Admin to Import the New Scopes:'"+roleIsNotSufficient+"' User don't have Permissions to Import Policies to following Scopes:'"+userDontHavePermission+"'"); + }else if(sEditorScopesCantCreate.size() != 0){ + logger.warn("Super-Editor can't create following new Scopes" +sEditorScopesCantCreate); + }else if(finalScopesToImport.size() == 0 && directoryNames.size() != 0){ + logger.warn(" User don't have Permissions to Import Policies to following Scopes:'"+directoryNames+"'"); + } + } + return null; + } + + //Copy files to Directorys + private void copyFileToLocation(TarArchiveInputStream extractFile, TarArchiveEntry entry, ArrayList<String> xacmlFiles, Set<String> finalScopes, Boolean superadminValue ) throws IOException{ + String individualFiles = ""; + int offset = 0; + FileOutputStream outputFile=null; + // Get the name of the file + if(superadminValue){ + individualFiles = entry.getName(); + //Add the list of scopes + if(entry.getName().endsWith(".xml")){ + String filename = null; + if(entry.getName().contains("\\")){ + filename = entry.getName().replace("\\", File.separator); + }else{ + filename = entry.getName().replace("/", File.separator); + } + if(roles.contains("super-editor")){ + listOfTarNewScopes.add(filename.substring(0, filename.lastIndexOf(File.separator))); + } + } + }else{ + for(int i =0; i< finalScopes.size(); i++){ + if(entry.getName().startsWith(finalScopes.toArray()[i].toString())){ + individualFiles = entry.getName(); + } + } + } + + //Filter the new Scopes which Super-Editor can't create + if(roles.contains("super-editor")){ + for(int j= 0; j< listOfTarNewScopes.size(); j++){ + boolean scopeExistsFlag = false; // This Flag is used to know if the Scope Exists. + for(int i=0; i < scopes.size(); i++ ){ + if(scopes.contains(listOfTarNewScopes.toArray()[j])){ + scopeExistsFlag = true; + } + } + if(!scopeExistsFlag){ + sEditorScopesCantCreate.add(listOfTarNewScopes.toArray()[j].toString()); + showMessage = true; + } + } + } + + individualFiles = individualFiles.replace("/", File.separator); + individualFiles = individualFiles.replace("\\", File.separator); + + //Create the path with the entry name + String filePath = directory + File.separator + individualFiles; + String configPath = CONFIG_HOME + File.separator + individualFiles; + String actionPath = ACTION_HOME + File.separator + individualFiles; + logger.info("File Name in TAR File is: " + individualFiles); + logger.info("Xml directory file path: " + filePath); + logger.info("Config Home directory file path: " + configPath); + logger.info("Action Home directory file path: " + actionPath); + + + // Get Size of the file and create a byte array for the size + byte[] content = new byte[(int) entry.getSize()]; + + offset=0; + logger.info("File Name in TAR File is: " + individualFiles); + logger.info("Size of the File is: " + entry.getSize()); + // Read file from the archive into byte array + extractFile.read(content, offset, content.length - offset); + if (!entry.isDirectory()) { + if(!individualFiles.contains(".Config_") || !individualFiles.contains(".Action_")){ + // if the entry is a file, extracts it + String filePath1 = filePath.substring(0, filePath.lastIndexOf(File.separator)); + File newFile = new File(filePath1); + if(!(newFile.exists()) && !(roles.contains("super-editor") || roles.contains("editor"))) { + File dir = new File(filePath1); + dir.mkdir(); + extractFile(extractFile, filePath); + } + } + } else { + // if the entry is a directory, make the directory + if(!(roles.contains("super-editor") || roles.contains("editor"))){ + File dir = new File(filePath); + dir.mkdir(); + } + } + // Define OutputStream for writing the file + if(individualFiles.contains(".Config_")){ + outputFile=new FileOutputStream(new File(configPath)); + }else if(individualFiles.contains(".Action_")){ + outputFile=new FileOutputStream(new File(actionPath)); + }else{ + if(filePath != null){ + outputFile=new FileOutputStream(new File(filePath)); + xacmlFiles.add(filePath); + } + } + + // Use IOUtiles to write content of byte array to physical file + IOUtils.write(content,outputFile); + + // Close Output Stream + try { + outputFile.close(); + } catch (IOException e) { + logger.info("IOException:" +e); + e.printStackTrace(); + } + } + + private void extractFile(TarArchiveInputStream extractFile, String filePath) throws IOException { + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = extractFile.read(bytesIn)) != -1) { + bos.write(bytesIn, 0, read); + } + bos.close(); + + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java new file mode 100644 index 000000000..203f3dcc6 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +/* + * + * */ +import java.io.File; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.rest.jpa.WatchPolicyNotificationTable; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.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.node.ArrayNode; + +@Controller +@RequestMapping({"/"}) +public class PolicyNotificationController extends RestrictedBaseController { + + @Autowired + WatchPolicyNotificationDao policyNotificationDao; + + @RequestMapping(value={"/watchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String path = ""; + String responseValue = ""; + try { + String userId = UserUtils.getUserIdFromCookie(request); + System.out.println(userId); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String name = root.get("watchData").get("name").toString(); + JsonNode pathList = root.get("watchData").get("path"); + String finalName = ""; + if(pathList.isArray()){ + ArrayNode arrayNode = (ArrayNode) pathList; + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode individualElement = arrayNode.get(i); + if(i == 0){ + path = path + individualElement.toString().replace("\"", "").trim(); + }else{ + path = path + File.separator + individualElement.toString().replace("\"", "").trim(); + } + } + } + + if(pathList.size() > 0){ + finalName = path + File.separator + name.replace("\"", "").trim(); + }else{ + finalName = name.replace("\"", "").trim(); + } + if(finalName.contains("\\")){ + finalName = finalName.replace("\\", "\\\\"); + } + String query = "from WatchPolicyNotificationTable where POLICYNAME = '"+finalName+"' and LOGINIDS = '"+userId+"'"; + List<WatchPolicyNotificationTable> watchList = policyNotificationDao.watchListQuery(query); + if(watchList.isEmpty()){ + if(finalName.contains("\\\\")){ + finalName = finalName.replace("\\\\", File.separator); + } + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + watch.setPolicyName(finalName); + watch.setLoginIds(userId); + policyNotificationDao.save(watch); + responseValue = "You have Subscribed Successfully"; + }else{ + policyNotificationDao.delete(watchList.get(0)); + responseValue = "You have UnSubscribed Successfully"; + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(responseValue); + JSONObject j = new JSONObject("{watchData: " + 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-app/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java new file mode 100644 index 000000000..dea341ea9 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.PrintWriter; +import java.nio.file.Path; +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.policy.dao.PolicyRolesDao; +import org.openecomp.policy.rest.jpa.PolicyRoles; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class PolicyRolesController extends RestrictedBaseController{ + + @Autowired + PolicyRolesDao policyRolesDao; + List<String> scopelist; + + @RequestMapping(value={"/get_RolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("rolesDatas", mapper.writeValueAsString(policyRolesDao.getUserRoles())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/save_NonSuperRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyRoles adapter = mapper.readValue(root.get("editRoleData").toString(), PolicyRoles.class); + policyRolesDao.update(adapter); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(policyRolesDao.getUserRoles()); + JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}"); + + out.write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + @RequestMapping(value={"/get_PolicyRolesScopeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + scopelist = new ArrayList<String>(); + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + Path gitPath = PolicyController.getGitPath().toAbsolutePath(); + model.put("scopeDatas", mapper.writeValueAsString(readFileRepository(gitPath))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + public List<String> readFileRepository(Path path){ + File root = new File(path.toString()); + for ( File file : root.listFiles()){ + if(file.isDirectory()){ + String fileName = getDomain(file); + if (!(fileName.contains(".git") || fileName.equals(".DS_Store"))) { + scopelist.add(fileName); + } + readFileRepository(file.toPath()); + } + } + return scopelist; + } + + public String getDomain(File file) { + String filePath = file.getAbsolutePath(); + int startIndex = filePath.indexOf("repository") + 11; + return filePath.substring(startIndex, filePath.length()); + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java new file mode 100644 index 000000000..5ffdd062a --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java @@ -0,0 +1,300 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.ClosedLoopFaultBody; +import org.openecomp.policy.adapter.ClosedLoopPMBody; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.rest.dao.SafePolicyWarningDao; +import org.openecomp.policy.rest.jpa.SafePolicyWarning; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.CharMatcher; + +@Controller +@RequestMapping("/") +public class PolicyValidationController extends RestrictedBaseController { + + public static final String CONFIG_POLICY = "Config"; + public static final String ACTION_POLICY = "Action"; + public static final String DECISION_POLICY = "Decision"; + public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault"; + public static final String CLOSEDLOOP_PM = "ClosedLoop_PM"; + public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config"; + public static final String MICROSERVICES="DCAE Micro Service"; + private Pattern pattern; + private Matcher matcher; + + private static final String EMAIL_PATTERN = + "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; + + @Autowired + SafePolicyWarningDao safePolicyWarningDao; + + @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try{ + boolean valid = true; + String responseString = ""; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").toString(), PolicyAdapter.class); + if(policyData.getPolicyName() != null){ + String policyNameValidate = emptyValidator(policyData.getPolicyName()); + if(!policyNameValidate.contains("success")){ + responseString = responseString + "PolicyName:" + policyNameValidate; + valid = false; + }; + }else{ + responseString = responseString + "PolicyName: PolicyName Should not be empty" + "<br>"; + } + if(policyData.getPolicyDescription() != null){ + String descriptionValidate = descriptionValidator(policyData.getPolicyDescription()); + if(!descriptionValidate.contains("success")){ + responseString = responseString + "Description:" + descriptionValidate; + valid = false; + } + } + + if(policyData.getPolicyType().equals(CONFIG_POLICY)){ + if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY) + || policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) { + if(policyData.getEcompName() != null){ + String ecompNameValidate = emptyValidator(policyData.getEcompName()); + if(!ecompNameValidate.contains("success")){ + responseString = responseString + "EcompName:" + ecompNameValidate; + valid = false; + } + }else{ + responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "<br>"; + } + } + + if(policyData.getRiskType() != null){ + String riskTypeValidate = emptyValidator(policyData.getRiskType()); + if(!riskTypeValidate.contains("success")){ + responseString = responseString + "RiskType:" + riskTypeValidate; + valid = false; + }else { + SafePolicyWarning safePolicyWarningData = safePolicyWarningDao.getSafePolicyWarningDataById(policyData.getRiskType()); + if (safePolicyWarningData!=null){ + safePolicyWarningData.getMessage(); + responseString = responseString + "Messaage:" + safePolicyWarningData.getMessage(); + } + } + }else { + responseString = responseString + "Risk Type: Risk Type Should not be Empty" + "<br>"; + valid = false; + } + + if(policyData.getRiskLevel() != null){ + String validateRiskLevel = emptyValidator(policyData.getRiskLevel()); + if(!validateRiskLevel.contains("success")){ + responseString = responseString + "RiskLevel:" + validateRiskLevel; + valid = false; + } + }else { + responseString = responseString + "Risk Level: Risk Level Should not be Empty" + "<br>"; + valid = false; + } + + if(policyData.getGuard() != null){ + String validateGuard = emptyValidator(policyData.getGuard()); + if(!validateGuard.contains("success")){ + responseString = responseString + "Guard:" + validateGuard; + valid = false; + } + }else { + responseString = responseString + "Guard: Guard Value Should not be Empty" + "<br>"; + valid = false; + } + + if(policyData.getConfigPolicyType().equals("Base")){ + if(policyData.getConfigName() != null){ + String configNameValidate = emptyValidator(policyData.getConfigName()); + if(!configNameValidate.contains("success")){ + responseString = responseString + "ConfigName:" + configNameValidate; + valid = false; + } + }else{ + responseString = responseString + "Config Name: Config Name Should not be Empty" + "<br>"; + } + if(policyData.getConfigType() != null){ + String configTypeValidate = emptyValidator(policyData.getConfigType()); + if(!configTypeValidate.contains("success")){ + responseString = responseString + "ConfigType:" + configTypeValidate; + valid = false; + } + }else{ + responseString = responseString + "Config Type: Config Type Should not be Empty" + "<br>"; + } + if(policyData.getConfigBodyData() != null){ + String policyType = policyData.getPolicyType(); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + if(!engine.validatePolicyRequest(policyData, policyType)){ + responseString = responseString + "ConfigBody: Validation Failed"; + valid = false; + } + }else{ + responseString = responseString + "Config Body: Config Body Should not be Empty" + "<br>"; + } + } + + + if(policyData.getJsonBodyData() != null){ + if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){ + ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class); + if(pmBody.getEmailAddress() != null){ + String validateEmail = validateEmailAddress(pmBody.getEmailAddress().toString()); + if(!validateEmail.contains("success")){ + responseString = responseString + "Email:" + validateEmail; + valid = false; + } + }else{ + valid = true; + } + }else if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){ + ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); + if(faultBody.getEmailAddress() != null){ + String validateEmail = validateEmailAddress(faultBody.getEmailAddress().toString()); + if(!validateEmail.contains("success")){ + responseString = responseString + "Email:" + validateEmail; + valid = false; + } + }else{ + valid = true; + } + } + } + } + if (policyData.getPolicyType().equals(DECISION_POLICY)){ + String ecompNameValidate = emptyValidator(policyData.getEcompName()); + if(!ecompNameValidate.contains("success")){ + responseString = responseString + "EcompName:" + ecompNameValidate; + valid = false; + } + } + + if(policyData.getPolicyType().equals(ACTION_POLICY)){ + String actionPerformer = emptyValidator(policyData.getActionPerformer()); + String actionAttribute = emptyValidator(policyData.getActionAttributeValue()); + if(!actionPerformer.contains("success")){ + responseString = responseString + "ActionPerformer:" + actionPerformer; + valid = false; + }; + if(!actionAttribute.contains("success")){ + responseString = responseString + "ActionAttribute:" + actionAttribute; + valid = false; + }; + } + + if(policyData.getPolicyType().equals(CONFIG_POLICY)){ + if(valid){ + responseString = "success" + "@#"+ responseString; + } + }else{ + if(valid){ + responseString = "success"; + } + } + + PrintWriter out = response.getWriter(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString)); + JSONObject j = new JSONObject(msg); + 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; + } + + protected String emptyValidator(String field){ + String error = "success"; + if (field.equals("") || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) { + error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; + return error; + } else { + if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){ + error = "success"; + }else{ + error = "The Value Contains Non ASCII Characters"; + return error; + } + } + return error; + } + + protected String descriptionValidator(String field) { + String error = "success"; + if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) { + error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:"; + return error; + } else { + error = "success"; + } + return error; + } + + public String validateEmailAddress(String emailAddressValue) { + String error = "success"; + List<String> emailList = Arrays.asList(emailAddressValue.toString().split(",")); + for(int i =0 ; i < emailList.size() ; i++){ + pattern = Pattern.compile(EMAIL_PATTERN); + matcher = pattern.matcher(emailList.get(i).trim()); + if(!matcher.matches()){ + error = "Please check the Following Email Address is not Valid .... " +emailList.get(i).toString(); + return error; + }else{ + error = "success"; + } + } + return error; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/FunctionDefinitionDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/FunctionDefinitionDao.java new file mode 100644 index 000000000..c216ca589 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/FunctionDefinitionDao.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.FunctionDefinition; + +public interface FunctionDefinitionDao { + + List<FunctionDefinition> getFunctionDefinition(); + List<String> getFunctionDefinitionByName(); +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/GlobalRoleSettingsDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/GlobalRoleSettingsDao.java new file mode 100644 index 000000000..35aab5211 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/GlobalRoleSettingsDao.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.GlobalRoleSettings; + +public interface GlobalRoleSettingsDao { + + void update(GlobalRoleSettings globalRoleSettings); + List<GlobalRoleSettings> getGlobalRoleSettings(); + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/GroupEntityDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/GroupEntityDao.java new file mode 100644 index 000000000..8983382f7 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/GroupEntityDao.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.GroupEntity; + + +public abstract interface GroupEntityDao { + + public abstract List<GroupEntity> getGroupEntityData(); + + public abstract GroupEntity getPDPGroupEntity(String string); + + public abstract void savePDPGroupEntity(GroupEntity pdpGroupDataFunction); + + public abstract void deletePDPGroupEntity(GroupEntity pdpGroupDataFunction); + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PDPEntityDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PDPEntityDao.java new file mode 100644 index 000000000..60f7441b3 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PDPEntityDao.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.PdpEntity; + + +public abstract interface PDPEntityDao { + + public abstract List<PdpEntity> getPDPEntityData(); + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PolicyEditorScopesDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PolicyEditorScopesDao.java new file mode 100644 index 000000000..f40de6d50 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PolicyEditorScopesDao.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.PolicyEditorScopes; + + +public interface PolicyEditorScopesDao { + List<PolicyEditorScopes> getPolicyEditorScopesData(); + List<String> getPolicyEditorScopesDataByName(); + void Save(PolicyEditorScopes policyEditorScopes); + void delete(PolicyEditorScopes policyEditorScopes); + void update(PolicyEditorScopes policyEditorScopes); + List<PolicyEditorScopes> getListOfPolicyScopes(String query); + void updateQuery(String policyScopeQuery); +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PolicyRolesDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PolicyRolesDao.java new file mode 100644 index 000000000..49cd17c10 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PolicyRolesDao.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.PolicyRoles; + +public interface PolicyRolesDao { + + List<PolicyRoles> getRoles(); + List<PolicyRoles> getUserRoles(); + void save(PolicyRoles role); + + void update(PolicyRoles role); + + void delete(PolicyRoles role); +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PolicyVersionDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PolicyVersionDao.java new file mode 100644 index 000000000..0c2692e6c --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/PolicyVersionDao.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.PolicyVersion; + + +public interface PolicyVersionDao { + List<PolicyVersion> getPolicyVersionData(); + List<PolicyVersion> getPolicyVersionEntityByName(String policyVersion); + List<String> getPolicyVersionDataByName(); + List<PolicyVersion> getActiveVersionPolicy(String query); + void Save(PolicyVersion policyVersion); + void delete(PolicyVersion policyVersion); + void update(PolicyVersion policyVersion); + void updateQuery(String policyVersion); +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/RemoteCatalogValuesDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/RemoteCatalogValuesDao.java new file mode 100644 index 000000000..c2ff0f7b8 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/RemoteCatalogValuesDao.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.RemoteCatalogValues; + +public interface RemoteCatalogValuesDao { + List<RemoteCatalogValues> getRemoteCatalogValuesData(); + List<String> getRemoteCatalogValuesDataByName(); + void Save(RemoteCatalogValues attribute); + void delete(RemoteCatalogValues attribute); + void update(RemoteCatalogValues attribute); +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/RolesDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/RolesDao.java new file mode 100644 index 000000000..4612daea0 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/RolesDao.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.model.Roles; + + + +public interface RolesDao { + + List<Roles> getUserRoles(String userId); + + void save(Roles role); + + void delete(Roles role); + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/RuleAlgorithmsDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/RuleAlgorithmsDao.java new file mode 100644 index 000000000..6a9c6b303 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/RuleAlgorithmsDao.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.RuleAlgorithms; + +public interface RuleAlgorithmsDao { + + List<RuleAlgorithms> getRuleAlgorithms(); +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java new file mode 100644 index 000000000..bdfdd8f0a --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.SystemLogDB; + + + +public abstract interface SystemLogDbDao { + public abstract List<SystemLogDB> getLoggingData(); + public abstract List<SystemLogDB> getSystemAlertData(); +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/WatchPolicyNotificationDao.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/WatchPolicyNotificationDao.java new file mode 100644 index 000000000..a43294e94 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/dao/WatchPolicyNotificationDao.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.WatchPolicyNotificationTable; + +public interface WatchPolicyNotificationDao { + List<WatchPolicyNotificationTable> getListData(); + List<WatchPolicyNotificationTable> getListDataByPolicyName(String policyName); + void save(WatchPolicyNotificationTable data); + void update(WatchPolicyNotificationTable data); + void delete(WatchPolicyNotificationTable data); + List<WatchPolicyNotificationTable> watchListQuery(String query); +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/ActionPolicyDictDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/ActionPolicyDictDaoImpl.java new file mode 100644 index 000000000..b29aafec2 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/ActionPolicyDictDaoImpl.java @@ -0,0 +1,178 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.rest.dao.ActionPolicyDictDao; +import org.openecomp.policy.rest.jpa.ActionPolicyDict; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("ActionPolicyDictDao") +public class ActionPolicyDictDaoImpl implements ActionPolicyDictDao { + private static final Logger logger = FlexLogger.getLogger(ActionPolicyDictDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<ActionPolicyDict> getActionDictData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + + List<ActionPolicyDict> actionDictData = null; + try { + Criteria cr = session.createCriteria(ActionPolicyDict.class); + actionDictData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying ActionDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return actionDictData; + } + + @Override + public void Save(ActionPolicyDict action) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(action); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving ActionDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void delete(ActionPolicyDict action) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(action); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting ActionDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(ActionPolicyDict action) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(action); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ActionDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getActionDictDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(ActionPolicyDict.class); + List<ActionPolicyDict> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getAttributeName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying ActionDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @SuppressWarnings("unchecked") + @Override + public ActionPolicyDict getActionEntityDatabyId(String action) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + ActionPolicyDict data = null; + try { + Criteria cr = session.createCriteria(ActionPolicyDict.class); + List<ActionPolicyDict> attributeData = cr.add(Restrictions.eq("attributeName", action)).list(); + for(Object entity : attributeData){ + data = (ActionPolicyDict) entity; + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying ActionDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/AddressGroupDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/AddressGroupDaoImpl.java new file mode 100644 index 000000000..132220f5f --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/AddressGroupDaoImpl.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.rest.dao.AddressGroupDao; +import org.openecomp.policy.rest.jpa.AddressGroup; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("AddressGroupDao") +public class AddressGroupDaoImpl implements AddressGroupDao{ + private static final Logger logger = FlexLogger.getLogger(AddressGroupDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<AddressGroup> getAddressGroupData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<AddressGroup> attributeData = null; + try { + Criteria cr = session.createCriteria(AddressGroup.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying AddressGroup Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + + } + + @Override + public void Save(AddressGroup attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving AddressGroup Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(AddressGroup attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting AddressGroup Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(AddressGroup attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating AddressGroup Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getAddressGroupDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(AddressGroup.class); + List<AddressGroup> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getGroupName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying AddressGroup Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/BRMSParamTemplateDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/BRMSParamTemplateDaoImpl.java new file mode 100644 index 000000000..0b634ff73 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/BRMSParamTemplateDaoImpl.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.rest.dao.BRMSParamTemplateDao; +import org.openecomp.policy.rest.jpa.BRMSParamTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("BRMSParamTemplateDao") +public class BRMSParamTemplateDaoImpl implements BRMSParamTemplateDao{ + private static final Logger logger = FlexLogger.getLogger(BRMSParamTemplateDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<BRMSParamTemplate> getBRMSParamTemplateData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<BRMSParamTemplate> attributeData =null; + try { + Criteria cr = session.createCriteria(BRMSParamTemplate.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying BRMSParamTemplate Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + + } + + @Override + public void Save(BRMSParamTemplate attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving BRMSParamTemplate Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(BRMSParamTemplate attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting BRMSParamTemplate Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(BRMSParamTemplate attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating BRMSParamTemplate Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getBRMSParamDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(BRMSParamTemplate.class); + List<BRMSParamTemplate> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getRuleName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying BRMSParamTemplate Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/DescriptiveScopeDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/DescriptiveScopeDaoImpl.java new file mode 100644 index 000000000..600b42ce7 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/DescriptiveScopeDaoImpl.java @@ -0,0 +1,177 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.rest.dao.DescriptiveScopeDao; +import org.openecomp.policy.rest.jpa.DescriptiveScope; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("DescriptiveScopeDao") +public class DescriptiveScopeDaoImpl implements DescriptiveScopeDao{ + private static final Logger logger = FlexLogger.getLogger(DescriptiveScopeDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<DescriptiveScope> getDescriptiveScope() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<DescriptiveScope> descriptiveScopeData = null; + try { + Criteria cr = session.createCriteria(DescriptiveScope.class); + descriptiveScopeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying DescriptiveScope Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return descriptiveScopeData; + } + + @Override + public void Save(DescriptiveScope descriptiveScope) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(descriptiveScope); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving DescriptiveScope Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(DescriptiveScope descriptiveScope) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(descriptiveScope); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting DescriptiveScope Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void update(DescriptiveScope descriptiveScope) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(descriptiveScope); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating DescriptiveScope Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getDescriptiveScopeDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(DescriptiveScope.class); + List<DescriptiveScope> descriptiveScopeData = cr.list(); + for(int i = 0; i < descriptiveScopeData.size(); i++){ + data.add(descriptiveScopeData.get(i).getScopeName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying DescriptiveScope Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public DescriptiveScope getDescriptiveScopeById(String name) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + DescriptiveScope data = null; + try { + Criteria cr = session.createCriteria(PolicyVersion.class); + cr.add(Restrictions.eq("scopename",name)); + data = (DescriptiveScope) cr.list().get(0); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying DescriptiveScope Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/FirewallDictionaryListDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/FirewallDictionaryListDaoImpl.java new file mode 100644 index 000000000..e002aa962 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/FirewallDictionaryListDaoImpl.java @@ -0,0 +1,196 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.rest.dao.FirewallDictionaryListDao; +import org.openecomp.policy.rest.jpa.FirewallDictionaryList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("FirewallDictionaryListDao") +public class FirewallDictionaryListDaoImpl implements FirewallDictionaryListDao { + private static final Logger logger = FlexLogger.getLogger(FirewallDictionaryListDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<FirewallDictionaryList> getFWDictionaryListData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<FirewallDictionaryList> attributeData = null; + try { + Criteria cr = session.createCriteria(FirewallDictionaryList.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying FirewallDictionaryList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getFWDictionaryListDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(FirewallDictionaryList.class); + List<FirewallDictionaryList> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getParentItemName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying FirewallDictionaryList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public void Save(FirewallDictionaryList firewallDictionaryList) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(firewallDictionaryList); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving FirewallDictionaryList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(FirewallDictionaryList firewallDictionaryList) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(firewallDictionaryList); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting FirewallDictionaryList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void update(FirewallDictionaryList firewallDictionaryList) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(firewallDictionaryList); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating FirewallDictionaryList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void updateQuery(String query) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + Query hbquery = session.createQuery(query); + hbquery.executeUpdate(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating FirewallDictionaryList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public FirewallDictionaryList getFWDictionaryDataById(String value) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + FirewallDictionaryList data = null; + try { + Criteria cr = session.createCriteria(FirewallDictionaryList.class); + cr = cr.add(Restrictions.eq("parentItemName",value)); + data = (FirewallDictionaryList) cr.list().get(0); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying FirewallDictionaryList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/FunctionDefinitionDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/FunctionDefinitionDaoImpl.java new file mode 100644 index 000000000..ebb833585 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/FunctionDefinitionDaoImpl.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.dao.FunctionDefinitionDao; +import org.openecomp.policy.rest.jpa.FunctionDefinition; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("FunctionDefinitionDao") +public class FunctionDefinitionDaoImpl implements FunctionDefinitionDao{ + private static final Logger logger = FlexLogger.getLogger(FunctionDefinitionDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<String> getFunctionDefinitionByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(FunctionDefinition.class); + List<FunctionDefinition> functionDefinitionData = cr.list(); + for(int i = 0; i < functionDefinitionData.size(); i++){ + data.add(functionDefinitionData.get(i).getShortname()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying FunctionDefinition Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @SuppressWarnings("unchecked") + @Override + public List<FunctionDefinition> getFunctionDefinition() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<FunctionDefinition> functionDefinitionData = null; + try { + Criteria cr = session.createCriteria(FunctionDefinition.class); + functionDefinitionData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying FunctionDefinition Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return functionDefinitionData; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/GlobalRoleSettingsDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/GlobalRoleSettingsDaoImpl.java new file mode 100644 index 000000000..718b8e98f --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/GlobalRoleSettingsDaoImpl.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.dao.GlobalRoleSettingsDao; +import org.openecomp.policy.rest.jpa.GlobalRoleSettings; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@Service("GlobalRoleSettingsDao") +public class GlobalRoleSettingsDaoImpl implements GlobalRoleSettingsDao{ + private static final Logger logger = FlexLogger.getLogger(GlobalRoleSettingsDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + + + @SuppressWarnings("unchecked") + @Override + public List<GlobalRoleSettings> getGlobalRoleSettings() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<GlobalRoleSettings> lockdownData = null; + try { + Criteria cr = session.createCriteria(GlobalRoleSettings.class); + lockdownData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying GlobalRoleSettings Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return lockdownData; + } + + + + @Override + public void update(GlobalRoleSettings globalRoleSettings) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(globalRoleSettings); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating GlobalRoleSettings Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/GroupEntityDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/GroupEntityDaoImpl.java new file mode 100644 index 000000000..1a468253c --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/GroupEntityDaoImpl.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.dao.GroupEntityDao; +import org.openecomp.policy.rest.jpa.GroupEntity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("PDPGroupDataDao") +public class GroupEntityDaoImpl implements GroupEntityDao{ + private static final Logger logger = FlexLogger.getLogger(GroupEntityDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<GroupEntity> getGroupEntityData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + Criteria cr = session.createCriteria(GroupEntity.class); + List<GroupEntity> groupData = null; + try { + groupData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying GroupEntity Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return groupData; + } + + @Override + public GroupEntity getPDPGroupEntity(String getgroupName) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + GroupEntity entity = null; + try { + entity = (GroupEntity) session.get(GroupEntity.class, getgroupName); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying GroupEntity Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return entity; + } + + @Override + public void savePDPGroupEntity(GroupEntity pdpGroupDataFunction) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(pdpGroupDataFunction); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving GroupEntity Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void deletePDPGroupEntity(GroupEntity pdpGroupDataFunction) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(pdpGroupDataFunction); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting GroupEntity Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/GroupPolicyScopeListDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/GroupPolicyScopeListDaoImpl.java new file mode 100644 index 000000000..a51eef102 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/GroupPolicyScopeListDaoImpl.java @@ -0,0 +1,177 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.rest.dao.GroupPolicyScopeListDao; +import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("GroupPolicyScopeListDao") +public class GroupPolicyScopeListDaoImpl implements GroupPolicyScopeListDao { + private static final Logger logger = FlexLogger.getLogger(GroupPolicyScopeListDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<GroupPolicyScopeList> getGroupPolicyScopeListData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<GroupPolicyScopeList> attributeData = null; + try { + Criteria cr = session.createCriteria(GroupPolicyScopeList.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying GroupPolicyScopeList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getGroupPolicyScopeListDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(GroupPolicyScopeList.class); + List<GroupPolicyScopeList> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getGroupName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying GroupPolicyScopeList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public void Save(GroupPolicyScopeList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving GroupPolicyScopeList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(GroupPolicyScopeList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting Attribute Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void update(GroupPolicyScopeList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Attribute Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<GroupPolicyScopeList> CheckDuplicateEntry(String value) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<GroupPolicyScopeList> data = null; + try { + Criteria cr = session.createCriteria(GroupPolicyScopeList.class); + cr.add(Restrictions.eq("name",value)); + data = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying GroupPolicyScopeList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/MicroServiceModelsDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/MicroServiceModelsDaoImpl.java new file mode 100644 index 000000000..6c198aa11 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/MicroServiceModelsDaoImpl.java @@ -0,0 +1,156 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.rest.dao.MicroServiceModelsDao; +import org.openecomp.policy.rest.jpa.MicroServiceModels; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("MicroServiceModelsDao") +public class MicroServiceModelsDaoImpl implements MicroServiceModelsDao{ + private static final Logger logger = FlexLogger.getLogger(MicroServiceModelsDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<MicroServiceModels> getMicroServiceModelsData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<MicroServiceModels> attributeData = null; + try { + Criteria cr = session.createCriteria(MicroServiceModels.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying MicroServiceModels Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + + } + + @Override + public void Save(MicroServiceModels attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving MicroServiceModels Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(MicroServiceModels attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting MicroServiceModels Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(MicroServiceModels attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating MicroServiceModels Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getMSModelsDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(MicroServiceModels.class); + List<MicroServiceModels> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + if(attributeData.get(i).getVersion() == null || attributeData.get(i).getVersion().equals("")){ + data.add(attributeData.get(i).getModelName()); + }else{ + data.add(attributeData.get(i).getModelName() + "-v" + attributeData.get(i).getVersion()); + } + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying MicroServiceModels Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PDPEntityDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PDPEntityDaoImpl.java new file mode 100644 index 000000000..2a2250e87 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PDPEntityDaoImpl.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.dao.PDPEntityDao; +import org.openecomp.policy.rest.jpa.PdpEntity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("PDPEntityDataDao") +public class PDPEntityDaoImpl implements PDPEntityDao { + private static final Logger logger = FlexLogger.getLogger(PDPEntityDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<PdpEntity> getPDPEntityData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PdpEntity> pdpData = null; + try { + Criteria cr = session.createCriteria(PdpEntity.class); + pdpData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PdpEntity Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return pdpData; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PolicyEditorScopesDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PolicyEditorScopesDaoImpl.java new file mode 100644 index 000000000..4aad7efbd --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PolicyEditorScopesDaoImpl.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.dao.PolicyEditorScopesDao; +import org.openecomp.policy.rest.jpa.PolicyEditorScopes; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +@Service("PolicyEditorScopesDao") +public class PolicyEditorScopesDaoImpl implements PolicyEditorScopesDao { + private static final Log logger = LogFactory.getLog(PolicyEditorScopesDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<PolicyEditorScopes> getPolicyEditorScopesData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PolicyEditorScopes> scopeNameData = null; + try { + Criteria cr = session.createCriteria(PolicyEditorScopes.class); + scopeNameData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyEditorScopes Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return scopeNameData; + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getPolicyEditorScopesDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(PolicyEditorScopes.class); + List<PolicyEditorScopes> scopeNameData = cr.list(); + for(int i = 0; i < scopeNameData.size(); i++){ + data.add(scopeNameData.get(i).getScopeName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyEditorScopes Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public void Save(PolicyEditorScopes policyEditorScopes) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(policyEditorScopes); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving PolicyEditorScopes Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(PolicyEditorScopes policyEditorScopes) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(policyEditorScopes); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting PolicyEditorScopes Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void update(PolicyEditorScopes policyEditorScopes) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(policyEditorScopes); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating PolicyEditorScopes Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<PolicyEditorScopes> getListOfPolicyScopes(String query) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PolicyEditorScopes> data = null; + try { + Query hbquery = session.createQuery(query); + data = hbquery.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyEditorScopes Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public void updateQuery(String policyScopeQuery) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + Query hbquery = session.createQuery(policyScopeQuery); + hbquery.executeUpdate(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating PolicyEditorScopes Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PolicyRolesDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PolicyRolesDaoImpl.java new file mode 100644 index 000000000..f10a94229 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PolicyRolesDaoImpl.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Conjunction; +import org.hibernate.criterion.Disjunction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.dao.PolicyRolesDao; +import org.openecomp.policy.rest.jpa.PolicyRoles; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("PolicyRolesDao") +public class PolicyRolesDaoImpl implements PolicyRolesDao{ + private static final Logger logger = FlexLogger.getLogger(PolicyRolesDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<PolicyRoles> getUserRoles() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PolicyRoles> rolesData = null; + try { + Criteria cr = session.createCriteria(PolicyRoles.class); + Disjunction disjunction = Restrictions.disjunction(); + Conjunction conjunction1 = Restrictions.conjunction(); + conjunction1.add(Restrictions.eq("role", "admin")); + Conjunction conjunction2 = Restrictions.conjunction(); + conjunction2.add(Restrictions.eq("role", "editor")); + Conjunction conjunction3 = Restrictions.conjunction(); + conjunction3.add(Restrictions.eq("role", "guest")); + disjunction.add(conjunction1); + disjunction.add(conjunction2); + disjunction.add(conjunction3); + rolesData = cr.add(disjunction).list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return rolesData; + } + + @Override + public void save(PolicyRoles role) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(role); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving PolicyRoles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(PolicyRoles role) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(role); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting PolicyRoles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void update(PolicyRoles role) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(role); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating PolicyRoles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<PolicyRoles> getRoles() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PolicyRoles> rolesData = null; + try { + Criteria cr = session.createCriteria(PolicyRoles.class); + rolesData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return rolesData; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PolicyVersionDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PolicyVersionDaoImpl.java new file mode 100644 index 000000000..02188ec47 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PolicyVersionDaoImpl.java @@ -0,0 +1,216 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("PolicyVersionDao") +public class PolicyVersionDaoImpl implements PolicyVersionDao { + private static final Logger logger = FlexLogger.getLogger(PolicyVersionDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<PolicyVersion> getPolicyVersionData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PolicyVersion> versionData = null; + try { + Criteria cr = session.createCriteria(PolicyVersion.class); + versionData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyVersion Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return versionData; + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getPolicyVersionDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(PolicyVersion.class); + List<PolicyVersion> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getPolicyName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyVersion Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public void Save(PolicyVersion policyVersion) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(policyVersion); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving PolicyVersion Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void delete(PolicyVersion policyVersion) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(policyVersion); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting PolicyVersion Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(PolicyVersion policyVersion) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(policyVersion); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating PolicyVersion Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @SuppressWarnings("unchecked") + @Override + public List<PolicyVersion> getPolicyVersionEntityByName(String policyVersion) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PolicyVersion> data = null; + try { + Criteria cr = session.createCriteria(PolicyVersion.class); + cr.add(Restrictions.eq("policyName",policyVersion)); + data = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyVersion Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @SuppressWarnings("unchecked") + @Override + public List<PolicyVersion> getActiveVersionPolicy(String query) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PolicyVersion> data = null; + try { + Query hbquery = session.createQuery(query); + data = hbquery.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyVersion Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public void updateQuery(String policyVersion) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + Query hbquery = session.createQuery(policyVersion); + hbquery.executeUpdate(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating PolicyVersion Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PrefixListDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PrefixListDaoImpl.java new file mode 100644 index 000000000..cc8701361 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/PrefixListDaoImpl.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.rest.dao.PrefixListDao; +import org.openecomp.policy.rest.jpa.PREFIXLIST; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("PrefixListDao") +public class PrefixListDaoImpl implements PrefixListDao{ + private static final Logger logger = FlexLogger.getLogger(PrefixListDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<PREFIXLIST> getPREFIXLISTData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PREFIXLIST> attributeData = null; + try { + Criteria cr = session.createCriteria(PREFIXLIST.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PREFIXLIST Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + + } + + @Override + public void Save(PREFIXLIST attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving PREFIXLIST Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(PREFIXLIST attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting PREFIXLIST Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(PREFIXLIST attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating PREFIXLIST Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getPrefixListDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(PREFIXLIST.class); + List<PREFIXLIST> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getPrefixListName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PREFIXLIST Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/RemoteCatalogValuesDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/RemoteCatalogValuesDaoImpl.java new file mode 100644 index 000000000..5f42ba73e --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/RemoteCatalogValuesDaoImpl.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.dao.RemoteCatalogValuesDao; +import org.openecomp.policy.rest.jpa.RemoteCatalogValues; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("RemoteCatalogValuesDao") +public class RemoteCatalogValuesDaoImpl implements RemoteCatalogValuesDao { + private static final Logger logger = FlexLogger.getLogger(RemoteCatalogValuesDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + + @SuppressWarnings("unchecked") + @Override + public List<RemoteCatalogValues> getRemoteCatalogValuesData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<RemoteCatalogValues> attributeData = null; + try { + Criteria cr = session.createCriteria(RemoteCatalogValues.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying RemoteCatalogValues Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getRemoteCatalogValuesDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(RemoteCatalogValues.class); + List<RemoteCatalogValues> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying RemoteCatalogValues Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public void Save(RemoteCatalogValues attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving RemoteCatalogValues Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void delete(RemoteCatalogValues attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting RemoteCatalogValues Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(RemoteCatalogValues attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating RemoteCatalogValues Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/RolesDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/RolesDaoImpl.java new file mode 100644 index 000000000..7e5c860de --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/RolesDaoImpl.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.dao.RolesDao; +import org.openecomp.policy.model.Roles; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("RolesDao") +public class RolesDaoImpl implements RolesDao{ + private static final Logger logger = FlexLogger.getLogger(RolesDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @Override + public void save(Roles role) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(role); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving Roles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void delete(Roles role) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + System.out.println("delete from Roles where loginid = '"+role.getLoginId()+"'"); + Query q = session.createQuery(" delete from Roles where loginid = '"+role.getLoginId()+"'"); + q.executeUpdate(); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting Roles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @SuppressWarnings("unchecked") + @Override + public List<Roles> getUserRoles(String userId) { + System.out.println("User Id:"+userId); + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<Roles> rolesData = null; + try { + Criteria cr = session.createCriteria(Roles.class); + cr = cr.add(Restrictions.eq("loginId",userId)); + rolesData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Roles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return rolesData; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/RuleAlgorithmsDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/RuleAlgorithmsDaoImpl.java new file mode 100644 index 000000000..149038501 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/RuleAlgorithmsDaoImpl.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("RuleAlgorithmsDao") +public class RuleAlgorithmsDaoImpl implements RuleAlgorithmsDao{ + private static final Logger logger = FlexLogger.getLogger(RuleAlgorithmsDaoImpl.class); + @Autowired + SessionFactory sessionFactory; + + @SuppressWarnings("unchecked") + @Override + public List<RuleAlgorithms> getRuleAlgorithms() { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List<RuleAlgorithms> ruleAlgorithmsData = null; + try { + Criteria cr = session.createCriteria(RuleAlgorithms.class); + ruleAlgorithmsData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying RuleAlgorithms Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return ruleAlgorithmsData; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/SafePolicyWarningDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/SafePolicyWarningDaoImpl.java new file mode 100644 index 000000000..209d60b2d --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/SafePolicyWarningDaoImpl.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.rest.dao.SafePolicyWarningDao; +import org.openecomp.policy.rest.jpa.SafePolicyWarning; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +@Service("SafePolicyWarningDao") +public class SafePolicyWarningDaoImpl implements SafePolicyWarningDao { + private static final Log logger = LogFactory.getLog(SafePolicyWarningDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + public SessionFactory getSessionfactory() { + return sessionfactory; + } + + public void setSessionfactory(SessionFactory sessionfactory) { + this.sessionfactory = sessionfactory; + } + + @SuppressWarnings("unchecked") + @Override + public List<SafePolicyWarning> getSafePolicyWarningData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<SafePolicyWarning> attributeData = null; + try { + Criteria cr = session.createCriteria(SafePolicyWarning.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SafePolicyWarning Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getSafePolicyWarningDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(SafePolicyWarning.class); + List<SafePolicyWarning> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SafePolicyWarning Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public void Save(SafePolicyWarning attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving SafePolicyWarning Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(SafePolicyWarning attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting Attribute Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void update(SafePolicyWarning attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Attribute Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public SafePolicyWarning getSafePolicyWarningDataById(String riskType) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + SafePolicyWarning data = null; + try { + Criteria cr = session.createCriteria(SafePolicyWarning.class); + cr.add(Restrictions.eq("riskType",riskType)); + data = (SafePolicyWarning) cr.list().get(0); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SafePolicyWarning Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/SecurityZoneDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/SecurityZoneDaoImpl.java new file mode 100644 index 000000000..e3661ceb9 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/SecurityZoneDaoImpl.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.rest.dao.SecurityZoneDao; +import org.openecomp.policy.rest.jpa.SecurityZone; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("SecurityZoneDao") +public class SecurityZoneDaoImpl implements SecurityZoneDao{ + private static final Logger logger = FlexLogger.getLogger(SecurityZoneDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<SecurityZone> getSecurityZoneData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<SecurityZone> attributeData = null; + try { + Criteria cr = session.createCriteria(SecurityZone.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SecurityZone Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + + } + + @Override + public void Save(SecurityZone attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving SecurityZone Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void delete(SecurityZone attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting SecurityZone Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(SecurityZone attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating SecurityZone Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getSecurityZoneDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(SecurityZone.class); + List<SecurityZone> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getZoneName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SecurityZone Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/ServiceGroupDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/ServiceGroupDaoImpl.java new file mode 100644 index 000000000..f2e9c5be8 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/ServiceGroupDaoImpl.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.rest.dao.ServiceGroupDao; +import org.openecomp.policy.rest.jpa.GroupServiceList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("ServiceGroupDao") +public class ServiceGroupDaoImpl implements ServiceGroupDao{ + private static final Logger logger = FlexLogger.getLogger(ServiceGroupDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<GroupServiceList> getGroupServiceListData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<GroupServiceList> attributeData = null; + try { + Criteria cr = session.createCriteria(GroupServiceList.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying GroupServiceList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + + } + + @Override + public void Save(GroupServiceList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving GroupServiceList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(GroupServiceList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting GroupServiceList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(GroupServiceList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating GroupServiceList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getGroupServiceDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(GroupServiceList.class); + List<GroupServiceList> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getGroupName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying GroupServiceList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/ServiceListDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/ServiceListDaoImpl.java new file mode 100644 index 000000000..0f80a16d3 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/ServiceListDaoImpl.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.rest.dao.ServiceListDao; +import org.openecomp.policy.rest.jpa.ServiceList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("ServiceListDao") +public class ServiceListDaoImpl implements ServiceListDao { + private static final Logger logger = FlexLogger.getLogger(ServiceListDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<ServiceList> getServiceListData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<ServiceList> attributeData = null; + try { + Criteria cr = session.createCriteria(ServiceList.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying ServiceList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + + } + + @Override + public void Save(ServiceList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving ServiceList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(ServiceList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting ServiceList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(ServiceList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ServiceList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getServiceListDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(ServiceList.class); + List<ServiceList> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getServiceName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying ServiceList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java new file mode 100644 index 000000000..927d20f2f --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.conf.HibernateSession; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.dao.SystemLogDbDao; +import org.openecomp.policy.rest.jpa.SystemLogDB; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@Service("SystemLogDbDao") +public class SystemLogDbDaoImpl implements SystemLogDbDao { + private static final Logger logger = FlexLogger.getLogger(SystemLogDbDaoImpl.class); + @SuppressWarnings("unchecked") + @Override + public List<SystemLogDB> getLoggingData() { + Session session = HibernateSession.getSession(); + Transaction tx = session.beginTransaction(); + List<SystemLogDB> system = null; + try { + String sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) ORDER BY date DESC limit "+PolicyController.logTableLimit+""; + Criteria cr = session.createCriteria(SystemLogDB.class); + cr.add(Restrictions.sqlRestriction(sqlWhere)); + system = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return system; + } + + @SuppressWarnings("unchecked") + @Override + public List<SystemLogDB> getSystemAlertData() { + Session session = HibernateSession.getSession();; + Transaction tx = session.beginTransaction(); + List<SystemLogDB> system = null; + try { + String sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) and logtype = 'error' ORDER BY date DESC limit "+PolicyController.systemAlertTableLimit+""; + Criteria cr = session.createCriteria(SystemLogDB.class); + cr.add(Restrictions.sqlRestriction(sqlWhere)); + system = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return system; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/TermListDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/TermListDaoImpl.java new file mode 100644 index 000000000..ff8f1f26d --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/TermListDaoImpl.java @@ -0,0 +1,176 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.rest.dao.TermListDao; +import org.openecomp.policy.rest.jpa.TermList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("TermListDao") +public class TermListDaoImpl implements TermListDao{ + private static final Logger logger = FlexLogger.getLogger(TermListDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<TermList> getTermListData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<TermList> attributeData = null; + try { + Criteria cr = session.createCriteria(TermList.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying TermList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + + } + + @Override + public void Save(TermList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving TermList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(TermList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting TermList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(TermList attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating TermList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getTermListDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(TermList.class); + List<TermList> attributeData = cr.list(); + for(int i = 0; i < attributeData.size(); i++){ + data.add(attributeData.get(i).getTermName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying TermList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public TermList getTermListValueByName(String name) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + TermList data = null; + try { + Criteria cr = session.createCriteria(TermList.class); + cr.add(Restrictions.eq("termName",name)); + data = (TermList) cr.list().get(0); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying TermList Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/UserInfoDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/UserInfoDaoImpl.java new file mode 100644 index 000000000..ad13b5940 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/UserInfoDaoImpl.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.policy.rest.dao.UserInfoDao; +import org.openecomp.policy.rest.jpa.UserInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@Service("UserInfoDao") +public class UserInfoDaoImpl implements UserInfoDao{ + private static final Logger logger = FlexLogger.getLogger(UserInfoDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + public SessionFactory getSessionfactory() { + return sessionfactory; + } + + public void setSessionfactory(SessionFactory sessionfactory) { + this.sessionfactory = sessionfactory; + } + + @Override + public void save(UserInfo userInfo) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(userInfo); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving UserInfo Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @SuppressWarnings("unchecked") + @Override + public List<UserInfo> getUserInfo() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<UserInfo> userData = null; + try { + Criteria cr = session.createCriteria(UserInfo.class); + userData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying UserInfo Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return userData; + } + + @Override + public String getUserName(String loginid) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + UserInfo user = null; + try { + user = (UserInfo) session.get(UserInfo.class, loginid); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying UserInfo Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return user.getUserName().toString(); + } + + @Override + public UserInfo getUserInfoByLoginId(String loginid) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/VarbindDictionaryDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/VarbindDictionaryDaoImpl.java new file mode 100644 index 000000000..a24c0e7ad --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/VarbindDictionaryDaoImpl.java @@ -0,0 +1,177 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.ArrayList; +import java.util.List; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.rest.dao.VarbindDictionaryDao; +import org.openecomp.policy.rest.jpa.VarbindDictionary; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("VarbindDictionaryDao") +public class VarbindDictionaryDaoImpl implements VarbindDictionaryDao { + private static final Logger logger = FlexLogger.getLogger(VarbindDictionaryDaoImpl.class); + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<VarbindDictionary> getVarbindDictionaryData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<VarbindDictionary> varbindDictionaryData = null; + try { + Criteria cr = session.createCriteria(VarbindDictionary.class); + varbindDictionaryData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying VarbindDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return varbindDictionaryData; + + } + + @Override + public void Save(VarbindDictionary varbindDictionary) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(varbindDictionary); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving VarbindDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(VarbindDictionary varbindDictionary) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(varbindDictionary); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting VarbindDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(VarbindDictionary varbindDictionary) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(varbindDictionary); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating VarbindDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<String> getVarbindDataByName() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<String> data = new ArrayList<String>(); + try { + Criteria cr = session.createCriteria(VarbindDictionary.class); + List<VarbindDictionary> varbindDictionaryData = cr.list(); + for(int i = 0; i < varbindDictionaryData.size(); i++){ + data.add(varbindDictionaryData.get(i).getVarbindName()); + } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying VarbindDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @SuppressWarnings("unchecked") + @Override + public List<VarbindDictionary> getVarbindEntityByName(String value) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<VarbindDictionary> data = null; + try { + Criteria cr = session.createCriteria(VarbindDictionary.class); + cr.add(Restrictions.eq("varbindName",value)); + data = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying VarbindDictionary Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/WatchPolicyNotificationDaoImpl.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/WatchPolicyNotificationDaoImpl.java new file mode 100644 index 000000000..b4b807fbd --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/daoImp/WatchPolicyNotificationDaoImpl.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.daoImp; + + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.rest.jpa.WatchPolicyNotificationTable; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("WatchPolicyNotificationDao") +public class WatchPolicyNotificationDaoImpl implements WatchPolicyNotificationDao{ + + private static final Logger logger = FlexLogger.getLogger(WatchPolicyNotificationDaoImpl.class); + + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings("unchecked") + @Override + public List<WatchPolicyNotificationTable> getListData() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<WatchPolicyNotificationTable> attributeData =null; + try { + Criteria cr = session.createCriteria(WatchPolicyNotificationTable.class); + attributeData = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying WatchPolicyNotificationTable Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return attributeData; + } + + @Override + public void save(WatchPolicyNotificationTable attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving WatchPolicyNotificationTable Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(WatchPolicyNotificationTable attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting WatchPolicyNotificationTable Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + } + + @Override + public void update(WatchPolicyNotificationTable attribute) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(attribute); + tx.commit(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating WatchPolicyNotificationTable Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @SuppressWarnings("unchecked") + @Override + public List<WatchPolicyNotificationTable> getListDataByPolicyName(String policyName) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<WatchPolicyNotificationTable> data = null; + try { + Criteria cr = session.createCriteria(WatchPolicyNotificationTable.class); + cr.add(Restrictions.eq("policyName",policyName)); + data = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying WatchPolicyNotificationTable Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @SuppressWarnings("unchecked") + @Override + public List<WatchPolicyNotificationTable> watchListQuery(String query) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<WatchPolicyNotificationTable> data = null; + try { + Query hbquery = session.createQuery(query); + data = hbquery.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying WatchPolicyNotificationTable Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/ElkConnector.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/ElkConnector.java new file mode 100644 index 000000000..617e67ccb --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/ElkConnector.java @@ -0,0 +1,1235 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.elk.client; + + +import io.searchbox.action.Action; +import io.searchbox.client.JestClient; +import io.searchbox.client.JestClientFactory; +import io.searchbox.client.JestResult; +import io.searchbox.client.config.HttpClientConfig; +import io.searchbox.core.Delete; +import io.searchbox.core.Get; +import io.searchbox.core.Index; +import io.searchbox.core.Search; +import io.searchbox.core.Search.Builder; +import io.searchbox.indices.IndicesExists; +import io.searchbox.indices.type.TypeExist; +import io.searchbox.params.Parameters; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Map.Entry; + +import javax.xml.bind.JAXBException; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.query.QueryStringQueryBuilder; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.kohsuke.args4j.CmdLineException; +import org.kohsuke.args4j.CmdLineParser; +import org.kohsuke.args4j.Option; +import org.openecomp.policy.elk.converter.ElkRecord; +import org.openecomp.policy.elk.converter.Xacml2Elk; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +public interface ElkConnector { + + public static final String ELK_URL = "http://localhost:9200"; + public static final String ELK_INDEX_POLICY = "policy"; + + public enum PolicyIndexType { + config, + action, + decision, + closedloop, + all, + } + + public enum PolicyType { + Config, + Action, + Decision, + Config_Fault, + Config_PM, + Config_FW, + Config_MS, + none, + } + + public enum PolicyBodyType { + json, + xml, + properties, + txt, + none, + } + + public ElkRecord create(PolicyType type, String name, String owner, String scope, + File xacmlFile, PolicyBodyType bodyType, String body, + File destinationDir) + throws IllegalStateException; + + public boolean testAndUpdate(File xacmlFile) throws IllegalStateException; + + public JestResult policy(String policyId) + throws IllegalStateException, IllegalArgumentException; + + public boolean clone(String origPolicyId, String clonePolicyId) + throws IllegalStateException; + + public boolean delete(File xacmlFile) + throws IllegalStateException; + + public ArrayList<PolicyLocator> policyLocators(PolicyIndexType type, String text,int connector) + throws IllegalStateException, IllegalArgumentException; + + public ArrayList<PolicyLocator> policyLocators(PolicyIndexType type, String text, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s,int connector) + throws IllegalStateException, IllegalArgumentException; + + public JestResult search(PolicyIndexType type, String text) + throws IllegalStateException, IllegalArgumentException; + + public JestResult search(PolicyIndexType type, String text, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) + throws IllegalStateException, IllegalArgumentException; + + public boolean update(File xacmlFile) throws IllegalStateException; + + public ElkConnector singleton = new ElkConnectorImpl(); + + public static PolicyIndexType toPolicyIndexType(PolicyType type) + throws IllegalArgumentException { + if (type == null) + throw new IllegalArgumentException("Unsupported NULL type conversion"); + + switch(type) { + case Config: + return PolicyIndexType.config; + case Action: + return PolicyIndexType.action; + case Decision: + return PolicyIndexType.decision; + case Config_Fault: + return PolicyIndexType.closedloop; + case Config_PM: + return PolicyIndexType.closedloop; + case Config_FW: + return PolicyIndexType.config; + case Config_MS: + return PolicyIndexType.config; + case none: + return PolicyIndexType.all; + default: + throw new IllegalArgumentException("Unsupported type conversion to index: " + type.name()); + } + } + + public static PolicyIndexType toPolicyIndexType(String policyName) + throws IllegalArgumentException { + if (policyName == null) + throw new IllegalArgumentException("Unsupported NULL policy name conversion"); + + if (policyName.startsWith("Config_Fault")) { + return PolicyIndexType.closedloop; + } else if (policyName.startsWith("Config_PM")) { + return PolicyIndexType.closedloop; + } else if (policyName.startsWith("Config_FW")) { + return PolicyIndexType.config; + } else if (policyName.startsWith("Config_MS")) { + return PolicyIndexType.config; + }else if (policyName.startsWith("Action")) { + return PolicyIndexType.action; + } else if (policyName.startsWith("Decision")) { + return PolicyIndexType.decision; + } else if (policyName.startsWith("Config")) { + return PolicyIndexType.config; + } else { + throw new IllegalArgumentException + ("Unsupported policy name conversion to index: " + + policyName); + } + } + + public static PolicyType toPolicyType(String policyName) + throws IllegalArgumentException { + if (policyName == null) + throw new IllegalArgumentException("Unsupported NULL policy name conversion to Policy Type"); + + if (policyName.startsWith("Config_Fault")) { + return PolicyType.Config_Fault; + } else if (policyName.startsWith("Config_PM")) { + return PolicyType.Config_PM; + } else if (policyName.startsWith("Config_FW")) { + return PolicyType.Config_FW; + } else if (policyName.startsWith("Config_MS")) { + return PolicyType.Config_MS; + }else if (policyName.startsWith("Action")) { + return PolicyType.Action; + } else if (policyName.startsWith("Decision")) { + return PolicyType.Decision; + } else if (policyName.startsWith("Config")) { + return PolicyType.Config; + } else { + throw new IllegalArgumentException + ("Unsupported policy name conversion to index: " + + policyName); + } + } + + public static void main(String args[]) + throws JAXBException, IOException, CmdLineException, IllegalStateException { + ElkConnectorImpl.CLIOptions cliOptions = new ElkConnectorImpl.CLIOptions(); + CmdLineParser cliParser= new CmdLineParser(cliOptions); + try { + cliParser.parseArgument(args); + } catch (CmdLineException e) { + System.out.println("Usage: ElkConnector"); + cliParser.printUsage(System.out); + throw e; + } + + if (cliOptions.searchText != null && !cliOptions.searchText.isEmpty()) { + ArrayList<PolicyLocator> locators = + ElkConnector.singleton.policyLocators(PolicyIndexType.all, cliOptions.searchText,0); + for (PolicyLocator l: locators) { + System.out.println(l); + } + } else if (cliOptions.testFile != null && cliOptions.testFile.canRead()) { + boolean ok = ElkConnector.singleton.testAndUpdate(cliOptions.testFile); + System.out.println(cliOptions.testFile.getName() + ":" + ok); + } + } +} + +class ElkConnectorImpl implements ElkConnector { + + protected static class CLIOptions { + @Option(name="-s", usage="search", aliases={"-search", "--search"}, required=false, metaVar="<search text>") + protected String searchText; + + @Option(name="-e", usage="test and update policy if not exists", aliases={"-exist", "--exists"}, required=false, metaVar="<policy file>") + protected File testFile; + + @Option(name = "-h", aliases = {"-help", "--help"}, usage = "print this message") + private boolean help = false; + }; + + private static final String POLICY_RESULT_FIELDS = "[ \"Policy.PolicyType\", " + + "\"Policy.PolicyName\", " + + "\"Policy.Owner\", " + + "\"Policy.Scope\", " + + "\"Policy.PolicyId\", " + + "\"Policy.Version\" ]"; + + private static final String SOURCE_RESULT_FIELDS = "\"_source\": " + POLICY_RESULT_FIELDS; + + private static final Logger logger = FlexLogger.getLogger(ElkConnector.class); + + protected final JestClientFactory jestFactory = new JestClientFactory(); + protected final JestClient jestClient; + protected static int QUERY_MAXRECORDS = 1000; + + public ElkConnectorImpl() { + if (logger.isDebugEnabled()) logger.debug("ENTER: -"); + + HttpClientConfig jestClientConfig = + new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); + jestFactory.setHttpClientConfig(jestClientConfig); + jestClient = jestFactory.getObject(); + } + + protected boolean isType(PolicyIndexType type) throws IOException { + if (logger.isDebugEnabled()) logger.debug("ENTER: -"); + + try { + Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY). + addType(type.toString()). + build(); + JestResult result = jestClient.execute(typeQuery); + + if (logger.isInfoEnabled()) { + logger.info("JSON:" + result.getJsonString()); + logger.info("ERROR:" + result.getErrorMessage()); + logger.info("PATH:" + result.getPathToResult()); + logger.info(result.getJsonObject()); + } + return result.isSucceeded(); + } catch (IOException e) { + logger.warn("Error checking type existance of " + type.toString() + + ": " + e.getMessage(), e); + throw e; + } + } + + protected boolean isIndex() throws IOException { + try { + Action<JestResult> indexQuery = + new IndicesExists.Builder(ELK_INDEX_POLICY).build(); + + JestResult result = jestClient.execute(indexQuery); + if (logger.isInfoEnabled()) { + logger.info("JSON:" + result.getJsonString()); + logger.info("ERROR:" + result.getErrorMessage()); + logger.info("PATH:" + result.getPathToResult()); + logger.info(result.getJsonObject()); + } + return result.isSucceeded(); + } catch (IOException e) { + logger.warn("Error checking index existance of " + + ELK_INDEX_POLICY + + ": " + e.getMessage(), e); + throw e; + } + } + + @Override + public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException { + if (logger.isTraceEnabled()) + logger.trace("ENTER: " + text); + + if (text == null || text.isEmpty()) { + throw new IllegalArgumentException("No search string provided"); + } + + // MatchQueryBuilder mQ = QueryBuilders.matchQuery("_all", text); + QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery(text); + SearchSourceBuilder searchSourceBuilder = + new SearchSourceBuilder().query(mQ). + fetchSource(new String[]{"Policy.PolicyType", + "Policy.PolicyName", + "Policy.Owner", + "Policy.Scope", + "Policy.PolicyId", + "Policy.Version"}, + null); + Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()). + addIndex(ELK_INDEX_POLICY). + setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); + + if (type == null || type == PolicyIndexType.all) { + for (PolicyIndexType pT: PolicyIndexType.values()) { + if (pT != PolicyIndexType.all) { + searchBuilder.addType(pT.toString()); + } + } + } else { + searchBuilder.addType(type.toString()); + } + + Search search = searchBuilder.build(); + + JestResult result; + try { + result = jestClient.execute(search); + } catch (IOException ioe) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + search + ": " + ioe.getMessage(), ioe); + throw new IllegalStateException(ioe); + } + + if (result.isSucceeded()) { + if (logger.isInfoEnabled()) + logger.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); + } else { + /* Unsuccessful search */ + if (logger.isWarnEnabled()) + logger.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + + result.getResponseCode() + ": " + + search.getURI() + ":" + + result.getPathToResult() + ":" + + result.getJsonString() + ":" + + result.getErrorMessage()); + + String errorMessage = result.getErrorMessage(); + if (errorMessage != null && !errorMessage.isEmpty()) { + String xMessage = errorMessage; + if (errorMessage.contains("TokenMgrError")) { + int indexError = errorMessage.lastIndexOf("TokenMgrError"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("QueryParsingException")) { + int indexError = errorMessage.lastIndexOf("QueryParsingException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("JsonParseException")) { + int indexError = errorMessage.lastIndexOf("JsonParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("Parse Failure")) { + int indexError = errorMessage.lastIndexOf("Parse Failure"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("SearchParseException")) { + int indexError = errorMessage.lastIndexOf("SearchParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else { + xMessage = result.getErrorMessage(); + } + throw new IllegalStateException(xMessage); + } + } + + return result; + } + + public JestResult searchKey(PolicyIndexType type, String text, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s,int connector) + throws IllegalStateException, IllegalArgumentException { + if (logger.isTraceEnabled()) + logger.trace("ENTER: " + text); + + if (filter_s == null || filter_s.size() <= 0) { + return search(type, text); + } + + String matches_s = ""; + + if(connector==0)// AND CONNECTOR + { + matches_s = "{\n" + + " " + SOURCE_RESULT_FIELDS + ",\n" + + " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + + " \"query\": {\n" + + " \"bool\" : {\n" + + " \"must\" : ["; + } + else if (connector ==1)//OR CONNECTOR + { + matches_s = "{\n" + + " " + SOURCE_RESULT_FIELDS + ",\n" + + " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + + " \"query\": {\n" + + " \"bool\" : {\n" + + " \"should\" : ["; + } + + for (Pair<ArrayList<String>,ArrayList<String>> p : filter_s) { + ArrayList<String> name_s = p.left(); + ArrayList<String> value_s = p.right(); + + if (name_s == null || name_s.size() <= 0) { + if (logger.isWarnEnabled()) + logger.warn("Defaulting to text search: Empty field name array passed in"); + return search(type, text); + } + + if (logger.isDebugEnabled()) { + for (String n: name_s) { + logger.debug("Filter Name: " + n); + } + } + + if (value_s == null || value_s.size() <= 0) { + if (logger.isWarnEnabled()) + logger.warn("Defaulting to text search: Empty field value array passed in"); + return search(type, text); + } + + if (logger.isDebugEnabled()) { + for (String v: value_s) { + logger.debug("Filter Value: " + v); + } + } + + /* common case: # filter names == # filter values */ + if (name_s.size() == value_s.size()) { + String match = ""; + for (int i=0; i<name_s.size(); i++) { + if (name_s.get(i).contains("*")) { + match = + "{ \"query_string\": { \"fields\": [ \"" + + name_s.get(i) + "\" ], " + + "\"query\" : \"" + + value_s.get(i) + "\" } },"; + } else { + match = + "{ \"match_phrase\": { \"" + + name_s.get(i) + "\" : \"" + + value_s.get(i) + "\" } },"; + } + if (logger.isDebugEnabled()) + logger.debug("Adding Match Line: " + match); + matches_s = matches_s + "\n " + match; + } + } + else if (name_s.size() > value_s.size() && (value_s.size() == 1)) { + String match = + "{ \"multi_match\": { \"query\": \"" + value_s.get(0) + "\", \"type\": \"phrase\", \"fields\": ["; + for (String n: name_s) { + match += " \"" + n + "\","; + } + match = match.substring(0, match.length()-1); + //match += " ] } },"; + match += " ] } },";//debug + if (logger.isDebugEnabled()) + logger.debug("Adding Match Line: " + match); + matches_s = matches_s + "\n " + match; + } else { + if (logger.isWarnEnabled()) + logger.warn("Defaulting to text search: different number of filter names and values"); + return search(type, text); + } + } + + matches_s = matches_s.substring(0, matches_s.length()-1); // remove last comma + + matches_s = matches_s + + " ]\n" + + " }\n" + + " }\n" + + "}"; + + if (logger.isDebugEnabled()) { + logger.debug(matches_s); + } + + Builder searchBuilder = new Search.Builder(matches_s). + addIndex(ELK_INDEX_POLICY); + + if (type == null || type == PolicyIndexType.all) { + for (PolicyIndexType pT: PolicyIndexType.values()) { + if (pT != PolicyIndexType.all) { + searchBuilder.addType(pT.toString()); + } + } + } else { + searchBuilder.addType(type.toString()); + } + + Search search = searchBuilder.build(); + + JestResult result; + try { + result = jestClient.execute(search); + } catch (IOException ioe) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + search + ": " + ioe.getMessage(), ioe); + throw new IllegalStateException(ioe); + } + + if (result.isSucceeded()) { + if (logger.isInfoEnabled()) + logger.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); + } else { + /* Unsuccessful search */ + if (logger.isWarnEnabled()) + logger.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + + result.getResponseCode() + ": " + + search.getURI() + ":" + + result.getPathToResult() + ":" + + result.getJsonString() + ":" + + result.getErrorMessage()); + + String errorMessage = result.getErrorMessage(); + if (errorMessage != null && !errorMessage.isEmpty()) { + String xMessage = errorMessage; + if (errorMessage.contains("TokenMgrError")) { + int indexError = errorMessage.lastIndexOf("TokenMgrError"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("QueryParsingException")) { + int indexError = errorMessage.lastIndexOf("QueryParsingException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("JsonParseException")) { + int indexError = errorMessage.lastIndexOf("JsonParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("Parse Failure")) { + int indexError = errorMessage.lastIndexOf("Parse Failure"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("SearchParseException")) { + int indexError = errorMessage.lastIndexOf("SearchParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else { + xMessage = result.getErrorMessage(); + } + throw new IllegalStateException(xMessage); + } + } + + return result; + } + + + @Override + public JestResult search(PolicyIndexType type, String text, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) + throws IllegalStateException, IllegalArgumentException { + if (logger.isTraceEnabled()) + logger.trace("ENTER: " + text); + + if (filter_s == null || filter_s.size() <= 0) { + return search(type, text); + } + + String matches_s = ""; + matches_s = "{\n" + + " " + SOURCE_RESULT_FIELDS + ",\n" + + " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + + " \"query\": {\n" + + " \"bool\" : {\n" + + " \"must\" : ["; + for (Pair<ArrayList<String>,ArrayList<String>> p : filter_s) { + ArrayList<String> name_s = p.left(); + ArrayList<String> value_s = p.right(); + + if (name_s == null || name_s.size() <= 0) { + if (logger.isWarnEnabled()) + logger.warn("Defaulting to text search: Empty field name array passed in"); + return search(type, text); + } + + if (logger.isDebugEnabled()) { + for (String n: name_s) { + logger.debug("Filter Name: " + n); + } + } + + if (value_s == null || value_s.size() <= 0) { + if (logger.isWarnEnabled()) + logger.warn("Defaulting to text search: Empty field value array passed in"); + return search(type, text); + } + + if (logger.isDebugEnabled()) { + for (String v: value_s) { + logger.debug("Filter Value: " + v); + } + } + + /* common case: # filter names == # filter values */ + if (name_s.size() == value_s.size()) { + String match = ""; + for (int i=0; i<name_s.size(); i++) { + if (name_s.get(i).contains("*")) { + match = + "{ \"query_string\": { \"fields\": [ \"" + + name_s.get(i) + "\" ], " + + "\"query\" : \"" + + value_s.get(i) + "\" } },"; + } else { + match = + "{ \"match_phrase\": { \"" + + name_s.get(i) + "\" : \"" + + value_s.get(i) + "\" } },"; + } + if (logger.isDebugEnabled()) + logger.debug("Adding Match Line: " + match); + matches_s = matches_s + "\n " + match; + } + } else if (name_s.size() > value_s.size() && (value_s.size() == 1)) { + String match = + "{ \"multi_match\": { \"query\": \"" + value_s.get(0) + "\", \"type\": \"phrase\", \"fields\": ["; + for (String n: name_s) { + match += " \"" + n + "\","; + } + match = match.substring(0, match.length()-1); + match += " ] } },"; + if (logger.isDebugEnabled()) + logger.debug("Adding Match Line: " + match); + matches_s = matches_s + "\n " + match; + } else { + if (logger.isWarnEnabled()) + logger.warn("Defaulting to text search: different number of filter names and values"); + return search(type, text); + } + } + if (text != null && !text.isEmpty()) { + if (logger.isDebugEnabled()) + logger.debug("Adding Match Line for search text: " + text); + + final JsonObject jsonText = new JsonObject(); + jsonText.addProperty("_all", text); + String escapedText = jsonText.toString(); + + matches_s = matches_s + "\n " + + "{ \"match\": " + + escapedText + " },"; + } + matches_s = matches_s.substring(0, matches_s.length()-1); // remove last comma + matches_s = matches_s + "\n" + + " ]\n" + + " }\n" + + " }\n" + + "}"; + + if (logger.isDebugEnabled()) { + logger.debug(matches_s); + } + + Builder searchBuilder = new Search.Builder(matches_s). + addIndex(ELK_INDEX_POLICY); + + if (type == null || type == PolicyIndexType.all) { + for (PolicyIndexType pT: PolicyIndexType.values()) { + if (pT != PolicyIndexType.all) { + searchBuilder.addType(pT.toString()); + } + } + } else { + searchBuilder.addType(type.toString()); + } + + Search search = searchBuilder.build(); + + JestResult result; + try { + result = jestClient.execute(search); + } catch (IOException ioe) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + search + ": " + ioe.getMessage(), ioe); + throw new IllegalStateException(ioe); + } + + if (result.isSucceeded()) { + if (logger.isInfoEnabled()) + logger.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); + } else { + /* Unsuccessful search */ + if (logger.isWarnEnabled()) + logger.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + + result.getResponseCode() + ": " + + search.getURI() + ":" + + result.getPathToResult() + ":" + + result.getJsonString() + ":" + + result.getErrorMessage()); + + String errorMessage = result.getErrorMessage(); + if (errorMessage != null && !errorMessage.isEmpty()) { + String xMessage = errorMessage; + if (errorMessage.contains("TokenMgrError")) { + int indexError = errorMessage.lastIndexOf("TokenMgrError"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("QueryParsingException")) { + int indexError = errorMessage.lastIndexOf("QueryParsingException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("JsonParseException")) { + int indexError = errorMessage.lastIndexOf("JsonParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("Parse Failure")) { + int indexError = errorMessage.lastIndexOf("Parse Failure"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("SearchParseException")) { + int indexError = errorMessage.lastIndexOf("SearchParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else { + xMessage = result.getErrorMessage(); + } + throw new IllegalStateException(xMessage); + } + } + + return result; + } + + @Override + public JestResult policy(String policyId) + throws IllegalStateException, IllegalArgumentException { + if (logger.isTraceEnabled()) + logger.trace("ENTER: " + policyId); + + if (policyId == null || policyId.isEmpty()) { + throw new IllegalArgumentException("No policy id string provided"); + } + + Get policyRequest = new Get.Builder(ELK_INDEX_POLICY, policyId).build(); + + if (logger.isInfoEnabled()) + logger.info("ELK Search body request: " + policyRequest.toString()); + + JestResult result; + try { + result = jestClient.execute(policyRequest); + } catch (IOException ioe) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + policyId + ": " + ioe.getMessage(), ioe); + throw new IllegalStateException(ioe); + } + + if (result.isSucceeded()) { + if (logger.isInfoEnabled()) + logger.info("OK:" + result.getResponseCode() + ":" + policyId + ":" + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); + + return result; + } + + /* Unsuccessful search */ + if (logger.isWarnEnabled()) + logger.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + + result.getResponseCode() + ": " + policyId + ":" + + result.getPathToResult() + ":" + + result.getErrorMessage()); + + return result; + } + + protected JsonObject getJsonObject(JsonObject jsonObject, String member) throws IllegalArgumentException { + if (jsonObject == null) { + if (logger.isWarnEnabled()) + logger.warn("No JSON object provided to get " + member); + + throw new IllegalArgumentException("No JSON Object provided"); + } + + if (logger.isTraceEnabled()) { + logger.trace("ENTER: " + member); + for (Entry<String, JsonElement> entry: jsonObject.entrySet()) { + logger.trace("JSONOBJECT: " + entry.getKey() + "->" + entry.getValue()); + } + } + + if (jsonObject.has(member)) { + JsonElement element = jsonObject.getAsJsonObject(member); + if (element.isJsonObject()) { + return (JsonObject) element; + } + } + + throw new IllegalArgumentException(member + " is not a JSON Object"); + } + + protected JsonArray getJsonArray(JsonObject jsonObject, String member) throws IllegalArgumentException { + if (jsonObject == null) { + throw new IllegalArgumentException("No JSON Object provided"); + } + + if (jsonObject.has(member)) { + if (jsonObject.get(member).isJsonArray()) { + return (JsonArray) jsonObject.get(member); + } + } + + throw new IllegalArgumentException(member + " is not a JSON Array"); + } + + protected String getJsonPolicyMember(JsonObject aHit, String member) throws IllegalArgumentException { + if (aHit == null) { + throw new IllegalArgumentException("No JSON Object provided"); + } + + JsonObject jSource = getJsonObject(aHit, "_source"); + JsonObject jPolicy = getJsonObject(jSource, "Policy"); + JsonElement jMember = jPolicy.get(member); + if (jMember == null) { + throw new IllegalArgumentException(member + " is not a JSON Object"); + } + return jMember.getAsString(); + } + + @Override + public ArrayList<PolicyLocator> policyLocators(PolicyIndexType indexType, String text, int connector) + throws IllegalStateException, IllegalArgumentException { + return policyLocators(indexType, text, new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(),connector); + } + + @Override + public ArrayList<PolicyLocator> policyLocators(PolicyIndexType indexType, + String text, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s, int connector) + throws IllegalStateException, IllegalArgumentException { + final ArrayList<PolicyLocator> policyLocators = new ArrayList<PolicyLocator>(); + + JestResult results = searchKey(indexType, text, filter_s,connector); + if (!results.isSucceeded()) { + return policyLocators; + } + + JsonArray jsonHit_s = null; + try { + JsonObject jsonHits = getJsonObject(results.getJsonObject(), "hits"); + jsonHit_s = getJsonArray(jsonHits, "hits"); + } catch (IllegalArgumentException e) { + logger.warn("SEARCH:" + text + " no valid element provided", e); + return policyLocators; + } + + for (JsonElement e : jsonHit_s) { + JsonObject elkSource = (JsonObject) e; + try { + String policyType = getJsonPolicyMember(elkSource,"PolicyType"); + String policyName = getJsonPolicyMember(elkSource,"PolicyName"); + String owner = getJsonPolicyMember(elkSource,"Owner"); + String scope = getJsonPolicyMember(elkSource,"Scope"); + String policyId = getJsonPolicyMember(elkSource,"PolicyId"); + String version = getJsonPolicyMember(elkSource,"Version"); + PolicyLocator policyLocator = + new PolicyLocator(policyType, policyName, owner, + scope, policyId, version); + policyLocators.add(policyLocator); + if (logger.isInfoEnabled()) { + logger.info("SEARCH:" + text + "|FOUND:" + policyLocator); + } + } catch (IllegalArgumentException ex) { + logger.warn("SEARCH:" + text + " missing locator information.", ex); + } + } + return policyLocators; + } + + public boolean put(String record, PolicyType type, String id) + throws IOException, IllegalStateException { + if (logger.isTraceEnabled()) logger.trace("ENTER"); + + PolicyIndexType indexType; + try { + indexType = ElkConnector.toPolicyIndexType(type); + } catch (IllegalArgumentException e) { + throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + + " Type: " + type + " :" + e.getMessage()); + } + + if (indexType == PolicyIndexType.all) { + throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + + " Bad Type: " + type.toString()); + } + + if (!isType(indexType)) { + throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + + " Type: " + type.toString() + + " is not configured"); + } + + Index elkPut = new Index.Builder(record). + index(ELK_INDEX_POLICY). + type(indexType.name()). + id(id). + build(); + + JestResult result = jestClient.execute(elkPut); + + if (result.isSucceeded()) { + if (logger.isInfoEnabled()) + logger.info("OK: PUT operation of " + type.name() + "->" + indexType + ":" + id + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + } else { + if (logger.isWarnEnabled()) + logger.warn("FAILURE: PUT operation of " + type.name() + "->" + indexType + ":" + id + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + + } + + return result.isSucceeded(); + } + + @Override + public boolean clone(String origPolicyId, String clonePolicyId) + throws IllegalStateException { + if (logger.isTraceEnabled()) logger.trace("ENTER"); + + String methodLog = "[" + + "original-policy-id:" + origPolicyId + "|" + + "cloned-policy-id:" + clonePolicyId + "]"; + + if (logger.isDebugEnabled()) + logger.debug(methodLog); + + if (origPolicyId == null || clonePolicyId == null || + origPolicyId.isEmpty() || clonePolicyId.isEmpty()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "Internal Error: original and cloned policy ids are identical: " + + origPolicyId + "->" + clonePolicyId + " :" + + methodLog); + throw new IllegalStateException(": " + "original and cloned policy ids are identical."); + } + + // GET original record + JestResult result = this.policy(origPolicyId); + if (!result.isSucceeded()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "Internal Error: not found policy id: " + + origPolicyId + " :" + + methodLog); + throw new IllegalStateException(": " + "policy id: " + origPolicyId + " not found"); + } + + try { + String policyId = getJsonPolicyMember(result.getJsonObject(),"PolicyId"); + String policyType = getJsonPolicyMember(result.getJsonObject(),"PolicyType"); + if (policyType == null || policyType.isEmpty()) { + throw new IllegalStateException(": " + origPolicyId + + " invalid policy type: " + policyType); + } + PolicyType policyTypeEnum = PolicyType.valueOf(policyType); + String newPolicyId = policyId.replace(origPolicyId, clonePolicyId); + + JsonObject jsonSource = getJsonObject(result.getJsonObject(), "_source"); + JsonObject jsonPolicy = getJsonObject(jsonSource, "Policy"); + jsonPolicy.addProperty("PolicyId", newPolicyId); + String sourcePolicy = new Gson().toJson(jsonPolicy); + return put(sourcePolicy, policyTypeEnum, clonePolicyId); + } catch (IllegalArgumentException e) { + logger.warn("POLICY-SEARCH:" + origPolicyId + " not properly found", e); + throw new IllegalStateException(": " + origPolicyId + " not found in ELK"); + } catch (IOException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "cannot create searchable record for " + methodLog + + ". Reason: " + e.getMessage(), e); + throw new IllegalStateException(": Communication Problem with ELK server"); + } + } + + @Override + public boolean delete(File xacmlFile) throws IllegalStateException { + if (logger.isDebugEnabled()) + logger.debug("ENTER: " + "[xacml-file:" + + ((xacmlFile != null) ? xacmlFile.getPath() : "null")+ "]"); + + if (xacmlFile == null || !xacmlFile.canRead()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "Internal Error: invalid arguments provided: " + + ((xacmlFile != null) ? xacmlFile.getPath() : "null")+ "]"); + throw new IllegalStateException(": " + "Invalid arguments to convert to ELK format."); + } + + String policyId = ""; + PolicyIndexType indexType = null; + JestResult result; + try { + indexType = ElkConnector.toPolicyIndexType(xacmlFile.getName()); + if (!isType(indexType)) { + throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + + " Type: " + indexType + + " is not configured"); + } + Xacml2Elk searchablePolicy = new Xacml2Elk(xacmlFile, true); + policyId = searchablePolicy.getPolicy().getValue().getPolicyId(); + policyId = policyId.substring(policyId.lastIndexOf(":")+1); + Delete deleteRequest = + new Delete.Builder(policyId).index(ELK_INDEX_POLICY). + type(indexType.name()).build(); + result = jestClient.execute(deleteRequest); + } catch (IllegalArgumentException | IOException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + + ((indexType != null) ? indexType.name() : "null") + ":" + policyId + ": " + + e.getMessage(), e); + throw new IllegalStateException(e); + } + + if (result.isSucceeded()) { + if (logger.isInfoEnabled()) + logger.info("OK: DELETE operation of " + indexType + ":" + policyId + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + } else { + if (logger.isWarnEnabled()) + logger.warn("FAILURE: DELETE operation of " + indexType + ":" + policyId + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + } + + return result.isSucceeded(); + } + + @Override + public ElkRecord create(PolicyType policyType, + String name, + String owner, + String scope, + File xacmlFile, + PolicyBodyType bodyType, + String body, + File destinationDir) + throws IllegalStateException { + if (logger.isTraceEnabled()) logger.trace("ENTER"); + + String methodLog = "[" + + "type:" + policyType.name() + "|" + + "owner:" + owner + "|" + + "scope:" + scope + "|" + + "xacml-file:" + ((xacmlFile != null) ? xacmlFile.getPath() : "null")+ "|" + + "body-type:" + bodyType.name() + "|" + + "body:" + body + "|" + + "destination-dir:" + ((destinationDir != null) ? destinationDir.getPath() : "null")+ "]"; + + if (logger.isDebugEnabled()) + logger.debug(methodLog); + + if (policyType == null || name == null || owner == null || scope == null || + xacmlFile == null) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "Internal Error: invalid arguments provided for " + methodLog); + throw new IllegalStateException(": " + "Invalid arguments to convert to ELK format."); + } + + try { + Xacml2Elk searchablePolicy = + new Xacml2Elk(policyType.name(), + name, + owner, + scope, + xacmlFile, + bodyType, + body, + destinationDir); + ElkRecord elkRecord = searchablePolicy.record(); + put(elkRecord.record, policyType, elkRecord.policyId); + return elkRecord; + } catch (JAXBException | JsonProcessingException | IllegalArgumentException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "cannot create searchable record for " + methodLog + + ". Reason: " + e.getMessage(), e); + throw new IllegalStateException(": " + "Error encountered converting to ELK format."); + } catch (IOException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "cannot create searchable record for " + methodLog + + ". Reason: " + e.getMessage(), e); + throw new IllegalStateException(": " + "Communication Problem with ELK server."); + } + } + + @Override + public boolean update(File xacmlFile) throws IllegalStateException { + if (logger.isDebugEnabled()) + logger.debug("ENTER: " + "[xacml-file:" + + ((xacmlFile != null) ? xacmlFile.getPath() : "null")+ "]"); + + if (xacmlFile == null || !xacmlFile.canRead()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "Internal Error: invalid arguments provided: " + + ((xacmlFile != null) ? xacmlFile.getPath() : "null")+ "]"); + throw new IllegalStateException(": " + "Invalid arguments to convert to ELK format."); + } + + Xacml2Elk searchablePolicy = new Xacml2Elk(xacmlFile, false); + return update(xacmlFile, searchablePolicy); + } + + protected boolean update(File xacmlFile, Xacml2Elk searchablePolicy) throws IllegalStateException { + if (logger.isDebugEnabled()) + logger.debug("ENTER"); + + try { + ElkRecord elkRecord = searchablePolicy.record(); + boolean success = put(elkRecord.record, ElkConnector.toPolicyType(xacmlFile.getName()), elkRecord.policyId); + return success; + } catch (JAXBException | JsonProcessingException | IllegalArgumentException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "cannot create searchable record for " + xacmlFile.getAbsolutePath() + + ". Reason: " + e.getMessage(), e); + throw new IllegalStateException(": " + "Error encountered converting to ELK format for " + + xacmlFile.getAbsolutePath()); + } catch (IOException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "cannot create ELK searchable record for " + xacmlFile.getAbsolutePath() + + ". Reason: " + e.getMessage(), e); + throw new IllegalStateException(": " + "Communication Problem with ELK server."); + } catch (IllegalStateException e) { + /* unexpected */ + throw e; + } catch (Exception e) { + logger.warn(XACMLErrorConstants.ERROR_UNKNOWN + ":" + "cannot test and update", e); + throw new IllegalStateException(e); + } + } + + @Override + public boolean testAndUpdate(File xacmlFile) throws IllegalStateException { + if (logger.isDebugEnabled()) + logger.debug("ENTER: " + "[xacml-file:" + + ((xacmlFile != null) ? xacmlFile.getPath() : "null")+ "]"); + + if (xacmlFile == null || !xacmlFile.canRead()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "Internal Error: invalid arguments provided: " + + ((xacmlFile != null) ? xacmlFile.getPath() : "null")+ "]"); + throw new IllegalStateException(": " + "Invalid arguments to convert to ELK format."); + } + + try { + Xacml2Elk searchablePolicy = new Xacml2Elk(xacmlFile, true); + String policyId = searchablePolicy.getPolicy().getValue().getPolicyId(); + policyId = policyId.substring(policyId.lastIndexOf(":")+1); + JestResult result = this.policy(policyId); + if (result.isSucceeded()) { + logger.info("Policy exists: " + policyId); + + /* validation tests */ + + String policyType = getJsonPolicyMember(result.getJsonObject(), "PolicyType"); + String scope = getJsonPolicyMember(result.getJsonObject(), "Scope"); + String policyName = getJsonPolicyMember(result.getJsonObject(), "PolicyName"); + if (policyType == null || policyType.isEmpty() || + scope == null || scope.isEmpty() || + policyName == null || policyName.isEmpty()) { + logger.warn("Policy metadata not found. Updating record .."); + update(xacmlFile, searchablePolicy); + return false; + } + + if (!xacmlFile.getName().startsWith(policyType)) { + logger.warn(xacmlFile.getName() + " does not match Policy Type: " + + policyType); + update(xacmlFile, searchablePolicy); + return false; + } + + java.nio.file.Path xacmlElkPath = Paths.get(scope, policyType + "_" + policyName + ".xml"); + java.nio.file.Path xacmlPath = xacmlFile.toPath(); + + if (logger.isDebugEnabled()) { + logger.debug(xacmlElkPath + " in " + xacmlElkPath + "? "); + } + + if (!xacmlPath.endsWith(xacmlElkPath)) { + logger.warn(xacmlPath + " does not match ELK inferred path: " + + xacmlElkPath); + update(xacmlFile, searchablePolicy); + return false; + } + + if (logger.isInfoEnabled()) { + logger.warn("OK: " + xacmlPath + " matches ELK inferred path: " + + xacmlElkPath); + } + return true; + } else { + logger.info("Policy ID not found. Adding to database: " + policyId); + update(xacmlFile, searchablePolicy); + return false; + } + } catch (Exception e) { + logger.warn(XACMLErrorConstants.ERROR_UNKNOWN + ":" + "cannot test and update", e); + throw new IllegalStateException(e); + } + } +}
\ No newline at end of file diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/Pair.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/Pair.java new file mode 100644 index 000000000..3c7b9951d --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/Pair.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.elk.client; + + +public class Pair<L,R> { + private L left; + private R right; + public Pair(L l, R r){ + this.left = l; + this.right = r; + } + public L left(){ return left; } + public R right(){ return right; } + public void left(L l){ this.left = l; } + public void right(R r){ this.right = r; } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/PolicyElasticSearchController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/PolicyElasticSearchController.java new file mode 100644 index 000000000..ee745236f --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/PolicyElasticSearchController.java @@ -0,0 +1,756 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.elk.client; + + +import java.io.File; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.ClosedLoopPerformanceMetrics; +import org.openecomp.policy.adapter.ClosedLoopPolicy; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.elk.client.ElkConnector.PolicyIndexType; +import org.openecomp.policy.rest.dao.DescriptiveScopeDao; +import org.openecomp.policy.rest.jpa.ActionPolicyDict; +import org.openecomp.policy.rest.jpa.Attribute; +import org.openecomp.policy.rest.jpa.BRMSParamTemplate; +import org.openecomp.policy.rest.jpa.ClosedLoopD2Services; +import org.openecomp.policy.rest.jpa.ClosedLoopSite; +import org.openecomp.policy.rest.jpa.DCAEuuid; +import org.openecomp.policy.rest.jpa.DecisionSettings; +import org.openecomp.policy.rest.jpa.DescriptiveScope; +import org.openecomp.policy.rest.jpa.EcompName; +import org.openecomp.policy.rest.jpa.EnforcingType; +import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; +import org.openecomp.policy.rest.jpa.MicroServiceLocation; +import org.openecomp.policy.rest.jpa.MicroServiceModels; +import org.openecomp.policy.rest.jpa.PEPOptions; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RiskType; +import org.openecomp.policy.rest.jpa.SafePolicyWarning; +import org.openecomp.policy.rest.jpa.TermList; +import org.openecomp.policy.rest.jpa.VNFType; +import org.openecomp.policy.rest.jpa.VSCLAction; +import org.openecomp.policy.rest.jpa.VarbindDictionary; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping({"/"}) +public class PolicyElasticSearchController extends RestrictedBaseController{ + + private static final Logger logger = FlexLogger.getLogger(PolicyElasticSearchController.class); + private volatile HashMap<Path, String> filteredPolicies = new HashMap<Path, String>(); + private List<JSONObject> policyNames = null; + + enum Mode{ + attribute, ecompName, actionPolicy, brmsParam, pepOptions, clSite, clService, clVarbind, clVnf, clVSCL, decision, enforcer, fwTerm, gocEventAlarm, + gocTraversal, gocRootCause, gocVnfType, gocServerScope, gocHPEventSource, msDCAEUUID, msConfigName, msLocation, msModels, + psGroupPolicy, safeRisk, safePolicyWarning + } + + public static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() { + private static final long serialVersionUID = 1L; + { + put(ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_TRINITY, ClosedLoopPolicy.CLFAULT_UIJSON_D2_SERVICES_TRINITY); + put(ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_VUSP, ClosedLoopPolicy.CLFAULT_UIJSON_D2_SERVICES_VUSP); + put(ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_MCR, ClosedLoopPolicy.CLFAULT_UIJSON_D2_SERVICES_MCR); + put(ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_GAMMA, ClosedLoopPolicy.CLFAULT_UIJSON_D2_SERVICES_GAMMA); + put(ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_VDNS, ClosedLoopPolicy.CLFAULT_UIJSON_D2_SERVICES_VDNS); + + put(ClosedLoopPolicy.CLFAULT_UIFIELD_EMAIL_ADDRESS, ClosedLoopPolicy.CLFAULT_UIJSON_EMAIL_ADDRESS); + put(ClosedLoopPolicy.CLFAULT_UIFIELD_TRIGGER_SIGNATURE, ClosedLoopPolicy.CLFAULT_UIJSON_TRIGGER_SIGNATURE); + put(ClosedLoopPolicy.CLFAULT_UIFIELD_VERIFICATION_SIGNATURE, ClosedLoopPolicy.CLFAULT_UIJSON_VERIFICATION_SIGNATURE); + put(ClosedLoopPolicy.CLFAULT_UIFIELD_CONNECT_ALL_TRAPS, ClosedLoopPolicy.CLFAULT_UIJSON_CONNECT_ALL_TRAPS); + put(ClosedLoopPolicy.CLFAULT_UIFIELD_CONNECT_ALL_FAULTS, ClosedLoopPolicy.CLFAULT_UIJSON_CONNECT_ALL_FAULTS); + + put(ClosedLoopPolicy.CLFAULT_UIFIELD_POLICY_STATUS_INACTIVE, ClosedLoopPolicy.CLFAULT_UIJSON_POLICY_STATUS_ACTIVE); + put(ClosedLoopPolicy.CLFAULT_UIFIELD_POLICY_STATUS_ACTIVE, ClosedLoopPolicy.CLFAULT_UIJSON_POLICY_STATUS_INACTIVE); + + put(ClosedLoopPerformanceMetrics.CLPM_UIFIELD_ONSET_MESSAGE, ClosedLoopPerformanceMetrics.CLPM_UIJSON_ONSET_MESSAGE); + put(ClosedLoopPerformanceMetrics.CLPM_UIFIELD_POLICY_NAME, ClosedLoopPerformanceMetrics.CLPM_UIJSON_POLICY_NAME); + put(ClosedLoopPerformanceMetrics.CLPM_UIFIELD_ABATEMENT_MESSAGE, ClosedLoopPerformanceMetrics.CLPM_UIJSON_ABATEMENT_MESSAGE); + put(ClosedLoopPerformanceMetrics.CLPM_UIFIELD_GEOLINK, ClosedLoopPerformanceMetrics.CLPM_UIJSON_GEOLINK); + }}; + + + //For AND and OR logical connector AND=0 and OR=1 + private int connectorSelected; + + public static DescriptiveScopeDao descriptiveScopeDao; + public static PolicyVersionDao policyVersionDao; + + @Autowired + public PolicyElasticSearchController(DescriptiveScopeDao descriptiveScopeDao, PolicyVersionDao policyVersionDao) { + PolicyElasticSearchController.descriptiveScopeDao = descriptiveScopeDao; + PolicyElasticSearchController.policyVersionDao = policyVersionDao; + + } + + public PolicyElasticSearchController() { + } + + @RequestMapping(value={"/searchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + List<JSONObject> resultList = new ArrayList<JSONObject>(); + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + SearchData searchData = (SearchData)mapper.readValue(root.get("searchdata").toString(), SearchData.class); + + String policyType = searchData.getPolicyType(); + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(); + + String searchText = searchData.getQuery(); + if (searchText == null || searchText.isEmpty()) { + String descriptiveValue = searchData.getDescriptiveScope(); + if(descriptiveValue != null){ + searchText = "Descriptive-Scope="+descriptiveValue; + } + if (policyType == null || policyType.isEmpty() && + !policyType.equals(ElkConnector.PolicyIndexType.closedloop.toString())) { + if (logger.isDebugEnabled()) { + logger.debug("Clearing search filters, nothing to search and not closed loop."); + } + } + } else { + searchText = searchText.trim(); + //Descriptive Scope. + /* + When a item is selected in the "descriptiveScope" comboBox, the name of the item + is added to the Search-Text Box with the prefix "Descriptive-Scope" + User needs to press the "Search" button to perform the search. + */ + if(searchText.contains("Descriptive-Scope=")){ + if (logger.isDebugEnabled()) { + logger.debug("Inside the Descriptive Scope"); + } + /* + First item is always String "Descriptive-Scope" before the "=", + So taking the second item of "split using =" + */ + String[] dsName= searchText.split("=",2); + /* + Trying to find the search String by traversing different items from the dictionary by Scope-Name + Once when the the "scope-name" is found, we get the search string from dictionary. + */ + if(searchData.getDescriptiveScope() != null){ + DescriptiveScope dsSearch = descriptiveScopeDao.getDescriptiveScopeById(searchData.getDescriptiveScope()); + if(dsSearch.getScopeName().equals(dsName[1])){ + searchText=dsSearch.getSearch(); + if (logger.isDebugEnabled()) { + logger.debug("DescriptiveScope Search String is " +searchText ); + } + } + } + + } + // '&' turned to "AND" to make it inline with Freeform search. + if(searchText.contains(":")){ + String connector="AND"; + if(searchText.contains("AND")){ + connector="AND"; + connectorSelected=0; + }else if(searchText.contains("OR")){ + connector=Pattern.quote("OR"); + connectorSelected=1; + } + for (String retval: searchText.split(connector)){ + + int index= retval.indexOf(':'); + String filterKey=null; + String filterValue=null; + + filterKey=retval.substring(0,index).trim(); + filterValue= retval.substring(index+1).trim(); + + logger.debug("Key is "+filterKey+" and value is "+filterValue); + String clSearchBoxFilter=filterKey; + + ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>(); + + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchBoxFilter); + + + ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>(); + clSearchBoxFilterValue_s.add(filterValue); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); + } + } + } + + if (policyType != null && !policyType.isEmpty() && + policyType.equals(ElkConnector.PolicyIndexType.closedloop.toString())) { + + /* closed loop policy type */ + + String clPolicyType = searchData.getClosedLooppolicyType(); + if (clPolicyType != null && !clPolicyType.isEmpty()) { + ArrayList<String> clPolicyTypeField_s = new ArrayList<String>(); + clPolicyTypeField_s.add("Policy.PolicyType"); + + ArrayList<String> clPolicyTypeValue_s = new ArrayList<String>(); + clPolicyTypeValue_s.add(clPolicyType); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clPolicyTypeField_s, clPolicyTypeValue_s)); + } + + String clEcompName = searchData.getEcompName(); + if (clEcompName != null && !clEcompName.isEmpty()) { + clSearchBody(clPolicyType, "ecompname", clEcompName, filter_s); + } + + String clD2Services = searchData.getD2Service(); + if (clD2Services != null && !clD2Services.isEmpty()) { + switch (clD2Services) { + case ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_TRINITY: + case ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_VUSP: + case ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_MCR: + case ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_GAMMA: + case ClosedLoopPolicy.CLFAULT_UIFIELD_D2_SERVICES_VDNS: + clSearchBody(clPolicyType, name2jsonPath.get(clD2Services), "true", filter_s); + break; + default: + if (logger.isWarnEnabled()) + logger.warn("Unexpected D2 Service: " + clD2Services); + break; + } + } + + String clFaultAction = searchData.getVproAction(); + if (clFaultAction != null && !clFaultAction.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "actions", clFaultAction, filter_s); + } + } + + String clFaultStatus = searchData.getPolicyStatus(); + if (clFaultStatus != null && !clFaultStatus.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "closedLoopPolicyStatus", clFaultStatus, filter_s); + } + } + + String clFaultVnfTypes = searchData.getVnfType(); + if (clFaultVnfTypes != null && !clFaultVnfTypes.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_Fault.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_Fault.name(), "vnfType", clFaultVnfTypes, filter_s); + } + } + + String clPMServiceType = searchData.getServiceType(); + if (clPMServiceType != null && !clPMServiceType.isEmpty()) { + if (clPolicyType == null || clPolicyType.equals(ElkConnector.PolicyType.Config_PM.name())) { + clSearchFilter(ElkConnector.PolicyType.Config_PM.name(), "serviceTypePolicyName", clPMServiceType, filter_s); + } + } + + String clSearchBoxFilter = searchData.getBindTextSearch(); + if (clSearchBoxFilter != null && !clSearchBoxFilter.isEmpty() && + searchText != null && !searchText.isEmpty()) { + + if (name2jsonPath.containsKey(clSearchBoxFilter)) { + clSearchBoxFilter = name2jsonPath.get(clSearchBoxFilter); + } + + ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>(); + if (clPolicyType == null || clPolicyType.isEmpty()) { + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchBoxFilter); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchBoxFilter); + } else { + clSearchBoxFilterField_s.add("Policy.Body." + clPolicyType + "_Body." + clSearchBoxFilter); + } + + ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>(); + clSearchBoxFilterValue_s.add(searchText); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); + + // deactivate search all fields in case a searchbox filter is provided + searchText = ""; + } + } + + if ((searchText == null || searchText.isEmpty()) && + (filter_s == null || filter_s.size() <=0) ) { + if (logger.isWarnEnabled()) { + logger.warn("Clearing search filters, closed loop but nothing to search nor filters"); + } + } + + ArrayList<PolicyLocator> locators = null; + try { + locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), + searchText, filter_s,connectorSelected); + } catch (Exception ise) { + logger.warn("Search is unavailable: " + ise.getMessage()); + } + + synchronized(this.filteredPolicies) { + if (locators.isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("No match has been found"); + } + logger.warn("No match has been found"); + } + + HashMap<String, Boolean> policyVersion_s = new HashMap<String, Boolean>(); + List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionData(); + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityVersion = policyVersionList.get(i); + String dbPolicy = entityVersion.getPolicyName() + "." + entityVersion.getActiveVersion(); + policyVersion_s.put(dbPolicy, true); + if (logger.isDebugEnabled()) + logger.debug("Map addition: DB Policy Name: " + dbPolicy); + } + + this.filteredPolicies.clear(); + for (PolicyLocator p: locators) { + String dbPolicyName = p.scope + File.separator + p.policyType + "_" + p.policyName; + if (policyVersion_s.containsKey(dbPolicyName)) { + String filterPolicyName = dbPolicyName + ".xml"; + this.filteredPolicies.put(Paths.get(filterPolicyName), filterPolicyName); + JSONObject el = new JSONObject(); + el.put("name", dbPolicyName); + resultList.add(el); + if (logger.isInfoEnabled()) + logger.info("Active Version Policy found in search: " + dbPolicyName + " -> " + filterPolicyName); + } else { + if (logger.isInfoEnabled()) + logger.info("Inactive Version Policy found in search: " + dbPolicyName); + } + } + + if (this.filteredPolicies.isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("No match has been found for active versions"); + } + JSONObject result = new JSONObject(); + result.put("success", false); + result.put("error", "No match has been found for active versions"); + resultList.add(result); + logger.warn("No match has been found for active versions"); + + } + + System.out.println(this.filteredPolicies); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{result: " + resultList + "}"); + 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; + } + + protected void clSearchBody(String clPolicyType, String bodyField, String bodyValue, + ArrayList<Pair<ArrayList<String>, ArrayList<String>>> filter_s) { + if (logger.isDebugEnabled()) + logger.debug("ENTER: " + clPolicyType + ":" + bodyField + ":" + bodyValue); + + final ArrayList<String> clBodyField_s = new ArrayList<String>(); + final ArrayList<String> clBodyValue_s = new ArrayList<String>(); + + if (clPolicyType == null || clPolicyType.isEmpty()) { + clBodyField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + bodyField); + clBodyField_s.add("Policy.Body."+ ElkConnector.PolicyType.Config_PM.name() + "_Body." + bodyField); + clBodyValue_s.add(bodyValue); + } else { + clBodyField_s.add("Policy.Body." + clPolicyType + "_Body." + bodyField); + clBodyValue_s.add(bodyValue); + } + filter_s.add(new Pair<ArrayList<String>, ArrayList<String>>(clBodyField_s, clBodyValue_s)); + } + + protected void clSearchFilter(String clType, String clField, String clValue, + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s) { + if (logger.isDebugEnabled()) + logger.debug("ENTER: " + clType + ":" + clField + ":" + clValue); + + ArrayList<String> clSearchField_s = new ArrayList<String>(); + clSearchField_s.add("Policy.Body." + clType + "_Body." + clField); + + ArrayList<String> clSearchValue_s = new ArrayList<String>(); + clSearchValue_s.add(clValue); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchField_s, clSearchValue_s)); + } + + public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException { + if (type == null || type.isEmpty()) + return PolicyIndexType.all; + + return PolicyIndexType.valueOf(type); + } + + public boolean updateElk(String xacmlFilePath) { + boolean success = true; + try { + File xacmlPolicy = new File(xacmlFilePath); + success = ElkConnector.singleton.update(xacmlPolicy); + if (!success) { + if (logger.isWarnEnabled()) { + logger.warn("FAILURE to create ELK record created for " + xacmlPolicy.getPath()); + } + } else { + if (logger.isInfoEnabled()) { + logger.warn("SUCCESS creating ELK record created for " + xacmlPolicy.getPath()); + } + } + } catch (Exception e) { + logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e); + success = false; + } + return success; + } + + @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView searchDictionary(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()); + String dictionaryType = root.get("type").textValue(); + Mode mode = Mode.valueOf(dictionaryType); + String value; + String msg; + switch (mode){ + case attribute : + Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class); + value = attributedata.getXacmlId(); + msg = searchElkDatabase("pholder",value); + break; + case ecompName : + EcompName ecompName = (EcompName)mapper.readValue(root.get("data").toString(), EcompName.class); + value = ecompName.getEcompName(); + msg = searchElkDatabase("pholder",value); + break; + case actionPolicy : + ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); + value = actionPolicyDict.getAttributeName(); + msg = searchElkDatabase("pholder",value); + break; + case brmsParam : + BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); + value = bRMSParamTemplate.getRuleName(); + msg = searchElkDatabase("BRMSParamTemplate AND " + value); + break; + case pepOptions : + PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class); + value = pEPOptions.getPepName(); + msg = searchElkDatabase("pepName",value); + break; + case clSite : + ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); + value = closedLoopSite.getSiteName(); + msg = searchElkDatabase("siteNames",value); + break; + case clService : + ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); + value = closedLoopD2Services.getServiceName(); + msg = searchElkDatabase("d2Services",value); + break; + case clVarbind : + VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class); + value = varbindDictionary.getVarbindName(); + msg = searchElkDatabase("triggerSignaturesUsedForUI.signatures",value); + break; + case clVnf : + VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class); + value = vNFType.getVnftype(); + msg = searchElkDatabase("vnfType",value); + break; + case clVSCL : + VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class); + value = vsclAction.getVsclaction(); + msg = searchElkDatabase("actions",value); + break; + case decision : + DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class); + value = decisionSettings.getXacmlId(); + msg = searchElkDatabase("pholder",value); + break; + case enforcer : + EnforcingType enforcingType = (EnforcingType)mapper.readValue(root.get("data").toString(), EnforcingType.class); + value = enforcingType.getEnforcingType(); + msg = searchElkDatabase("pholder",value); + break; + case fwTerm : + TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class); + value = term.getTermName(); + msg = searchElkDatabase("firewallRuleList.ruleName",value); + break; + case msDCAEUUID : + DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class); + value = dcaeUUID.getName(); + msg = searchElkDatabase("uuid",value); + break; + case msLocation : + MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); + value = mslocation.getName(); + msg = searchElkDatabase("location",value); + break; + case msModels : + MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class); + value = msModels.getModelName(); + msg = searchElkDatabase("configName",value); + break; + case psGroupPolicy : + GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); + value = groupPoilicy.getGroupName(); + msg = searchElkDatabase("PolicyScope",value); + break; + case safeRisk : + RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class); + value = riskType.getRiskName(); + msg = searchElkDatabase("Risk Type",value); + break; + case safePolicyWarning : + SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); + value = safePolicy.getName(); + msg = searchElkDatabase("Safe Warning",value); + break; + default: + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{result: " + policyNames + "}"); + 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; + } + + //Search Elk database + public String searchElkDatabase(String value){ + String policyType = ""; + String searchText = value; + ArrayList<PolicyLocator> locators; + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(); + try { + locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), searchText, filter_s,0); + } catch (Exception ise) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage()); + value = "$notSuccess%"; + return value; + } + policyNames = new ArrayList<JSONObject>(); + for (PolicyLocator p: locators) { + String dbPolicyName = p.scope + "/" + p.policyType + "_" + p.policyName + "." +p.version + ".xml"; + logger.debug(dbPolicyName); + JSONObject el = new JSONObject(); + el.put("name", dbPolicyName); + policyNames.add(el); + } + if(!locators.isEmpty()){ + value = "$success%"; + return value; + } + return value; + } + + //Search the Elk database + public String searchElkDatabase(String key, String value){ + String policyType = ""; + String searchText = key+":"+value; + ArrayList<PolicyLocator> locators; + ArrayList<Pair<ArrayList<String>,ArrayList<String>>> filter_s = new ArrayList<Pair<ArrayList<String>,ArrayList<String>>>(); + logger.debug("Parameter value is"+value); + + String clSearchKey=null; + clSearchKey=key; + + logger.debug("Filter value is"+clSearchKey); + + ArrayList<String> clSearchBoxFilterField_s = new ArrayList<String>(); + + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_Fault.name() + "_Body." + clSearchKey); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchKey); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_FW.name() + "_Body." + clSearchKey); + clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_MS.name() + "_Body." + clSearchKey); + //clSearchBoxFilterField_s.add("Policy.Body." + ElkConnector.PolicyType.Config_PM.name() + "_Body." + clSearchKey); + + String clSearchValue=null; + clSearchValue=value; + + logger.debug("Search value is"+clSearchValue); + + ArrayList<String> clSearchBoxFilterValue_s = new ArrayList<String>(); + clSearchBoxFilterValue_s.add(clSearchValue); + + filter_s.add(new Pair<ArrayList<String>,ArrayList<String>>(clSearchBoxFilterField_s, clSearchBoxFilterValue_s)); + + try { + locators = ElkConnector.singleton.policyLocators(toPolicyIndexType(policyType), searchText, filter_s,0); + logger.debug("No Exceptions"); + for (PolicyLocator l: locators) { + logger.debug(l.policyName); + } + logger.debug("After for"); + } catch (Exception ise) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Search is unavailable: " + ise.getMessage()); + //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, ise, "AttributeDictionary", " Exception while searching Elk database "); + logger.debug("Exceptions"); + value = "$notSuccess%"; + return value; + } + policyNames = new ArrayList<JSONObject>(); + for (PolicyLocator p: locators) { + String dbPolicyName = p.scope + File.separator + p.policyType + "_" + p.policyName + ".xml"; + logger.debug(dbPolicyName); + JSONObject el = new JSONObject(); + el.put("name", dbPolicyName); + policyNames.add(el); + } + if(!locators.isEmpty()){ + value = "$success%"; + logger.debug("Success"); + return value; + } + return value; + } + +} + + +class SearchData{ + private String query; + private String policyType; + private String descriptiveScope; + private String closedLooppolicyType; + private String ecompName; + private String d2Service; + private String vnfType; + private String policyStatus; + private String vproAction; + private String serviceType; + private String bindTextSearch; + public String getQuery() { + return query; + } + public void setQuery(String query) { + this.query = query; + } + public String getPolicyType() { + return policyType; + } + public void setPolicyType(String policyType) { + this.policyType = policyType; + } + public String getDescriptiveScope() { + return descriptiveScope; + } + public void setDescriptiveScope(String descriptiveScope) { + this.descriptiveScope = descriptiveScope; + } + public String getClosedLooppolicyType() { + return closedLooppolicyType; + } + public void setClosedLooppolicyType(String closedLooppolicyType) { + this.closedLooppolicyType = closedLooppolicyType; + } + public String getEcompName() { + return ecompName; + } + public void setEcompName(String ecompName) { + this.ecompName = ecompName; + } + public String getD2Service() { + return d2Service; + } + public void setD2Service(String d2Service) { + this.d2Service = d2Service; + } + public String getVnfType() { + return vnfType; + } + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + public String getPolicyStatus() { + return policyStatus; + } + public void setPolicyStatus(String policyStatus) { + this.policyStatus = policyStatus; + } + public String getVproAction() { + return vproAction; + } + public void setVproAction(String vproAction) { + this.vproAction = vproAction; + } + public String getServiceType() { + return serviceType; + } + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + public String getBindTextSearch() { + return bindTextSearch; + } + public void setBindTextSearch(String bindTextSearch) { + this.bindTextSearch = bindTextSearch; + } +}
\ No newline at end of file diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/PolicyLocator.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/PolicyLocator.java new file mode 100644 index 000000000..f7cc58fa2 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/client/PolicyLocator.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.elk.client; + + +public class PolicyLocator { + public final String policyType; + public final String policyName; + public final String owner; + public final String scope; + public final String policyId; + public final String version; + + public PolicyLocator(String policyType, String policyName, + String owner, String scope, String policyId, + String version) { + this.policyType = policyType; + this.policyName= policyName; + this.owner = owner; + this.scope = scope; + this.policyId = policyId; + this.version = version; + } + + public String toString() { + return "[" + + this.owner + "|" + + this.scope + "|" + + this.policyType + "|" + + this.policyName + "|" + + this.policyId + "|" + + "v" + this.version + "|" + "]"; + + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/converter/ElkRecord.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/converter/ElkRecord.java new file mode 100644 index 000000000..40bdb7929 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/converter/ElkRecord.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.elk.converter; + + +import com.fasterxml.jackson.databind.JsonNode; + +public class ElkRecord { + public final String record; + public final String policyId; + public final JsonNode jsonRecord; + public final boolean bodyAttached; + + public ElkRecord(final String policyId, + final String record, + final JsonNode jsonRecord, + final boolean bodyAttached) { + this.policyId = policyId; + this.record = record; + this.jsonRecord = jsonRecord; + this.bodyAttached = bodyAttached; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/converter/Xacml2Elk.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/converter/Xacml2Elk.java new file mode 100644 index 000000000..f7aa34ff2 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/elk/converter/Xacml2Elk.java @@ -0,0 +1,978 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.elk.converter; + + +import io.searchbox.core.Update; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.Result; +import javax.xml.transform.stream.StreamResult; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + +import org.apache.commons.io.IOUtils; +import org.eclipse.persistence.jaxb.JAXBContextFactory; +import org.eclipse.persistence.jaxb.MarshallerProperties; +import org.eclipse.persistence.jaxb.json.JsonSchemaOutputResolver; + +import com.att.research.xacml.api.Advice; +import com.att.research.xacml.api.AttributeAssignment; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.Obligation; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.util.XACMLPolicyScanner; +import com.att.research.xacml.util.XACMLProperties; +import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; +import com.att.research.xacml.util.XACMLPolicyScanner.SimpleCallback; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; +import com.fasterxml.jackson.module.jsonSchema.JsonSchema; +import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper; + +import org.kohsuke.args4j.CmdLineException; +import org.kohsuke.args4j.CmdLineParser; +import org.kohsuke.args4j.Option; +import org.openecomp.policy.elk.client.ElkConnector; +import org.openecomp.policy.elk.client.ElkConnector.PolicyBodyType; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@SuppressWarnings("unused") +public class Xacml2Elk { + public static final String URLID_ATTRIBUTE = "URLID"; + public static final String BODY_ATTRIBUTE = "body"; + + protected static final Logger logger = FlexLogger.getLogger(Xacml2Elk.class); + protected static JAXBContext jaxbContext = jaxbContext(); + + protected static String toConfigsWebDirectory(String policyType) + throws IllegalArgumentException { + if (policyType == null || policyType.isEmpty()) + throw new IllegalArgumentException("Unexpected policy type: " + policyType); + + ElkConnector.PolicyType type = ElkConnector.PolicyType.valueOf(policyType); + switch(type) { + case Config: + return type.name(); + case Action: + return type.name(); + case Decision: + return type.name(); + case Config_Fault: + case Config_PM: + case Config_FW: + case Config_MS: + return ElkConnector.PolicyType.Config.name(); + default: + throw new IllegalArgumentException("Unexpected policy type: " + policyType); + } + } + + protected synchronized static JAXBContext jaxbContext() { + if (jaxbContext != null) { + return jaxbContext; + } + + try { + jaxbContext = JAXBContextFactory.createContext(new Class[] {PolicyType.class}, null); + } catch (JAXBException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + "JAXB Context cannot be created"); + return null; + } + + return jaxbContext; + } + + protected static class CLIOptions { + @Option(name="-t", usage="policy type", aliases={"-type", "--type"}, required=true) + protected String type; + + @Option(name="-n", usage="policy name", aliases={"-name", "--name"}, required=true) + protected String name; + + @Option(name="-o", usage="git repository owner", aliases={"-owner", "--owner"}, required=true) + protected String owner; + + @Option(name="-s", usage="enclosing scope", aliases={"-scope", "--scope"}, required=true) + protected String scope; + + @Option(name="-x", usage="xacml input file", aliases={"-xacml", "--xacml"}, required=true, metaVar="<xacml input file>") + protected File xacmlFile; + + @Option(name="-p", usage="payload body type", aliases={"-payloadType", "--payloadType"}, required=false, metaVar="<bayload body type>", depends={"-b"}) + protected PolicyBodyType bodyType; + + @Option(name="-b", usage="payload body", aliases={"-body", "--body"}, required=false, metaVar="<bayload body type>", depends={"-p"}) + protected String body; + + @Option(name="-d", usage="elk record output directory", aliases={"-d", "--directory"}, required=true, metaVar="<elk directory>") + protected File elkDirectory; + + @Option(name = "-h", aliases = {"-help", "--help"}, usage = "print this message") + private boolean help = false; + }; + + class AttributeAssignmentFinderProcessor extends SimpleCallback { + protected final String attributeId; + protected String attributeValue = null; + + public AttributeAssignmentFinderProcessor(String attributeId) { + this.attributeId = attributeId; + } + + public String getAttributeValue() { + return attributeValue; + } + + public boolean isAttributeValue() { + return (this.attributeValue != null && !this.attributeValue.isEmpty()); + } + + private boolean processAssignments( + List<AttributeAssignmentExpressionType> assignments) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + for (AttributeAssignmentExpressionType assignment : assignments) { + if (!assignment.getAttributeId().equals(attributeId)) { + if (logger.isDebugEnabled()) + logger.debug("Ignoring: " + assignment.getAttributeId()); + continue; + } + + if (logger.isDebugEnabled()) + logger.debug("Found Attribute ID: " + assignment.getAttributeId()); + + JAXBElement<?> jaxbExp = assignment.getExpression(); + Object assignmentObject = jaxbExp.getValue(); + if (assignmentObject instanceof AttributeValueType) { + AttributeValueType avt = (AttributeValueType) assignmentObject; + if (avt.getContent().size() <= 0) { + logger.warn("Ignoring: " + assignment.getAttributeId() + ": No values"); + continue; + } + + this.attributeValue = avt.getContent().get(0).toString(); + if (logger.isInfoEnabled()) + logger.info("Found: " + this.attributeValue); + + return true; + } + } + return false; + } + + @Override + public CallbackResult onAdvice(Object parent, AdviceExpressionType expression, Advice advice) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + List<AttributeAssignmentExpressionType> assignments = + expression.getAttributeAssignmentExpression(); + + if (assignments != null) { + boolean found = processAssignments(assignments); + if (found) + return CallbackResult.STOP; + } + + return super.onAdvice(parent, expression, advice); + } + + @Override + public CallbackResult onObligation(Object parent, ObligationExpressionType expression, Obligation obligation) { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + List<AttributeAssignmentExpressionType> assignments = + expression.getAttributeAssignmentExpression(); + + if (assignments != null) { + boolean found = processAssignments(assignments); + if (found) + return CallbackResult.STOP; + } + + return super.onObligation(parent, expression, obligation); + + } + } + + final protected String type; + final protected String name; + final protected String owner; + final protected String scope; + final protected File xacmlFile; + final protected File elkDirectory; + + final protected JAXBElement<PolicyType> policy; + + protected PolicyBodyType bodyType; + protected String body; + + + public Xacml2Elk(String type, String name, + String owner, String scope, + File xacmlFile, File elkDirectory) + throws IllegalArgumentException { + + this.type = type; + this.name = name; + this.owner = owner; + this.scope = scope; + this.xacmlFile = xacmlFile; + this.elkDirectory = elkDirectory; + + this.policy = jaxbXacml(xacmlFile); + + this.body = ""; + this.bodyType = PolicyBodyType.none; + bodyFromXacml(); + } + + public Xacml2Elk(CLIOptions args) throws IllegalArgumentException { + this.type = args.type; + this.name = args.name; + this.owner = args.owner; + this.scope = args.scope; + this.xacmlFile = args.xacmlFile; + this.elkDirectory = args.elkDirectory; + + this.policy = jaxbXacml(xacmlFile); + + if (args.body == null || args.body.isEmpty()) { + this.body = ""; + this.bodyType = PolicyBodyType.none; + bodyFromXacml(); + } else { + this.body = args.body; + this.bodyType = args.bodyType; + } + } + + public Xacml2Elk(String type, String name, String owner, + String scope, File xacmlFile, PolicyBodyType bodyType, + String body, File destinationDir) + throws IllegalArgumentException { + this.type = type; + this.name = name; + this.owner = owner; + this.scope = scope; + this.xacmlFile = xacmlFile; + this.bodyType = bodyType; + this.body = body; + this.elkDirectory = destinationDir; + + this.policy = jaxbXacml(xacmlFile); + } + + public Xacml2Elk(File xacmlFile, boolean skipBody) + throws IllegalArgumentException { + this.policy = jaxbXacml(xacmlFile); + PolicyType jPolicy = this.policy.getValue(); + + this.xacmlFile = xacmlFile; + + this.type = ElkConnector.toPolicyType(xacmlFile.getName()).name(); + String fileName = xacmlFile.getName().replaceFirst(this.type + "_", ""); + if (fileName.indexOf(".") > 0) + this.name = fileName.substring(0, fileName.lastIndexOf(".")); + else + this.name = fileName; + + this.owner = "admin"; + this.scope = getScope(xacmlFile.getParent()); + this.elkDirectory = null; + + this.body = ""; + this.bodyType = PolicyBodyType.none; + if (!skipBody) { + bodyFromXacml(); + } + } + + @SuppressWarnings("unchecked") + protected JAXBElement<PolicyType> jaxbXacml(File xacmlFile) throws IllegalArgumentException { + Path xacmlPath = xacmlFile.toPath(); + if (!Files.isReadable(xacmlPath) || !Files.isRegularFile(xacmlPath)) { + if (logger.isWarnEnabled()) { + logger.warn("Error: " + xacmlPath + " is invalid."); + } + throw new IllegalArgumentException("Error: " + xacmlPath + " is invalid."); + } + + try { + Unmarshaller u = jaxbContext.createUnmarshaller(); + return (JAXBElement<PolicyType>) u.unmarshal(xacmlFile); + } catch (Exception e) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + " - error: " + xacmlPath + " is invalid."); + } + throw new IllegalArgumentException(xacmlFile.getAbsolutePath() + " does not contain valid XACML"); + } + } + + public JAXBElement<PolicyType> getPolicy() { + return policy; + } + + protected String getScope(String xacmlDirPath) { + if (logger.isTraceEnabled()) logger.trace("ENTER"); + + xacmlDirPath = xacmlDirPath.replaceAll("//", "/"); + xacmlDirPath = xacmlDirPath.replaceAll("\\\\", "/"); + xacmlDirPath = xacmlDirPath.replace('\\', '/'); + + String ws = XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE); + String adminRepo = XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY); + Path wsPath = Paths.get(ws, "admin", adminRepo); + File repoDir = wsPath.toFile(); + String repoPath = repoDir.getPath(); + repoPath = repoPath.replaceAll("//", "/"); + repoPath = repoPath.replaceAll("\\\\", "/"); + repoPath = repoPath.replace('\\', '/'); + + int startIndex = xacmlDirPath.indexOf(repoPath.toString()) + repoPath.toString().length() + 1; + String scope = xacmlDirPath.substring(startIndex, xacmlDirPath.length()); + + if (logger.isInfoEnabled()) + logger.info("xacml-policy-path=" + xacmlDirPath + "|" + + "repository-path=" + repoPath + "|" + + "scope=" + scope); + + return scope; + } + + @SuppressWarnings("deprecation") + private boolean bodyFromXacml() { + if (logger.isTraceEnabled()) + logger.trace("ENTER"); + + String urlAttribute = URLID_ATTRIBUTE; + try { + switch (ElkConnector.toPolicyType(this.type)) { + case Action: + urlAttribute = BODY_ATTRIBUTE; + break; + case Decision: + case none: + /* no body attached to decision policies */ + if (logger.isInfoEnabled()) + logger.info("No body attached for this type of policy: " + this.xacmlFile.getAbsolutePath()); + return false; + default: + /* a flavour of a config policy - default is fine */ + break; + } + } catch (IllegalArgumentException iae) { + if (logger.isWarnEnabled()) { + logger.warn(this.type + " cannot be converted to a valid type: " + iae.getMessage(), iae); + } + return false; + } + + AttributeAssignmentFinderProcessor + processor = new AttributeAssignmentFinderProcessor(urlAttribute); + XACMLPolicyScanner xacmlScanner = + new XACMLPolicyScanner(this.policy.getValue(), processor); + xacmlScanner.scan(); + if (!processor.isAttributeValue()) { + if (logger.isInfoEnabled()) + logger.info(urlAttribute + " not found in " + this.xacmlFile.getAbsolutePath()); + return false; + } + + String configsUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_CONFIG_URL); + if (configsUrl == null || configsUrl.isEmpty() || !configsUrl.startsWith("http")) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLRestProperties.PROP_CONFIG_URL + " property is not set."); + } + configsUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + if (configsUrl == null || configsUrl.isEmpty() || !configsUrl.startsWith("http")) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLRestProperties.PROP_PAP_URL + " property is not set."); + } + return false; + } else { + configsUrl = configsUrl.replaceFirst("/pap", ""); + } + } + + if (!configsUrl.endsWith("/")) { + configsUrl += "/"; + } + + String urlXacml = processor.getAttributeValue(); + if (logger.isDebugEnabled()) { + logger.debug("configs url is " + configsUrl + "and url in xacml is " + urlXacml); + } + + if (urlXacml.startsWith("http")) { + // assuming this an unescaped url + } else if (urlXacml.startsWith("$URLConfig/")) { + urlXacml = urlXacml.replace("$URLConfig/", configsUrl); + } else if (urlXacml.startsWith("$URL/")) { + urlXacml = urlXacml.replace("$URL/", configsUrl); + } else{ + if (logger.isWarnEnabled()) { + logger.warn("XACML url is not in the expected format: " + urlXacml); + } + return false; + } + + if (urlXacml.endsWith(".properties")) { + this.bodyType = PolicyBodyType.properties; + } else if (urlXacml.endsWith(".json")) { + this.bodyType = PolicyBodyType.json; + } else if (urlXacml.endsWith(".xml")) { + this.bodyType = PolicyBodyType.xml; + } else if (urlXacml.endsWith(".txt")) { + this.bodyType = PolicyBodyType.txt; + } + + if (logger.isDebugEnabled()) { + logger.debug("converted url from xacml is " + urlXacml + ", body-type is " + this.bodyType); + } + + InputStream inConfigs = null; + try { + URL url = new URL(urlXacml); + URLConnection connection = url.openConnection(); + inConfigs = connection.getInputStream(); + String encoding = connection.getContentEncoding(); + encoding = (encoding == null ? "UTF-8" : encoding); + this.body = IOUtils.toString(inConfigs, encoding); + if (logger.isInfoEnabled()) { + logger.info("The following document of type " + this.bodyType.toString() + + " has been fetched from " + urlXacml + System.lineSeparator() + + this.body); + } + try { + inConfigs.close(); + } catch (IOException e) { + // ignore + logger.warn("Unexpected error closing stream to " + urlXacml, e); + } + return true; + } catch (Exception e) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- XACML url is not in the expected format: " + e.getMessage() + + ": " + urlXacml, e); + } + // continue + } finally { + if (inConfigs != null) { + try { + inConfigs.close(); + } catch (IOException e) { + // ignore + logger.warn("Unexpected error closing stream to " + urlXacml, e); + } + } + } + + // if retrieval through PAP url was not possible, try to retrieve it from + // filesystem instead. + + if (this.body == null || this.body.isEmpty()) { + Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); + if (webappsPath == null) { + logger.error("Invalid Webapps Path Location property : " + + XACMLRestProperties.PROP_PAP_WEBAPPS); + return false; + } + String waPath = webappsPath.toFile().getAbsolutePath(); + + String typeDir = null; + try { + typeDir = Xacml2Elk.toConfigsWebDirectory(this.type); + } catch (IllegalArgumentException iae) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- " + this.type + + " cannot be converted to body-directory: " + iae.getMessage(), + iae); + } + this.bodyType = PolicyBodyType.none; + return false; + } + + String scopePrefix = this.scope.replace('/', '.'); + Path bodyPath = Paths.get(waPath, + typeDir, + scopePrefix + "." + this.type + "_" + + this.name + "." + this.bodyType.name()); + File bodyFile = bodyPath.toFile(); + if (Files.notExists(bodyPath)) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "The following document of type " + this.bodyType.toString() + + " does not exist at filesystem location " + bodyFile.getAbsolutePath()); + } + this.bodyType = PolicyBodyType.none; + return false; + } else { + if (logger.isInfoEnabled()) { + logger.info("The following document of type " + this.bodyType.toString() + + " will be fetched from filesystem location " + bodyFile.getAbsolutePath()); + } + } + + try { + inConfigs = new FileInputStream(bodyFile); + this.body = IOUtils.toString(inConfigs); + inConfigs.close(); + if (logger.isInfoEnabled()) { + logger.info("The document of type " + this.bodyType.toString() + + " has been found at filesystem location " + bodyFile.getAbsolutePath()); + } + } catch (Exception e) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- XACML Body File cannot be read: " + bodyFile.getAbsolutePath(), e); + } + this.bodyType = PolicyBodyType.none; + return false; + } finally { + if (inConfigs != null) { + try { + inConfigs.close(); + } catch (IOException e) { + // ignore + logger.warn("Unexpected error closing stream to " + urlXacml, e); + } + } else { + return false; + } + } + } + return true; + } + + public boolean attachJsonBody(JsonNode jPolicy) { + if (this.body == null) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- JSON Body expected but none provided from " + + this.scope + ":" + this.type + ":" + this.name); + } + return true; + } + + ObjectNode jPolicyRoot = (ObjectNode) jPolicy; + + // verify the json is valid + final ObjectMapper mapper = new ObjectMapper(); + JsonNode jBodyContent; + try { + jBodyContent = mapper.readTree(this.body); + } catch (IOException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- JSON Body is invalid in " + + this.scope + ":" + this.type + ":" + this.name + ":" + + e.getMessage() + System.lineSeparator() + this.body, e); + return false; + } + + String jBodyName = this.type + "_" + "Body"; + ObjectNode jBodyContainer = mapper.createObjectNode(); + jBodyContainer.set(jBodyName, jBodyContent); + + jPolicyRoot.set("Body", jBodyContainer); + + if (logger.isDebugEnabled()) + logger.debug("Attaching JSON to " + + this.scope + ":" + + this.type + ":" + this.name + ":" + + jBodyName + System.lineSeparator() + + jBodyContent); + + return true; + } + + @SuppressWarnings("unchecked") + public boolean attachXmlBody(JsonNode jPolicy) { + if (this.body == null) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- JSON Body expected but none provided from " + + this.scope + ":" + this.type + ":" + this.name); + } + return true; + } + + XmlMapper xmlMapper = new XmlMapper(); + xmlMapper.setConfig(xmlMapper.getSerializationConfig().withRootName("")); + Map<Object, Object> map; + try { + map = xmlMapper.readValue(this.body, Map.class); + } catch (IOException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- XML Body is invalid in " + + this.scope + ":" + this.type + ":" + this.name + ":" + + e.getMessage() + System.lineSeparator() + this.body, e); + return false; + } + + final ObjectMapper mapper = new ObjectMapper(); + String jXmlBody; + try { + jXmlBody = mapper.writeValueAsString(map); + } catch (JsonProcessingException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- Cannot convert XML Body to JSON in " + + this.scope + ":" + this.type + ":" + this.name + ":" + + e.getMessage() + System.lineSeparator() + this.body, e); + return false; + } + + if (logger.isDebugEnabled()) + logger.debug("XML-to-JSON Body conversion: " + this.scope + ":" + + this.type + ":" + this.name +jXmlBody); + + JsonNode jBodyContent; + try { + jBodyContent = mapper.readTree(jXmlBody); + } catch (IOException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- JSON Body (converted from XML) is invalid in " + + this.scope + ":" + this.type + ":" + this.name + ":" + + e.getMessage() + System.lineSeparator() + jXmlBody, e); + return false; + } + + ObjectNode jPolicyRoot = (ObjectNode) jPolicy; + + String jBodyName = this.type + "_" + "Body"; + ObjectNode jBodyContainer = mapper.createObjectNode(); + jBodyContainer.set(jBodyName, jBodyContent); + + jPolicyRoot.set("Body", jBodyContainer); + + + if (logger.isDebugEnabled()) + logger.debug("Attaching JSON to " + + this.scope + ":" + + this.type + ":" + this.name + ":" + + jBodyName + System.lineSeparator() + + jBodyContent); + + return true; + } + + protected boolean attachPropertiesBody(JsonNode jPolicy) { + if (this.body == null) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- JSON Body expected but none provided from " + + this.scope + ":" + this.type + ":" + this.name); + } + return true; + } + + final Properties propBody = new Properties(); + try { + propBody.load(new StringReader(this.body)); + } catch (IOException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- JSON Body is invalid in " + + this.scope + ":" + this.type + ":" + this.name + ":" + + e.getMessage() + System.lineSeparator() + this.body, e); + return false; + } + + if (propBody.isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("Empty set of properties: " + + this.scope + ":" + this.type + ":" + this.name + + System.lineSeparator() + this.body); + } + return true; + } + + + final ObjectMapper mapper = new ObjectMapper(); + + ObjectNode jPolicyRoot = (ObjectNode) jPolicy; + ObjectNode jBody = jPolicyRoot.putObject("Body"); + String jBodyName = this.type + "_" + "Body"; + ObjectNode jBodyContainer = jBody.putObject(jBodyName); + + // ObjectNode jBodyContainer = mapper.createObjectNode(); + + for(String key : propBody.stringPropertyNames()) { + String value = propBody.getProperty(key); + if (logger.isDebugEnabled()) { + logger.debug("Attaching JSON field to " + jBodyName + " for " + + this.type.toString() + ":" + + this.scope + ":" + this.name + ":" + jBodyName + ":" + + " <" + key +"," + value + ">"); + } + jBodyContainer.put(key, propBody.getProperty(key)); + } + + return true; + } + + public boolean attachTextBody(JsonNode jPolicy) { + if (this.body == null) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- JSON Body expected but none provided from " + + this.scope + ":" + this.type + ":" + this.name); + } + return true; + } + + final ObjectMapper mapper = new ObjectMapper(); + StringWriter jsonEscapedTextWriter = new StringWriter(); + try { + mapper.writer().writeValue(jsonEscapedTextWriter, this.body); + } catch (IOException e) { + if (logger.isWarnEnabled()) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "- Text Body cannot be converted from " + + this.scope + ":" + this.type + ":" + this.name + ":" + + e.getMessage() + ":" + jsonEscapedTextWriter , e); + } + return false; + } + String jTextBody = jsonEscapedTextWriter.toString(); + + if (logger.isDebugEnabled()) + logger.debug("XML 2JSON Body conversion: " + this.scope + ":" + + this.type + ":" + this.name + ":" + jTextBody); + + ObjectNode jPolicyRoot = (ObjectNode) jPolicy; + + String jBodyName = this.type + "_" + "Body"; + ObjectNode jBodyContainer = mapper.createObjectNode(); + jBodyContainer.put(jBodyName, jTextBody); + + jPolicyRoot.set("Body", jBodyContainer); + + if (logger.isDebugEnabled()) + logger.debug("Attaching JSON to " + + this.scope + ":" + + this.type + ":" + this.name + ":" + + jBodyName + ":" + + jTextBody); + + return true; + } + + protected boolean attachBody(JsonNode jPolicy) { + if (logger.isTraceEnabled()) logger.trace("ENTER"); + + if (this.bodyType == PolicyBodyType.none) { + if (logger.isInfoEnabled()) + logger.info("No body to attach for policy " + + this.scope + "/" + this.type + "_" + this.name); + + return true; + } + + if (this.body == null || this.body.isEmpty()) { + if (logger.isWarnEnabled()) + logger.warn("No body to attach for policy " + + this.bodyType + this.type + this.scope + this.name); + + return true; + } + + switch (this.bodyType) { + case json: + return attachJsonBody(jPolicy); + case properties: + return attachPropertiesBody(jPolicy); + case xml: + return attachXmlBody(jPolicy); + case txt: + return attachTextBody(jPolicy); + case none: + default: + if (logger.isWarnEnabled()) + logger.warn("Unexpected body type: " + this.bodyType + + this.bodyType + this.type + this.scope + this.name); + return false; + } + } + + public ElkRecord record() throws JAXBException, JsonProcessingException, + IOException, IllegalArgumentException { + if (logger.isTraceEnabled()) logger.trace("ENTER"); + + Marshaller m = jaxbContext.createMarshaller(); + m.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json"); + m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + m.setProperty(MarshallerProperties.JSON_REDUCE_ANY_ARRAYS, true); + m.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, false); + + StringWriter policyStringWriter = new StringWriter(); + m.marshal(policy, policyStringWriter); + + // add metadata to elk record + + final ObjectMapper mapper = new ObjectMapper(); + JsonNode jRoot = mapper.readTree(policyStringWriter.toString()); + JsonNode jPolicy = jRoot.path("Policy"); + if (jPolicy.isMissingNode()) { + logger.warn("Aborting: Policy root node is missing."); + throw new IllegalArgumentException("Missing policy root node"); + } + + ((ObjectNode) jPolicy).put("PolicyType", this.type.toString()); + ((ObjectNode) jPolicy).put("PolicyName", this.name); + ((ObjectNode) jPolicy).put("Owner", this.owner); + ((ObjectNode) jPolicy).put("Scope", this.scope); + + JsonNode jPolicyId = jPolicy.path("PolicyId"); + if (jPolicyId.isMissingNode()) { + logger.warn("Aborting: Policy ID node is missing."); + throw new IllegalArgumentException("Missing policy id"); + } + + if (!jPolicyId.isTextual() || !jPolicyId.isValueNode()) { + logger.warn("Aborting: Policy ID invalid."); + throw new IllegalArgumentException("Invalid policy id"); + } + + String xacmlPolicyId = jPolicyId.asText(); + String policyId = xacmlPolicyId.substring(xacmlPolicyId.lastIndexOf(":")+1); + + boolean success = attachBody(jPolicy); + + mapper.configure(SerializationFeature.INDENT_OUTPUT, true); + mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); + mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false); + mapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true); + + String recordText = mapper.writeValueAsString(jRoot); + if (logger.isDebugEnabled()) { + logger.debug("ELK Record: " + System.lineSeparator() + recordText); + } + + ElkRecord elkRecord = new ElkRecord(policyId, recordText, jRoot, success); + return elkRecord; + } + + public void store(String policyId, String record) throws IOException { + if (logger.isTraceEnabled()) logger.trace("ENTER"); + + if (this.elkDirectory != null) { + Files.createDirectories(this.elkDirectory.toPath());; + Path elkPolicyFile = Paths.get(this.elkDirectory.getPath(), policyId + ".json"); + + if (logger.isDebugEnabled()) { + logger.info("Output: " + elkPolicyFile.toAbsolutePath().toString()); + logger.info("---------------------------------------------------"); + } + + Files.write(elkPolicyFile, record.getBytes()); + } + } + + public static void main(String args[]) + throws JAXBException, IOException, CmdLineException, IllegalStateException { + + CLIOptions cliOptions = new CLIOptions(); + CmdLineParser cliParser= new CmdLineParser(cliOptions); + + try { + cliParser.parseArgument(args); + } catch (CmdLineException e) { + System.err.println("Usage: Xacml2elk"); + cliParser.printUsage(System.err); + throw e; + } + + System.out.println("---------------------------------------------------"); + System.out.println("Converting " + cliOptions.xacmlFile.getName() + " to ELK format"); + System.out.println("Metadata=" + "[type:" + cliOptions.type + + "|name:" + cliOptions.name + + "|owner:" + cliOptions.owner + + "|scope:" + cliOptions.scope + "]"); + + // generate json from jaxb input file + + Path xacmlPath = cliOptions.xacmlFile.toPath(); + if (!Files.isReadable(xacmlPath) || !Files.isRegularFile(xacmlPath)) { + System.out.println("Error: " + xacmlPath + " is invalid."); + throw new IllegalArgumentException("Error: " + xacmlPath + " is invalid."); + } + + + Xacml2Elk convertor = new Xacml2Elk(cliOptions); + ElkRecord elkRecord = convertor.record(); + System.out.println(elkRecord.record); + + Path elkOutDir = cliOptions.elkDirectory.toPath(); + if (!Files.isReadable(elkOutDir) || !Files.isDirectory(elkOutDir) || + !Files.isWritable(elkOutDir) || !Files.isExecutable(elkOutDir)) { + System.out.println("Error: " + elkOutDir.getFileName() + " is invalid."); + throw new IllegalArgumentException("Error: " + elkOutDir.getFileName() + " is invalid."); + } + + convertor.store(elkRecord.policyId, elkRecord.record); + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java new file mode 100644 index 000000000..fd996f444 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java @@ -0,0 +1,531 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.model; + + +import java.awt.Checkbox; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.openecomp.policy.utils.PolicyContainer; +import org.openecomp.policy.utils.PolicyItemSetChangeNotifier; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDP; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; +import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; + +import com.att.research.xacml.api.pap.PAPEngine; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDP; +//import com.att.research.xacml.api.pap.PDP; +//import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.att.research.xacml.api.pap.PDPPolicy; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +public class PDPGroupContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed, PolicyContainer.ItemSetChangeNotifier { + private static final long serialVersionUID = 1L; + private static Logger logger = FlexLogger.getLogger(PDPGroupContainer.class); + + /** + * String identifier of a file's "Id" property. + */ + public static String PROPERTY_ID = "Id"; + + /** + * String identifier of a file's "name" property. + */ + public static String PROPERTY_NAME = "Name"; + + /** + * String identifier of a file's "Description" property. + */ + public static String PROPERTY_DESCRIPTION = "Description"; + + /** + * String identifier of a file's "Default" property. + */ + public static String PROPERTY_DEFAULT = "Default"; + + /** + * String identifier of a file's "icon" property. + */ + public static String PROPERTY_ICON = "Icon"; + + /** + * String identifier of a file's "Status" property. + */ + public static String PROPERTY_STATUS = "Status"; + + /** + * String identifier of a file's "PDPs" property. + */ + public static String PROPERTY_PDPS = "PDPs"; + + /** + * String identifier of a file's "Policies" property. + */ + public static String PROPERTY_POLICIES = "Policies"; + + /** + * String identifier of a file's "PIP Configurations" property. + */ + public static String PROPERTY_PIPCONFIG = "PIP Configurations"; + + /** + * String identifier of a file's "Selected" property. + */ + public static String PROPERTY_SELECTED = "Selected"; + + /** + * List of the string identifiers for the available properties. + */ + public static Collection<String> PDP_PROPERTIES; + + private PAPPolicyEngine papEngine = null; + protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>()); + + public PDPGroupContainer(PAPPolicyEngine papPolicyEngine) { + super(); + this.setContainer(this); + // + // + // + this.papEngine = (PAPPolicyEngine) papPolicyEngine; + // + // + // + this.refreshGroups(); + } + + public boolean isSupported(Object itemId) { + if (itemId instanceof EcompPDPGroup) { + return true; + } + return false; + } + + public synchronized void refreshGroups() { + synchronized(this.groups) { + this.groups.clear(); + try { + this.groups.addAll(this.papEngine.getEcompPDPGroups()); + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + } + logger.info("refreshGroups"); + } + // + // Notify that we have changed + // + this.fireItemSetChange(); + } + + public List<EcompPDPGroup> getGroups() { + return Collections.unmodifiableList(this.groups); + } + + public void makeDefault(EcompPDPGroup group) { + try { + this.papEngine.SetDefaultGroup(group); + } catch (PAPException e) { + String message = "Unable to set Default Group on server: " + e; + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + } + return; + } + + public void removeGroup(EcompPDPGroup group, EcompPDPGroup newGroup) throws PAPException { + if (logger.isTraceEnabled()) { + logger.trace("removeGroup: " + group + " new group for PDPs: " + newGroup); + } + if (group.isDefaultGroup()) { + throw new UnsupportedOperationException("You can't remove the Default Group."); + } + try { + this.papEngine.removeGroup(group, newGroup); + } catch (NullPointerException | PAPException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to removeGroup " + group.getId(), e); + throw new PAPException("Failed to remove group '" + group.getId()+ "'", e); + } + } + + public void removePDP(EcompPDP pdp, EcompPDPGroup group) throws PAPException { + if (logger.isTraceEnabled()) { + logger.trace("removePDP: " + pdp + " from group: " + group); + } + try { + this.papEngine.removePDP(pdp); + } catch (PAPException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to removePDP " + pdp.getId(), e); + throw new PAPException("Failed to remove pdp '" + pdp.getId()+ "'", e); + } + } + + public void updatePDP(EcompPDP pdp) { + try { + papEngine.updatePDP(pdp); + } catch (PAPException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + public void updateGroup(EcompPDPGroup group) { + try { + papEngine.updateGroup(group); + } catch (PAPException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @Override + public Collection<?> getContainerPropertyIds() { + return PDP_PROPERTIES; + } + + @Override + public Collection<?> getItemIds() { + final Collection<Object> items = new ArrayList<Object>(); + items.addAll(this.groups); + if (logger.isTraceEnabled()) { + logger.trace("getItemIds: " + items); + } + return Collections.unmodifiableCollection(items); + } + + @Override + public Class<?> getType(Object propertyId) { + if (propertyId.equals(PROPERTY_ID)) { + return String.class; + } + if (propertyId.equals(PROPERTY_NAME)) { + return String.class; + } + if (propertyId.equals(PROPERTY_DESCRIPTION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_DEFAULT)) { + return Boolean.class; + } + if (propertyId.equals(PROPERTY_STATUS)) { + return String.class; + } + if (propertyId.equals(PROPERTY_PDPS)) { + return Set.class; + } + if (propertyId.equals(PROPERTY_POLICIES)) { + return Set.class; + } + if (propertyId.equals(PROPERTY_PIPCONFIG)) { + return Set.class; + } + if (propertyId.equals(PROPERTY_SELECTED)) { + return Checkbox.class; + } + return null; + } + + @Override + public int size() { + return this.groups.size(); + } + + @Override + public boolean containsId(Object itemId) { + if (logger.isTraceEnabled()) { + logger.trace("containsId: " + itemId); + } + if (this.isSupported(itemId) == false) { + return false; + } + return this.groups.contains(itemId); + } + + @Override + public Object addItem() throws UnsupportedOperationException { + throw new UnsupportedOperationException("PDP Container cannot add a given item."); + } + + public void addNewGroup(String name, String description) throws NullPointerException, PAPException { + if (logger.isTraceEnabled()) { + logger.trace("addNewGroup " + name + " " + description); + } + this.papEngine.newGroup(name, description); + } + + public void addNewPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) throws NullPointerException, PAPException { + if (logger.isTraceEnabled()) { + logger.trace("addNewPDP " + id + " " + name + " " + description + " " + jmxport); + } + this.papEngine.newPDP(id, group, name, description, jmxport); + } + + public void movePDP(EcompPDP pdp, EcompPDPGroup group) { + try { + this.papEngine.movePDP(pdp, group); + } catch (PAPException e) { + String message = "Unable to move PDP to new group on server: " + e; + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + } + return; + } + + @Override + public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot add a container property."); + } + + @Override + public boolean removeContainerProperty(Object propertyId) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot remove a container property."); + } + + @Override + public boolean removeAllItems() throws UnsupportedOperationException { + throw new UnsupportedOperationException("PDP Container cannot remove all items. You must have at least the Default group."); + } + + @Override + public void addItemSetChangeListener(ItemSetChangeListener listener) { + if (getItemSetChangeListeners() == null) { + setItemSetChangeListeners(new LinkedList<PolicyContainer.ItemSetChangeListener>()); + } + getItemSetChangeListeners().add(listener); + } + + @Override + public Object nextItemId(Object itemId) { + if (this.isSupported(itemId) == false) { + return null; + } + int index = this.groups.indexOf(itemId); + if (index == -1) { + // + // We don't know this group + // + return null; + } + // + // Is it the last one? + // + if (index == this.groups.size() - 1) { + // + // Yes + // + return null; + } + // + // Return the next one + // + return this.groups.get(index + 1); + } + + @Override + public Object prevItemId(Object itemId) { + if (this.isSupported(itemId) == false) { + return null; + } + int index = this.groups.indexOf(itemId); + if (index == -1) { + // + // We don't know this group + // + return null; + } + // + // Is it the first one? + // + if (index == 0) { + // + // Yes + // + return null; + } + // + // Return the previous one + // + return this.groups.get(index - 1); + } + + @Override + public Object firstItemId() { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return this.groups.get(0); + } + } + return null; + } + + @Override + public Object lastItemId() { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return this.groups.get(this.groups.size() - 1); + } + } + return null; + } + + @Override + public boolean isFirstId(Object itemId) { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return (this.groups.get(0).equals(itemId)); + } + } + return false; + } + + @Override + public boolean isLastId(Object itemId) { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return (this.groups.get(this.groups.size() - 1).equals(itemId)); + } + } + return false; + } + + @Override + public Object addItemAfter(Object previousItemId) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot addItemAfter, there really is no real ordering."); + } + + @Override + public int indexOfId(Object itemId) { + return this.groups.indexOf(itemId); + } + + @Override + public Object getIdByIndex(int index) { + return this.groups.get(index); + } + + @Override + public List<?> getItemIds(int startIndex, int numberOfItems) { + synchronized (this.groups) { + int endIndex = startIndex + numberOfItems; + if (endIndex > this.groups.size()) { + endIndex = this.groups.size() - 1; + } + return this.groups.subList(startIndex, endIndex); + } + } + + @Override + public Object addItemAt(int index) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot addItemAt"); + } + + @Override + public boolean removeItem(Object itemId) throws UnsupportedOperationException { + if (logger.isTraceEnabled()) { + logger.trace("removeItem: " + itemId); + } + if (this.isSupported(itemId) == false) { + return false; + } + // + // You cannot remove the default group + // + if (((EcompPDPGroup) itemId).getId().equals("Default")) { + throw new UnsupportedOperationException("You can't remove the Default Group."); + } + // + // Remove PDPGroup and move any PDP's in it into the default group + // + try { + this.papEngine.removeGroup((EcompPDPGroup) itemId, this.papEngine.getDefaultGroup()); + return true; + } catch (NullPointerException | PAPException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to remove group", e); + } + return false; + } + + public class PDPGroupItem{ + private final EcompPDPGroup group; + + public PDPGroupItem(EcompPDPGroup itemId) { + this.group = itemId; + } + + public String getId() { + if (logger.isTraceEnabled()) { + logger.trace("getId: " + this.group); + } + return this.group.getId(); + } + + public String getName() { + if (logger.isTraceEnabled()) { + logger.trace("getName: " + this.group); + } + return this.group.getName(); + } + + public String getDescription() { + if (logger.isTraceEnabled()) { + logger.trace("getDescription: " + this.group); + } + return this.group.getDescription(); + } + + public Boolean getDefault() { + if (logger.isTraceEnabled()) { + logger.trace("getDefault: " + this.group); + } + return this.group.isDefaultGroup(); + } + + + public String getStatus() { + return this.group.getStatus().getStatus().toString(); + } + + public Set<PDP> getPDPs() { + return Collections.unmodifiableSet(this.group.getPdps()); + } + + public Set<PDPPolicy> getPolicies() { + if (logger.isTraceEnabled()) { + logger.trace("getPolicies: " + this.group); + } + return this.group.getPolicies(); + } + + public Set<PDPPIPConfig> getPipConfigs() { + if (logger.isTraceEnabled()) { + logger.trace("getPIPConfigs: " + this.group); + } + return this.group.getPipConfigs(); + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java new file mode 100644 index 000000000..bea7915a4 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java @@ -0,0 +1,348 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.model; + + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.openecomp.policy.utils.PolicyContainer; +import org.openecomp.policy.utils.PolicyItemSetChangeNotifier; +import org.openecomp.policy.common.logging.flexlogger.*; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPolicy; +import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed { + private static final long serialVersionUID = 1L; + private static Logger logger = FlexLogger.getLogger(PDPPolicyContainer.class); + + /** + * String identifier of a file's "Id" property. + */ + public static String PROPERTY_ID = "Id"; + + /** + * String identifier of a file's "name" property. + */ + public static String PROPERTY_NAME = "Name"; + + /** + * String identifier of a file's "name" property. + */ + public static String PROPERTY_VERSION = "Version"; + + /** + * String identifier of a file's "Description" property. + */ + public static String PROPERTY_DESCRIPTION = "Description"; + + /** + * String identifier of a file's "IsRoot" property. + */ + public static String PROPERTY_ISROOT = "Root"; + + /** + * List of the string identifiers for the available properties. + */ + public static Collection<String> PDPPOLICY_PROPERTIES; + + private final Object data; + private List<PDPPolicy> policies; + + @SuppressWarnings("unchecked") + public PDPPolicyContainer(Object data) { + super(); + this.data = data; + if (this.data instanceof PDPGroup) { + policies = new ArrayList<PDPPolicy> (((PDPGroup) this.data).getPolicies()); + } + if (this.data instanceof PDP) { + policies = new ArrayList<PDPPolicy> (((PDP) this.data).getPolicies()); + } + if (this.data instanceof Set) { + policies = new ArrayList<PDPPolicy> ((Set<PDPPolicy>)data); + } + if (this.policies == null) { + logger.info("NULL policies"); + throw new NullPointerException("PDPPolicyContainer created with unexpected Object type '" + data.getClass().getName() + "'"); + } + this.setContainer(this); + } + + @Override + public Object nextItemId(Object itemId) { + if (logger.isTraceEnabled()) { + logger.trace("nextItemId: " + itemId); + } + int index = this.policies.indexOf(itemId); + if (index == -1 || ((index + 1) >= this.policies.size())) { + return null; + } + return new PDPPolicyItem(this.policies.get(index + 1)); + } + + @Override + public Object prevItemId(Object itemId) { + if (logger.isTraceEnabled()) { + logger.trace("prevItemId: " + itemId); + } + int index = this.policies.indexOf(itemId); + if (index <= 0) { + return null; + } + return new PDPPolicyItem(this.policies.get(index - 1)); + } + + @Override + public Object firstItemId() { + if (logger.isTraceEnabled()) { + logger.trace("firstItemId: "); + } + if (this.policies.isEmpty()) { + return null; + } + return new PDPPolicyItem(this.policies.get(0)); + } + + @Override + public Object lastItemId() { + if (logger.isTraceEnabled()) { + logger.trace("lastItemid: "); + } + if (this.policies.isEmpty()) { + return null; + } + return new PDPPolicyItem(this.policies.get(this.policies.size() - 1)); + } + + @Override + public boolean isFirstId(Object itemId) { + if (logger.isTraceEnabled()) { + logger.trace("isFirstId: " + itemId); + } + if (this.policies.isEmpty()) { + return false; + } + return (itemId.equals(this.policies.get(0))); + } + + @Override + public boolean isLastId(Object itemId) { + if (logger.isTraceEnabled()) { + logger.trace("isLastId: " + itemId); + } + if (this.policies.isEmpty()) { + return false; + } + return (itemId.equals(this.policies.get(this.policies.size() - 1))); + } + + @Override + public Object addItemAfter(Object previousItemId) + throws UnsupportedOperationException { + return null; + } + + @Override + public Collection<?> getContainerPropertyIds() { + return PDPPOLICY_PROPERTIES; + } + + @Override + public Collection<?> getItemIds() { + final Collection<Object> items = new ArrayList<Object>(); + items.addAll(this.policies); + return Collections.unmodifiableCollection(items); + } + + + @Override + public Class<?> getType(Object propertyId) { + if (propertyId.equals(PROPERTY_ID)) { + return String.class; + } + if (propertyId.equals(PROPERTY_NAME)) { + return String.class; + } + if (propertyId.equals(PROPERTY_VERSION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_DESCRIPTION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_ISROOT)) { + return Boolean.class; + } + return null; + } + + @Override + public int size() { + if (logger.isTraceEnabled()) { + logger.trace("size: " + this.policies.size()); + } + return this.policies.size(); + } + + @Override + public boolean containsId(Object itemId) { + if (logger.isTraceEnabled()) { + logger.trace("containsId: " + itemId); + } + return this.policies.contains(itemId); + } + + @Override + public Object addItem() throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot add an empty policy."); + } + + @Override + public boolean removeItem(Object itemId) + throws UnsupportedOperationException { + if (logger.isTraceEnabled()) { + logger.trace("removeItem: " + itemId); + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + StdPDPPolicy pdpPolicy = null; + try { + pdpPolicy = mapper.readValue(itemId.toString() , StdPDPPolicy.class); + for(int i = 0; i< policies.size(); i++){ + if(policies.get(i).getId().equalsIgnoreCase(pdpPolicy.getId())){ + return this.policies.remove(this.policies.get(i)); + } + } + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Mapping the Removing Policy from PDP Group to Std Policy"+e); + } + return this.policies.remove(itemId); + } + + @Override + public boolean addContainerProperty(Object propertyId, Class<?> type, + Object defaultValue) throws UnsupportedOperationException { + return false; + } + + @Override + public boolean removeContainerProperty(Object propertyId) + throws UnsupportedOperationException { + return false; + } + + @Override + public boolean removeAllItems() throws UnsupportedOperationException { + return false; + } + + @Override + public int indexOfId(Object itemId) { + if (logger.isTraceEnabled()) { + logger.trace("indexOfId: " + itemId); + } + return this.policies.indexOf(itemId); + } + + @Override + public Object getIdByIndex(int index) { + if (logger.isTraceEnabled()) { + logger.trace("getIdByIndex: " + index); + } + return this.policies.get(index); + } + + @Override + public List<?> getItemIds(int startIndex, int numberOfItems) { + if (logger.isTraceEnabled()) { + logger.trace("getItemIds: " + startIndex + " " + numberOfItems); + } + if (numberOfItems < 0) { + throw new IllegalArgumentException(); + } + return this.policies.subList(startIndex, startIndex + numberOfItems); + } + + @Override + public Object addItemAt(int index) throws UnsupportedOperationException { + if (logger.isTraceEnabled()) { + logger.trace("addItemAt: " + index); + } + return null; + } + + public class PDPPolicyItem { + private final PDPPolicy policy; + + public PDPPolicyItem(PDPPolicy itemId) { + this.policy = itemId; + } + + public String getId() { + if (logger.isTraceEnabled()) { + logger.trace("getId: " + this.policy); + } + return this.policy.getId(); + } + + public String getName() { + if (logger.isTraceEnabled()) { + logger.trace("getName: " + this.policy); + } + return this.policy.getName(); + } + + public String getVersion() { + if (logger.isTraceEnabled()) { + logger.trace("getVersion: " + this.policy); + } + return this.policy.getVersion(); + } + + public String getDescription() { + if (logger.isTraceEnabled()) { + logger.trace("getDescription: " + this.policy); + } + return this.policy.getDescription(); + } + + public boolean getRoot() { + if (logger.isTraceEnabled()) { + logger.trace("isRoot: " + this.policy); + } + return this.policy.isRoot(); + } + + public void setRoot(Boolean root) { + ((StdPDPPolicy)this.policy).setRoot(root); + } + + } +}
\ No newline at end of file diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/model/Roles.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/model/Roles.java new file mode 100644 index 000000000..5cad87f41 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/model/Roles.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.model; + + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@Entity +@Table(name="Roles") +@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) +public class Roles implements Serializable{ + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + + @Column(name="id") + private int id; + + private String loginId; + private String name; + private String scope; + private String role; + + public Roles(){ + + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getLoginId() { + return this.loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + + } + public String getScope() { + return this.scope; + } + + public void setScope(String scope) { + this.scope = scope; + + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + public String getRole() { + return this.role; + } + + public void setRole(String role) { + this.role = role; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java new file mode 100644 index 000000000..eafd2196d --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.utils; + + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Map; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +public class ConfigurableRESTUtils { + + protected Logger logger = FlexLogger.getLogger(this.getClass()); + + // + // How the value is returned from the RESTful server + // httpResponseCode means the result is simply the HTTP Response code (e.g. 200, 505, etc.) + // other values identify the encoding used for the string in the body of the HTTP response + // + public enum REST_RESPONSE_FORMAT {httpResponseCode, json } + public enum RESQUEST_METHOD { + GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE; + } + + public String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: "; + + public ConfigurableRESTUtils() { + + } + + + /** + * Call the RESTful API and return a string containing the result. The string may be either a httpResponseCode or json body + * + * @param fullURI + * @param hardCodedHeaders + * @param httpResponseCodes + * @param responseFormat + * @param jsonBody + * @param requestMethod + * @return String + */ + public String sendRESTRequest(String fullURI, Map<String, String> hardCodedHeaderMap, + Map<Integer,String> httpResponseCodeMap, + REST_RESPONSE_FORMAT responseFormat, + String jsonBody, + RESQUEST_METHOD requestMethod ){ + + String responseString = null; + HttpURLConnection connection = null; + try { + + URL url = new URL(fullURI); + + // + // Open up the connection + // + connection = (HttpURLConnection)url.openConnection(); + // + // Setup our method and headers + // + connection.setRequestMethod(requestMethod.toString()); + + connection.setUseCaches(false); + + // add hard-coded headers + for (String headerName : hardCodedHeaderMap.keySet()) { + connection.addRequestProperty(headerName, hardCodedHeaderMap.get(headerName)); + } + + + + if (jsonBody != null){ + connection.setDoInput(true); + connection.setDoOutput(true); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); + out.write(jsonBody); + out.flush(); + out.close(); + } else{ + connection.connect(); + } + + int responseCode = connection.getResponseCode(); + + // check that the response is one we expected (and get the associated value at the same time) + responseString = httpResponseCodeMap.get(responseCode); + if (responseString == null) { + // the response was not configured, meaning it is unexpected and therefore an error + logger.error("Unexpected HTTP response code '" + responseCode + "' from RESTful Server"); + return ERROR_RECEIVED + " code" + responseCode + " from RESTful Server"; + } + + // if the response is contained only in the http code we are done. Otherwise we need to read the body + if (responseFormat == REST_RESPONSE_FORMAT.httpResponseCode) { + return responseString; + } + + // Need to read the body and return that as the responseString. + + responseString = null; + // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) + java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); + scanner.useDelimiter("\\A"); + responseString = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + logger.debug("RESTful body: " + responseString); + return responseString; + + } catch (Exception e) { + logger.error("HTTP Request/Response from RESTFUL server: " + e); + responseString = ERROR_RECEIVED + e; + } finally { + // cleanup the connection + if (connection != null) { + try { + // For some reason trying to get the inputStream from the connection + // throws an exception rather than returning null when the InputStream does not exist. + InputStream is = null; + try { + is = connection.getInputStream(); + } catch (Exception e1) { + // ignore this + } + if (is != null) { + is.close(); + } + + } catch (IOException ex) { + logger.error("Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + return responseString; + + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/PolicyContainer.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/PolicyContainer.java new file mode 100644 index 000000000..fdca336ea --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/PolicyContainer.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.utils; + +import java.io.Serializable; +import java.util.Collection; +import java.util.List; + + +public interface PolicyContainer extends Serializable{ + + public Collection<?> getContainerPropertyIds(); + + public Collection<?> getItemIds(); + + public Class<?> getType(Object propertyId); + + public int size(); + + public boolean containsId(Object itemId); + + public Object addItem() throws UnsupportedOperationException; + + public boolean removeItem(Object itemId) + throws UnsupportedOperationException; + + public boolean addContainerProperty(Object propertyId, Class<?> type, + Object defaultValue) throws UnsupportedOperationException; + + public boolean removeContainerProperty(Object propertyId) + throws UnsupportedOperationException; + + public boolean removeAllItems() throws UnsupportedOperationException; + + public interface Ordered extends PolicyContainer { + + public Object nextItemId(Object itemId); + + public Object prevItemId(Object itemId); + + public Object firstItemId(); + + public Object lastItemId(); + + public boolean isFirstId(Object itemId); + + public boolean isLastId(Object itemId); + + public Object addItemAfter(Object previousItemId) + throws UnsupportedOperationException; + + } + + + public interface Indexed extends Ordered { + + public int indexOfId(Object itemId); + + public Object getIdByIndex(int index); + + public List<?> getItemIds(int startIndex, int numberOfItems); + + public Object addItemAt(int index) throws UnsupportedOperationException; + + public interface ItemAddEvent extends ItemSetChangeEvent { + + public Object getFirstItemId(); + + public int getFirstIndex(); + + public int getAddedItemsCount(); + } + + + public interface ItemRemoveEvent extends ItemSetChangeEvent { + + public Object getFirstItemId(); + + public int getFirstIndex(); + + public int getRemovedItemsCount(); + } + } + + public interface ItemSetChangeEvent extends Serializable { + + public PolicyContainer getContainer(); + } + + public interface ItemSetChangeListener extends Serializable { + + public void containerItemSetChange(PolicyContainer.ItemSetChangeEvent event); + } + + public interface ItemSetChangeNotifier extends Serializable { + + public void addItemSetChangeListener( + PolicyContainer.ItemSetChangeListener listener); + + public void removeItemSetChangeListener( + PolicyContainer.ItemSetChangeListener listener); + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java new file mode 100644 index 000000000..934c30564 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.utils; + + +import java.io.Serializable; +import java.util.Collection; +import java.util.EventObject; +import java.util.LinkedList; + +import org.openecomp.policy.utils.PolicyContainer.ItemSetChangeEvent; +import org.openecomp.policy.utils.PolicyContainer.ItemSetChangeListener; + + + +public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChangeNotifier { + private static final long serialVersionUID = 1L; + private Collection<PolicyContainer.ItemSetChangeListener> itemSetChangeListeners = null; + private PolicyContainer container = null; + + public PolicyItemSetChangeNotifier() { + } + + protected void setContainer(PolicyContainer c) { + this.container = c; + } + + @Override + public void addItemSetChangeListener(ItemSetChangeListener listener) { + if (getItemSetChangeListeners() == null) { + setItemSetChangeListeners(new LinkedList<PolicyContainer.ItemSetChangeListener>()); + } + getItemSetChangeListeners().add(listener); } + + @Override + public void removeItemSetChangeListener(ItemSetChangeListener listener) { + if (getItemSetChangeListeners() != null) { + getItemSetChangeListeners().remove(listener); + } + } + + protected static class BaseItemSetChangeEvent extends EventObject implements + PolicyContainer.ItemSetChangeEvent, Serializable { + private static final long serialVersionUID = 1L; + + protected BaseItemSetChangeEvent(PolicyContainer source) { + super(source); + } + + @Override + public PolicyContainer getContainer() { + return (PolicyContainer) getSource(); + } + } + + protected void setItemSetChangeListeners( + Collection<PolicyContainer.ItemSetChangeListener> itemSetChangeListeners) { + this.itemSetChangeListeners = itemSetChangeListeners; + } + protected Collection<PolicyContainer.ItemSetChangeListener> getItemSetChangeListeners() { + return itemSetChangeListeners; + } + + protected void fireItemSetChange() { + fireItemSetChange(new BaseItemSetChangeEvent(this.container)); + } + + protected void fireItemSetChange(ItemSetChangeEvent event) { + if (getItemSetChangeListeners() != null) { + final Object[] l = getItemSetChangeListeners().toArray(); + for (int i = 0; i < l.length; i++) { + ((PolicyContainer.ItemSetChangeListener) l[i]) + .containerItemSetChange(event); + } + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java new file mode 100644 index 000000000..20bfa1a50 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java @@ -0,0 +1,494 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.utils; + + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryNotEmptyException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; +import java.util.UUID; + +import org.openecomp.policy.rest.XACMLRestProperties; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyWriter; +import com.att.research.xacml.util.XACMLProperties; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +/** + * Helper static class that wraps XACMLPolicyWriter + * + * + */ +public class XACMLPolicyWriterWithPapNotify{ + private static final Logger logger = FlexLogger.getLogger(XACMLPolicyWriterWithPapNotify.class); + + /** + * Helper static class that does the work to write a policy set to a file on disk and notify PAP + * + * + */ + public static Path writePolicyFile(Path filename, PolicySetType policySet) { + if(logger.isDebugEnabled()){ + logger.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet)" + + "\nfilename = " + filename + + "\npolicySet = " + policySet); + } + //write to file + Path path = XACMLPolicyWriter.writePolicyFile(filename, policySet); + + if(path!=null){ + //write to DB + if(notifyPapOfCreateUpdate(filename.toAbsolutePath().toString())){ + return path; + }else{ + //write to DB failed. So, delete the file + try{ + Files.deleteIfExists(path); + }catch(DirectoryNotEmptyException e){ + //We are trying to delete a directory and it is not empty + logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nDirectoryNotEmptyException for path = " + path + + "\nException message = " + e); + }catch(IOException e) { + // File permission problems are caught here. + logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nIOException for path = " + path + + "\nException message = " + e); + }catch(Exception e){ + logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nException for path = " + path + + "\nException message = " + e); + } + return null; + } + + }else{ + return null; + } + } + + /** + * Helper static class that does the work to write a policy set to an output stream and notify PAP + * + * + */ + public static void writePolicyFile(OutputStream os, PolicySetType policySet) { + if(logger.isDebugEnabled()){ + logger.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(OutputStream os, PolicySetType policySet)" + + "\nos = " + os + + "\npolicySet = " + policySet); + } + //Only used for writing a byte array output stream for a message. No file is written + XACMLPolicyWriter.writePolicyFile(os, policySet); + } + + /** + * Helper static class that does the work to write a policy to a file on disk. + * + * + */ + public static Path writePolicyFile(Path filename, PolicyType policy) { + if(logger.isDebugEnabled()){ + logger.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicyType policy)" + + "\nfilename = " + filename + + "\npolicy = " + policy); + } + + //write to file + Path path = XACMLPolicyWriter.writePolicyFile(filename, policy); + + if(path!=null){ + //write to DB + if(notifyPapOfCreateUpdate(filename.toAbsolutePath().toString())){ + return path; + }else{ + //write to DB failed so delete the file + try{ + Files.deleteIfExists(path); + }catch(DirectoryNotEmptyException e){ + //We are trying to delete a directory and it is not empty + logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet)Files.deleteIfExists(path) :" + + "\nDirectoryNotEmptyException for path = " + path + + "\nException message = " + e); + }catch(IOException e) { + // File permission problems are caught here. + logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nIOException for path = " + path + + "\nException message = " + e); + }catch(Exception e){ + logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nException for path = " + path + + "\nException message = " + e); + } + return null; + } + + }else{ + return null; + } + } + + + /** + * Helper static class that does the work to write a policy to a file on disk. + * + * + */ + public static InputStream getXmlAsInputStream(PolicyType policy) { + if(logger.isDebugEnabled()){ + logger.debug("\nXACMLPolicyWriterWithPapNotify.getXmlAsInputStream(PolicyType policy)" + + "\npolicy = " + policy); + } + return XACMLPolicyWriter.getXmlAsInputStream(policy); + } + /** + * Helper static class that does the work to write a policy set to an output stream. + * + * + */ + public static void writePolicyFile(OutputStream os, PolicyType policy) { + if(logger.isDebugEnabled()){ + logger.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(OutputStream os, PolicyType policy)" + + "\nos = " + os + + "\npolicy = " + policy); + } + //There are no references to this and if there were, it would most likely be used in an http message + XACMLPolicyWriter.writePolicyFile(os, policy); + } + + public static String changeFileNameInXmlWhenRenamePolicy(Path filename) { + if(logger.isDebugEnabled()){ + logger.debug("\nXACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(Path filename)" + + "\nfilename = " + filename); + } + return XACMLPolicyWriter.changeFileNameInXmlWhenRenamePolicy(filename); + } + + public static boolean notifyPapOfPolicyRename(String oldPolicyName, String newPolicyName){ + if(logger.isDebugEnabled()){ + logger.debug("\nXACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(String policyToCreateUpdate) " + + "\npolicyToCreateUpdate = " + " "); + } + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + UUID requestID = UUID.randomUUID(); + //loggingContext.setRequestID(requestID.toString()); + //loggingContext.transactionStarted(); + URL url; + try { + url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)+"?oldPolicyName="+ URLEncoder.encode(oldPolicyName, "UTF-8")+"&newPolicyName="+URLEncoder.encode(newPolicyName,"UTF-8")); + if(logger.isDebugEnabled()){ + logger.debug("\nnotifyPapOfCreateUpdate: URL = " + url); + } + } catch (MalformedURLException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nMalformedURLException message = " + e); + + return false; + } catch (UnsupportedEncodingException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nUnsupportedEncodingException message = " + e); + + return false; + } + // + // Open up the connection + // + try { + connection = (HttpURLConnection)url.openConnection(); + } catch (IOException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nurl.openConnection() IOException message = " + e); + return false; + } + // + // Setup our method and headers + // + try { + connection.setRequestMethod("PUT"); + } catch (ProtocolException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.setRequestMethod(PUT) ProtocolException message = " + e); + connection.disconnect(); + return false; + } + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("requestID", requestID.toString()); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + try { + connection.connect(); + } catch (IOException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.connect() IOException message = " + e); + connection.disconnect(); + return false; + } + try { + int responseCode = connection.getResponseCode(); + if(logger.isDebugEnabled()){ + logger.debug("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() = " + responseCode); + } + if (responseCode == 200) { + connection.disconnect(); + return true; + } else { + connection.disconnect(); + return false; + //System.out.println(connection.getResponseMessage()); + //System.out.println(connection.getResponseCode()); + //System.out.println(connection.g); + } + } catch (IOException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() IOException message = " + e); + connection.disconnect(); + return false; + } + } + + public static boolean notifyPapOfDelete(String policyToDelete){ + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + UUID requestID = UUID.randomUUID(); + //loggingContext.setRequestID(requestID.toString()); + //loggingContext.transactionStarted(); + String papUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + if(papUrl == null){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "PAP url property does not exist"); + return false; + } + String urlString = ""; + try{ + urlString = papUrl+"?groupId=0&isDeleteNotify=1&policyToDelete="+ URLEncoder.encode(policyToDelete, "UTF-8"); + } catch(UnsupportedEncodingException e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Invalid encoding: UTF-8", e); + return false; + } + URL url; + try { + url = new URL(urlString); + } catch (MalformedURLException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error parsing PAP url: " + + urlString + , e); + return false; + } + // + // Open up the connection + // + try { + connection = (HttpURLConnection)url.openConnection(); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error opening HttpURLConnection to: " + + url.toString() + , e); + return false; + } + // + // Setup our method and headers + // + try { + connection.setRequestMethod("DELETE"); + } catch (ProtocolException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Invalid request method: DELETE", e); + connection.disconnect(); + return false; + } + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("requestID", requestID.toString()); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + try { + connection.connect(); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error connecting HttpURLConnection to: " + + connection.getURL().toString() + , e); + connection.disconnect(); + return false; + } + try { + if (connection.getResponseCode() == 200) { + connection.disconnect(); + //worked + return true; + } else { + connection.disconnect(); + return false; + //System.out.println(connection.getResponseMessage()); + //System.out.println(connection.getResponseCode()); + //System.out.println(connection.g); + } + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error getting HttpUrlConnection response code for: " + + connection.getURL().toString() + , e); + connection.disconnect(); + return false; + } + } + + public static boolean notifyPapOfCreateUpdate(String policyToCreateUpdate){ + if(logger.isDebugEnabled()){ + logger.debug("\nXACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(String policyToCreateUpdate) " + + "\npolicyToCreateUpdate = " + policyToCreateUpdate); + } + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + UUID requestID = UUID.randomUUID(); + //loggingContext.setRequestID(requestID.toString()); + //loggingContext.transactionStarted(); + URL url; + try { + url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)+"?policyToCreateUpdate="+ URLEncoder.encode(policyToCreateUpdate, "UTF-8")); + if(logger.isDebugEnabled()){ + logger.debug("\nnotifyPapOfCreateUpdate: URL = " + url); + } + } catch (MalformedURLException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nMalformedURLException message = " + e); + + return false; + } catch (UnsupportedEncodingException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nUnsupportedEncodingException message = " + e); + + return false; + } + // + // Open up the connection + // + try { + connection = (HttpURLConnection)url.openConnection(); + } catch (IOException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nurl.openConnection() IOException message = " + e); + return false; + } + // + // Setup our method and headers + // + try { + connection.setRequestMethod("PUT"); + } catch (ProtocolException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.setRequestMethod(PUT) ProtocolException message = " + e); + connection.disconnect(); + return false; + } + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("requestID", requestID.toString()); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + try { + connection.connect(); + } catch (IOException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.connect() IOException message = " + e); + connection.disconnect(); + return false; + } + try { + int responseCode = connection.getResponseCode(); + if(logger.isDebugEnabled()){ + logger.debug("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() = " + responseCode); + } + if (responseCode == 200) { + connection.disconnect(); + return true; + } else { + connection.disconnect(); + return false; + //System.out.println(connection.getResponseMessage()); + //System.out.println(connection.getResponseCode()); + //System.out.println(connection.g); + } + } catch (IOException e) { + logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() IOException message = " + e); + connection.disconnect(); + return false; + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java new file mode 100644 index 000000000..ff9f0f1ab --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java @@ -0,0 +1,188 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.conf; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.portalapp.scheduler.RegistryAdapter; +import org.openecomp.portalapp.uebhandler.InitUebHandler; +import org.openecomp.portalapp.uebhandler.MainUebHandler; +import org.openecomp.portalapp.uebhandler.WidgetNotificationHandler; +import org.openecomp.portalsdk.core.conf.AppConfig; +import org.openecomp.portalsdk.core.conf.Configurable; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.CacheManager; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Profile; +import org.springframework.context.annotation.PropertySource; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; + +/** + * Configures Spring features in the ECOMP Portal SDK sample application. + * Subclasses the ECOMP Portal SDK core AppConfig class to reuse interceptors, + * view resolvers and other features defined there. + */ +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "org.openecomp") +@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/app/test.properties" }, ignoreResourceNotFound = true) +@Profile("src") +@EnableAsync +@EnableScheduling +public class ExternalAppConfig extends AppConfig implements Configurable { + + private RegistryAdapter schedulerRegistryAdapter; + + @Configuration + @Import(SystemProperties.class) + static class InnerConfiguration { + } + + /** + * @see org.openecomp.portalsdk.core.conf.AppConfig#viewResolver() + */ + public ViewResolver viewResolver() { + return super.viewResolver(); + } + + /** + * @see org.openecomp.portalsdk.core.conf.AppConfig#addResourceHandlers(ResourceHandlerRegistry) + * + * @param registry + */ + public void addResourceHandlers(ResourceHandlerRegistry registry) { + super.addResourceHandlers(registry); + } + + /** + * @see org.openecomp.portalsdk.core.conf.AppConfig#dataAccessService() + */ + public DataAccessService dataAccessService() { + return super.dataAccessService(); + } + + /** + * Creates a new list with a single entry that is the external app + * definitions.xml path. + * + * @return List of String, size 1 + */ + public List<String> addTileDefinitions() { + List<String> definitions = new ArrayList<String>(); + definitions.add("/WEB-INF/defs/definitions.xml"); + return definitions; + } + + /** + * Adds request interceptors to the specified registry by calling + * {@link AppConfig#addInterceptors(InterceptorRegistry)}, but excludes + * certain paths from the session timeout interceptor. + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + super.setExcludeUrlPathsForSessionTimeout("/login_external", "*/login_external.htm", "login", "/login.htm", + "/api*","/single_signon.htm","/single_signon"); + super.addInterceptors(registry); + } + + /** + * Creates and returns a new instance of a {@link CacheManager} class. + * + * @return New instance of {@link CacheManager} + */ + @Bean + public AbstractCacheManager cacheManager() { + return new CacheManager(); + } + + /** + * Creates and returns a new instance of a {@link MainUebHandler}. + * + * @return New instance of {@link MainUebHandler}. + */ + @Bean + public MainUebHandler mainUebHandler() { + + return new MainUebHandler(); + } + + /** + * Creates and returns a new instance of a {@link InitUebHandler}. + * + * @return New instance of {@link InitUebHandler}. + */ + @Bean + public InitUebHandler initUebHandler() { + + return new InitUebHandler(); + } + + /** + * Creates and returns a new instance of a {@link WidgetNotificationHandler} + * . + * + * @return New instance of {@link WidgetNotificationHandler}. + */ + @Bean + public WidgetNotificationHandler widgetNotificationHandler() { + return new WidgetNotificationHandler(); + } + + /** + * Creates and returns a new instance of a {@link SchedulerFactoryBean} and + * populates it with triggers. + * + * @return New instance of {@link SchedulerFactoryBean} + * @throws Exception + */ + // @Bean // ANNOTATION COMMENTED OUT + // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION + public SchedulerFactoryBean schedulerFactoryBean() throws Exception { + SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); + scheduler.setTriggers(schedulerRegistryAdapter.getTriggers()); + scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties")); + scheduler.setDataSource(dataSource()); + return scheduler; + } + + + /** + * Sets the scheduler registry adapter. + * + * @param schedulerRegistryAdapter + */ + @Autowired + public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) { + this.schedulerRegistryAdapter = schedulerRegistryAdapter; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java new file mode 100644 index 000000000..dfdfcadec --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java @@ -0,0 +1,60 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.conf; + +import java.util.Arrays; + +import org.openecomp.portalsdk.core.conf.AppInitializer; + +public class ExternalAppInitializer extends AppInitializer{ + + + @Override + protected Class<?>[] getRootConfigClasses() { + return super.getRootConfigClasses(); + } + + @Override + protected Class<?>[] getServletConfigClasses() { +// Class<?>[] configClasses = super.getServletConfigClasses(); +// Class<?>[] additionalConfigClasses = Arrays.copyOf(configClasses, configClasses.length); +// addConfigClass(additionalConfigClasses, ExternalAppConfig.class); +// return additionalConfigClasses; +// + return new Class[] {ExternalAppConfig.class}; + } + + static Class<?>[] addConfigClass(Class<?>[] a, Class<?> e) { + a = Arrays.copyOf(a, a.length + 1); + a[a.length - 1] = e; + return a; + } + + /* + * URL request will direct to the Spring dispatcher for processing + */ + @Override + protected String[] getServletMappings() { + return super.getServletMappings(); + } + +} + + diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java new file mode 100644 index 000000000..3e1d89d25 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java @@ -0,0 +1,37 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.conf; + +import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +@Component +@Profile("src") +public class HibernateMappingLocations implements HibernateMappingLocatable { + + public Resource[] getMappingLocations() { + return new Resource[]{new ClassPathResource("../fusion/orm/Fusion.hbm.xml"), new ClassPathResource("../fusion/orm/Workflow.hbm.xml"), new ClassPathResource("../fusion/orm/RNoteBookIntegration.hbm.xml")}; + } + + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/AngularSinglePageController.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/AngularSinglePageController.java new file mode 100644 index 000000000..e654a51c0 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/AngularSinglePageController.java @@ -0,0 +1,48 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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 for a single-page application sample. The view is restricted to + * authenticated users. The named view resolves to page singlePageSample.html, + * which uses Angular. + */ +@Controller +@RequestMapping("/") +public class AngularSinglePageController extends RestrictedBaseController { + + @RequestMapping(value = { "/singlePageSample" }, method = RequestMethod.GET) + public ModelAndView view(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + return new ModelAndView("single_page_sample", "model", model); + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/CallflowController.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/CallflowController.java new file mode 100644 index 000000000..a3d1be5f0 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/CallflowController.java @@ -0,0 +1,44 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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 for a message sequence chart view. The view is restricted to + * authenticated users. The view name defaults to the request name with no + * suffix, "callflow", which resolves to page details.jsp. That page is an + * iframe around page details.html. + */ +@Controller +@RequestMapping("/") +public class CallflowController extends RestrictedBaseController { + + @RequestMapping(value = { "/callflow" }, method = RequestMethod.GET) + public ModelAndView plot() { + final String defaultViewName = null; + return new ModelAndView(defaultViewName); + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/ElasticSearchController.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/ElasticSearchController.java new file mode 100644 index 000000000..69ff63db6 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/ElasticSearchController.java @@ -0,0 +1,128 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.io.IOException; + +import org.json.JSONObject; +import org.openecomp.portalapp.model.Result; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; + +import io.searchbox.client.JestClient; +import io.searchbox.client.JestClientFactory; +import io.searchbox.client.config.HttpClientConfig; +import io.searchbox.core.Search; +import io.searchbox.core.SearchResult; +import io.searchbox.core.Suggest; +import io.searchbox.core.SuggestResult; +import io.searchbox.params.Parameters; + +/** + * Controller for views that demonstrate Elastic Search features. + */ +@RestController +public class ElasticSearchController extends RestrictedBaseController{ + + @RequestMapping(value = {"/es_search_demo" }, method = RequestMethod.GET) + public ModelAndView search() { + return new ModelAndView("es_search_demo"); + } + + @RequestMapping(value = {"/es_suggest_demo" }, method = RequestMethod.GET) + public ModelAndView suggest() { + return new ModelAndView("es_suggest_demo"); + } + + @RequestMapping(value="/es_suggest/{task}",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity<Result> doSuggest(@PathVariable("task") String task) throws IOException { + JSONObject obj = new JSONObject(task); + String searchTerm = obj.getString("data"); + String searchSize = obj.getString("size"); + String searchFuzzy = obj.getString("fuzzy"); + String resultName = obj.getString("resultname"); + + JestClientFactory factory = new JestClientFactory(); + factory.setHttpClientConfig(new HttpClientConfig + .Builder("http://todo_elastic_search_server") + .multiThreaded(true) + .build()); + JestClient client = factory.getObject(); + + + Suggest suggest = new Suggest.Builder("{\n" + +"\"" + resultName +"\" : {\n" + +"\"text\" : \""+ searchTerm +"\",\n" + +"\"completion\" : {\n" + +"\"field\" : \"suggest\",\n" + +"\"size\" : " + searchSize + ",\n" + +"\"fuzzy\" : \"" + searchFuzzy + "\"\n" + +"}\n" + +"}\n" + +"}").addIndex("customer").build(); + + SuggestResult result = client.execute(suggest); + System.err.println(result.getJsonObject().toString()); + return new ResponseEntity<Result>(new Result(result.getJsonObject().toString()),HttpStatus.OK); + } + + @RequestMapping(value="/es_search/{task}",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity<Result> doSearch(@PathVariable("task") String task) throws IOException { + JSONObject obj = new JSONObject(task); + String searchTerm = obj.getString("data"); + String searchSize = obj.getString("size"); + // String searchFuzzy = obj.getString("fuzzy"); + + JestClientFactory factory = new JestClientFactory(); + factory.setHttpClientConfig(new HttpClientConfig + .Builder("http://todo_elastic_search_server") + .multiThreaded(true) + .build()); + JestClient client = factory.getObject(); + + Search search = new Search.Builder("{\n" + +"\"query\" : {\n" + +"\"query_string\" : {\n" + +"\"query\" : \"name:"+ searchTerm +"\"\n" + +"}\n" + +"}\n" + +"}").addIndex("customer").setParameter(Parameters.SIZE,Integer.valueOf(searchSize)).build(); + + SearchResult result = client.execute(search); + System.err.println(result.getJsonObject().toString()); + return new ResponseEntity<Result>(new Result(result.getJsonObject().toString()),HttpStatus.OK); + } + + public ResponseEntity<Result> sendResult(Result result) { + return new ResponseEntity<Result>(result, HttpStatus.OK); + } + + @Override + public boolean isRESTfulCall() { + return true; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/LeafletMapContoller.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/LeafletMapContoller.java new file mode 100644 index 000000000..4c603fe19 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/LeafletMapContoller.java @@ -0,0 +1,43 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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 for geographic map view. The view is restricted to authenticated + * users. The view name defaults to the request name with no suffix, + * "leafletMap", which resolves to page leafletMap.jsp. + */ +@Controller +@RequestMapping("/") +public class LeafletMapContoller extends RestrictedBaseController { + + @RequestMapping(value = { "/leafletMap" }, method = RequestMethod.GET) + public ModelAndView plot() { + final String defaultViewName = null; + return new ModelAndView(defaultViewName); + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/PostDroolsController.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/PostDroolsController.java new file mode 100644 index 000000000..2729e8731 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/PostDroolsController.java @@ -0,0 +1,138 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.command.PostDroolsBean; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.service.PostDroolsService; +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 PostDroolsController extends RestrictedBaseController{ + + @Autowired + private PostDroolsService postDroolsService; + + @RequestMapping(value = {"/drools" }, method = RequestMethod.GET) + public ModelAndView drools(HttpServletRequest request) { + + return new ModelAndView(getViewName()); + } + + + @RequestMapping(value = {"/getDrools" }, method = RequestMethod.GET) + public void getDrools(HttpServletRequest request, HttpServletResponse response) { + // Map<String, Object> model = new HashMap<String, Object>(); + + ObjectMapper mapper = new ObjectMapper(); + try { + List<PostDroolsBean> beanList = postDroolsService.fetchDroolBeans(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(beanList)); + 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(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @RequestMapping(value = {"/getDroolDetails" }, method = RequestMethod.GET) + public void getDroolDetails(HttpServletRequest request, HttpServletResponse response) { + + ObjectMapper mapper = new ObjectMapper(); + try { + + PostDroolsBean postDroolsBean = new PostDroolsBean(); + String selectedFile = request.getParameter("selectedFile"); + postDroolsBean.setDroolsFile(selectedFile);//sample populated + //postDroolsBean.setSelectedRules("[\"NJ\",\"NY\",\"KY\"]"); + postDroolsBean.setClassName(postDroolsService.retrieveClass(selectedFile)); + + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(postDroolsBean)); + 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(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @RequestMapping(value = {"/post_drools/execute" }, 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()); + PostDroolsBean postDroolsBean = mapper.readValue(root.get("postDroolsBean").toString(), PostDroolsBean.class); + + String resultsString = postDroolsService.execute(postDroolsBean.getDroolsFile(), postDroolsBean.getClassName(), postDroolsBean.getSelectedRules()); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + //String responseString = mapper.writeValueAsString(resultsString); + JSONObject j = new JSONObject("{resultsString: "+resultsString+"}"); + + out.write(j.toString()); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } + + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/UserProfileController.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/UserProfileController.java new file mode 100644 index 000000000..2f4ea93de --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/UserProfileController.java @@ -0,0 +1,72 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.domain.Profile; +import org.openecomp.portalsdk.core.service.ProfileService; +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.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Controller for user profile view. The view is restricted to authenticated + * users. The view name resolves to page user_profile.jsp which uses Angular. + */ + +@Controller +@RequestMapping("/") +public class UserProfileController extends RestrictedBaseController { + + @Autowired + ProfileService service; + + @RequestMapping(value = { "/user_profile" }, method = RequestMethod.GET) + public ModelAndView ProfileSearch(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + List<Profile> profileList = service.findAll(); + try { + model.put("customerInfo", mapper.writeValueAsString(profileList)); + } catch (JsonGenerationException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return new ModelAndView("user_profile", "model", model); + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/WelcomeController.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/WelcomeController.java new file mode 100644 index 000000000..06853f0e3 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/controller/WelcomeController.java @@ -0,0 +1,43 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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 for welcome view. The view is restricted to authenticated users. + * The view name defaults to the request name with no suffix, "welcome", which + * resolves to page welcome.jsp. + */ +@Controller +@RequestMapping("/") +public class WelcomeController extends RestrictedBaseController { + @RequestMapping(value = { "/welcome" }, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { + final String defaultViewName = null; + return new ModelAndView(defaultViewName); + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/model/Result.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/model/Result.java new file mode 100644 index 000000000..5e09cb2cc --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/model/Result.java @@ -0,0 +1,37 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.model; + +public class Result { + private String result; + + public Result(String result) { + this.result = result; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java new file mode 100644 index 000000000..b308efbb2 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java @@ -0,0 +1,47 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import org.openecomp.portalapp.conf.ExternalAppConfig; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.quartz.DisallowConcurrentExecution; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.PersistJobDataAfterExecution; +import org.springframework.scheduling.quartz.QuartzJobBean; + +@PersistJobDataAfterExecution +@DisallowConcurrentExecution +public class LogJob extends QuartzJobBean { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class); + + + @Override + protected void executeInternal(JobExecutionContext ctx) + throws JobExecutionException { + // JobDataMap dataMap = ctx.getJobDetail().getJobDataMap(); + //int cnt = dataMap.getInt(""); + // JobKey jobKey = ctx.getJobDetail().getKey(); + logger.info(EELFLoggerDelegate.debugLogger, (Runtime.getRuntime().maxMemory() + " " + Runtime.getRuntime().maxMemory())); + + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java new file mode 100644 index 000000000..dce9e26bf --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java @@ -0,0 +1,57 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.portalsdk.core.scheduler.CronRegistry; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.context.annotation.DependsOn; +import org.springframework.scheduling.quartz.CronTriggerFactoryBean; +import org.springframework.scheduling.quartz.JobDetailFactoryBean; +import org.springframework.stereotype.Component; + +@Component +@DependsOn({ "systemProperties" }) +public class LogRegistry extends CronRegistry { + + private static final String groupName = "AppGroup"; + private static final String jobName = "LogJob"; + private static final String triggerName = "LogTrigger"; + + // @Autowired + // private SystemProperties systemProperties; + + // @Bean + public JobDetailFactoryBean jobDetailFactoryBean() { + Map<String, Object> map = new HashMap<String, Object>(); + map.put("units", "bytes"); + return jobDetailFactoryBean(groupName, jobName, LogJob.class, map); + } + + // @Bean + public CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException { + // "0 * * * * ? * + return cronTriggerFactoryBean(groupName, triggerName, SystemProperties.getProperty(SystemProperties.LOG_CRON)); + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/Register.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/Register.java new file mode 100644 index 000000000..3a29520ec --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/Register.java @@ -0,0 +1,82 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.scheduler.Registerable; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.quartz.Trigger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.DependsOn; +import org.springframework.stereotype.Component; + +@Component +@DependsOn({"logRegistry", "systemProperties"}) +public class Register implements Registerable { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Register.class); + + + private List<Trigger> scheduleTriggers = new ArrayList<Trigger>(); + Trigger trigger[] = new Trigger[1]; + + + @Autowired + private LogRegistry logRegistry; + + + + @Override + public Trigger[] getTriggers() { + return getScheduleTriggers().toArray(trigger); + } + + @Override + public void registerTriggers() { + // 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(SystemProperties.LOG_CRON) != null) + getScheduleTriggers().add(logRegistry.getTrigger()); + + } catch(IllegalStateException ies) { + logger.info(EELFLoggerDelegate.debugLogger, ("Log Cron not available")); + } + + + } + + + public List<Trigger> getScheduleTriggers() { + return scheduleTriggers; + } + + public void setScheduleTriggers(List<Trigger> scheduleTriggers) { + this.scheduleTriggers = scheduleTriggers; + } + + + + + + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java new file mode 100644 index 000000000..1bc43fee6 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java @@ -0,0 +1,108 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.openecomp.portalsdk.core.scheduler.Registerable; +import org.openecomp.portalsdk.workflow.services.WorkflowScheduleService; +import org.quartz.Trigger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.springframework.stereotype.Component; + +/** + * TODO REFACTOR + * moved from org.openecomp.portalsdk.core.scheduler + * to org.openecomp.portalapp.scheduler + * + */ +@Component +public class RegistryAdapter { + + @Autowired + private Registerable registry; + + @Autowired + private WorkflowScheduleService workflowScheduleService; + + private SchedulerFactoryBean schedulerBean; + + Trigger trigger[] = new Trigger[1]; + + public Trigger[] getTriggers() { + + registry.registerTriggers(); + + List<Trigger> allTriggers = new ArrayList<Trigger>(); + + List<Trigger> coreTriggers = addCoreTriggers(); + final Trigger[] extTriggerArray = registry.getTriggers(); + + allTriggers.addAll(Arrays.asList(extTriggerArray)); + allTriggers.addAll(coreTriggers); + + return allTriggers.toArray(trigger); + + + } + + + public List<Trigger> addCoreTriggers() { + //On startup of the application after crash recovery, invoke workflow schedule trigger + List<Trigger> triggers = getWorkflowScheduleService().triggerWorkflowScheduling(); + return triggers; + } + + + public void setSchedulerBean(SchedulerFactoryBean _schedulerBean) { + schedulerBean = _schedulerBean; + + } + + public SchedulerFactoryBean getSchedulerBean() { + return schedulerBean; + + } + + + public Registerable getRegistry() { + return registry; + } + + + public void setRegistry(Registerable registry) { + this.registry = registry; + } + + + public WorkflowScheduleService getWorkflowScheduleService() { + return workflowScheduleService; + } + + + public void setWorkflowScheduleService( + WorkflowScheduleService workflowScheduleService) { + this.workflowScheduleService = workflowScheduleService; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java new file mode 100644 index 000000000..1b9e020c5 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.service; + + +import org.openecomp.policy.dao.RolesDao; +import org.openecomp.policy.model.Roles; +import org.openecomp.policy.rest.dao.UserInfoDao; +import org.openecomp.policy.rest.jpa.UserInfo; +import org.openecomp.portalsdk.core.domain.Role; +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; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Service("adminAuthExtension") +@Transactional +public class AdminAuthExtension { + + @Autowired + RolesDao rolesDAO; + + @Autowired + UserInfoDao userInfoDao; + + private static Logger logger = FlexLogger.getLogger(AdminAuthExtension.class); + public void saveUserExtension(User user){ + System.out.println("User Object Recieved"); + try{ + Roles roles = new Roles(); + roles.setName(user.getFullName()); + roles.setLoginId(user.getLoginId()); + if(user.getRoles() != null){ + rolesDAO.delete(roles); + for(Role role : user.getRoles()){ + if(role.getName().trim().equalsIgnoreCase("Policy Super Admin") || role.getName().trim().equalsIgnoreCase("System Administrator") || role.getName().trim().equalsIgnoreCase("Standard User") ){ + roles.setRole("super-admin"); + }else if(role.getName().trim().equalsIgnoreCase("Policy Super Editor")){ + roles.setRole("super-editor"); + }else if(role.getName().trim().equalsIgnoreCase("Policy Super Guest")){ + roles.setRole("super-guest"); + }else if(role.getName().trim().equalsIgnoreCase("Policy Admin")){ + roles.setRole("admin"); + }else if(role.getName().trim().equalsIgnoreCase("Policy Editor")){ + roles.setRole("editor"); + }else if(role.getName().trim().equalsIgnoreCase("Policy Guest")){ + roles.setRole("guest"); + } + rolesDAO.save(roles); + } + } + + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(user.getLoginId()); + userInfo.setUserName(user.getFullName()); + userInfoDao.save(userInfo); + } + catch(Exception e){ + logger.error("Exception caused while Setting role to Policy DB"+e); + } + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/service/OnBoardingApiServiceImplPolicy.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/service/OnBoardingApiServiceImplPolicy.java new file mode 100644 index 000000000..083c57683 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/service/OnBoardingApiServiceImplPolicy.java @@ -0,0 +1,348 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + +package org.openecomp.portalapp.service; + +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.client.AppContextManager; +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; + + +public class OnBoardingApiServiceImplPolicy implements IPortalRestAPIService { + RoleService roleService; + UserProfileService userProfileService; + AdminAuthExtension adminAuthExtension; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(OnBoardingApiServiceImplPolicy.class); + + public OnBoardingApiServiceImplPolicy(){ + roleService = AppContextManager.getAppContext().getBean(RoleService.class); + userProfileService = AppContextManager.getAppContext().getBean(UserProfileService.class); + adminAuthExtension = AppContextManager.getAppContext().getBean(AdminAuthExtension.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()); + } + + + @Override + public void pushUser(EcompUser userJson) throws PortalAPIException { + + logger.debug(EELFLoggerDelegate.debugLogger, "pushUser was invoked" + userJson); + + User user = new User(); + String response = ""; + + logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## userJson: " + userJson); + + try { + + //Set input attributes to the object about to be saved + setCurrentAttributes(user, userJson); + + user.setRoles(new TreeSet()); + user.setUserApps(new TreeSet()); + user.setPseudoRoles(new TreeSet()); + + userProfileService.saveUser(user); + adminAuthExtension.saveUserExtension(user); + logger.debug(EELFLoggerDelegate.debugLogger, "push user success."); + response = "push user success."; + response = JSONUtil.convertResponseToJSON(response); + } catch (Exception e) { + e.printStackTrace(); + response = "push user failed with error: " + e.getMessage(); + logger.error(EELFLoggerDelegate.debugLogger, response); + logger.error(EELFLoggerDelegate.errorLogger, "Error happened during OnboardingApiService.pushUser operation: " + response); + logger.error(EELFLoggerDelegate.debugLogger, "Error happened during OnboardingApiService.pushUser operation: " + response); + logger.info(EELFLoggerDelegate.metricsLogger, "OnboardingApiService.pushUser operation has failed."); + throw new PortalAPIException(response, e); + }finally { + MDC.remove(SystemProperties.MDC_TIMER); + } + } + + @Override + public void editUser(String loginId, EcompUser userJson) throws PortalAPIException { + + logger.debug(EELFLoggerDelegate.debugLogger, "OnboardingApi editUser was invoked" + userJson); + + User editUser = new User(); + String response = ""; + logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: " + loginId); + logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## userJson: " + userJson); + + 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); + adminAuthExtension.saveUserExtension(domainUser); + + logger.debug(EELFLoggerDelegate.debugLogger, "edit user success."); + response = "edit user success."; + response = JSONUtil.convertResponseToJSON(response); + } catch (Exception e) { + e.printStackTrace(); + response = "edit user failed with error: " + e.getMessage(); + logger.error(EELFLoggerDelegate.errorLogger, response); + logger.error(EELFLoggerDelegate.debugLogger, "Error happened during OnboardingApiService.editUser operation: " + response); + logger.error(EELFLoggerDelegate.errorLogger, "Error happened during OnboardingApiService.editUser operation: " + response); + throw new PortalAPIException(response, e); + }finally { + MDC.remove(SystemProperties.MDC_TIMER); + } + + //return response; + } + + @Override + public EcompUser getUser(String loginId) throws PortalAPIException { + try{ + 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; + } + else + return UserUtils.convertToEcompUser(user); + } + catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + return null; + } + + } + + @Override + public List<EcompUser> getUsers() throws PortalAPIException { + + + String response = ""; + + 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 pe){ + + response = "getUsers failed with error: " + pe.getMessage(); + pe.printStackTrace(); + logger.error(EELFLoggerDelegate.debugLogger, response); + logger.error(EELFLoggerDelegate.errorLogger, response); + throw new PortalAPIException(response, pe); + } + + + } + + @Override + public List<EcompRole> getAvailableRoles() throws PortalAPIException{ + + String response = ""; + + 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 pe){ + response = "getUsers failed with error: " + pe.getMessage(); + pe.printStackTrace(); + logger.error(EELFLoggerDelegate.debugLogger, response); + logger.error(EELFLoggerDelegate.errorLogger, response); + throw new PortalAPIException(response, pe); + } + } + + @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); + + SortedSet<Role> roles = new TreeSet(); + 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 = "pushUserRole failed with error: " + e.getMessage(); + e.printStackTrace(); + logger.error(EELFLoggerDelegate.debugLogger, response); + logger.error(EELFLoggerDelegate.errorLogger, response); + throw new PortalAPIException(response, e); + }finally { + MDC.remove(SystemProperties.MDC_TIMER); + } + + } + + @Override + public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException { + + 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 = "getUserRoles failed with error: " + e.getMessage(); + e.printStackTrace(); + logger.error(EELFLoggerDelegate.debugLogger, response); + logger.debug(EELFLoggerDelegate.errorLogger, response); + throw new PortalAPIException(response, e); + } + } + + private void replaceExistingRoles(SortedSet<Role> roles, User user) { + // 1. remove existing roles + Set<UserApp> userApps = user.getUserApps(); + Iterator appsItr = (Iterator) 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); + adminAuthExtension.saveUserExtension(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"); + boolean flag = securityService.verifyRESTCredential(null, appUser, password); + return flag; + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to authenticate" + e.getMessage()); + throw new PortalAPIException("Failed to authenticate: " + e.getMessage()); + } + + } + + public String getSessionTimeOuts() throws Exception{ + return PortalTimeoutHandler.gatherSessionExtensions(); + } + + public void updateSessionTimeOuts(String sessionMap) throws Exception{ + PortalTimeoutHandler.updateSessionExtensions(sessionMap); + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java new file mode 100644 index 000000000..c052187af --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java @@ -0,0 +1,73 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import java.util.concurrent.ConcurrentLinkedQueue; + +import javax.annotation.PostConstruct; + +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.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; + +// +// Adding this class for the sole purpose of insuring that the MainUebHandler really +// honors @Async and kicks off a thread. For more info google @Async and read about +// @Async only working if called from different class. +// +@Configuration +public class InitUebHandler { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(InitUebHandler.class); + + + @Autowired + MainUebHandler mainUebHandler; + + public InitUebHandler() { + + } + + @PostConstruct + public void initUeb() { + + try { + String enableListenerThread = PortalApiProperties.getProperty(PortalApiConstants.UEB_LISTENERS_ENABLE); + if (enableListenerThread.equalsIgnoreCase("true")) { + ConcurrentLinkedQueue<UebMsg> inboxQueue = new ConcurrentLinkedQueue<UebMsg>(); + UebManager.getInstance().initListener(inboxQueue); + mainUebHandler.runHandler(inboxQueue); + logger.info(EELFLoggerDelegate.debugLogger, ("Returned from initiating mainUebHandler...")); + } + else { + logger.info(EELFLoggerDelegate.debugLogger, ("Not starting UEB listening thread because ueb_listeners_enable is not set to true in the properties file.")); + } + } + catch (Exception e) { + logger.error(EELFLoggerDelegate.debugLogger, ("Not starting UEB listening thread because property could not be read " + PortalApiConstants.UEB_LISTENERS_ENABLE),AlarmSeverityEnum.MAJOR); + } + + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java new file mode 100644 index 000000000..7ff07dd4e --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java @@ -0,0 +1,104 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +//------------------------------------------------------------------------- +// Listens for received UEB messages and handles the messages +// +// Note: To implement a synchronous reply call getMsgId on the request +// and putMsgId on the reply (echoing the request MsgId). +// +//------------------------------------------------------------------------- +@Component("MainUebHandler") +public class MainUebHandler { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MainUebHandler.class); + + + ConcurrentLinkedQueue<UebMsg> inboxQueue = null; + + @Autowired + WidgetNotificationHandler widgetNotificationHandler; + + @Async + public void runHandler(ConcurrentLinkedQueue<UebMsg> queue) { + inboxQueue = queue; + + logger.info(EELFLoggerDelegate.debugLogger, ("==> MainUebHandler started")); + + while (true) { + UebMsg msg = null; + while ((msg = inboxQueue.poll()) != null) { + if (msg.getMsgType() != null) { + logger.debug(EELFLoggerDelegate.debugLogger, ("<== Received UEB message : " + msg.toString())); + + switch (msg.getMsgType()) { + /* + * Add your own defined handler objects, use @Component for + * the class. See WidgetNotificationHandler as an example. + * + * Use @Async on methods for performance + * + * For syncronous replies use UebManager publishReply and + * echo back the msgId in your response ie + * msg.putMsgId(requestMsg.getMsgId()) + * + * case UebMsgTypes.UEB_MSG_TYPE_XYZ: { + * XYZHandler.handleMsg(msg); break; } + */ + case UebMsgTypes.UEB_MSG_TYPE_WIDGET_NOTIFICATION: { + widgetNotificationHandler.handleWidgetNotification(msg); + break; + } + default: { + + logger.info(EELFLoggerDelegate.debugLogger, ("Unknown message type [" + msg.getMsgType() + "] from " + msg.getSourceTopicName())); + + break; + } + } + } + } + + if (Thread.interrupted()) { + + logger.info(EELFLoggerDelegate.debugLogger, ("==> UebMainHandler exiting")); + + break; + } + + try { + Thread.sleep(10); + } catch (InterruptedException e) { + logger.info(EELFLoggerDelegate.debugLogger, ("UebMainHandler interrupted during sleep" + e.getMessage())); + + } + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java new file mode 100644 index 000000000..dd2213dae --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java @@ -0,0 +1,46 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +@Component +public class WidgetNotificationHandler { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetNotificationHandler.class); + + + public WidgetNotificationHandler() { + } + + @Async + public void handleWidgetNotification(UebMsg requestMsg) { + logger.debug(EELFLoggerDelegate.debugLogger, ("handleWidgetNotification received notification: " + requestMsg.toString())); + /* + * Here the notification msg can be handled + * + * requestMsg.getPayload() - returns string that contains the + * Application defined content + */ + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/util/CustomLoggingFilter.java b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/util/CustomLoggingFilter.java new file mode 100644 index 000000000..48c51195f --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/portalapp/util/CustomLoggingFilter.java @@ -0,0 +1,54 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.util; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.filter.Filter; +import ch.qos.logback.core.spi.FilterReply; + +/** + * Custom Filter class bind with logback.xml + * configuration file to strip out certain log messages + * coming out of special packages or classes. + * + */ +public class CustomLoggingFilter extends Filter<ILoggingEvent> { + + /** + * Custom Filter is added to strip out the continuous U-EB logging messages + * But make sure we log the ERROR & WARNING Level messages. + */ + @Override + public FilterReply decide(ILoggingEvent event) { + try { + if ((event.getLevel() != Level.ERROR || event.getLevel() != Level.WARN) && + (event.getThreadName().equalsIgnoreCase("UEBConsumerThread")) && + (event.getLoggerName().contains("org.openecomp.nsa") || event.getLoggerName().contains("org.apache.http")) + ) { + return FilterReply.DENY; + } else { + return FilterReply.NEUTRAL; + } + } catch(Exception e) { + return FilterReply.NEUTRAL; + } + } +} |