diff options
Diffstat (limited to 'PolicyEngineUtils')
23 files changed, 2105 insertions, 0 deletions
diff --git a/PolicyEngineUtils/policyLogger.properties b/PolicyEngineUtils/policyLogger.properties new file mode 100644 index 000000000..3cf88e816 --- /dev/null +++ b/PolicyEngineUtils/policyLogger.properties @@ -0,0 +1,44 @@ +### +# ============LICENSE_START======================================================= +# PolicyEngineUtils +# ================================================================================ +# 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========================================================= +### + +################################### Set concurrentHashMap and timer info ####################### +#Timer initial delay and the delay between in milliseconds before task is to be execute. +timer.delay.time=1000 +#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. +check.interval= 30000 +#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. +event.expired.time=86400 +#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed +#to remove all expired records from this concurrentHashMap. +concurrentHashMap.limit=5000 +#Size of the concurrentHashMap - when its size drops to this point, stop the Timer +stop.check.point=2500 +################################### Set logging format ############################################# +# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println +logger.type=EELF +#################################### Set level for EELF or SYSTEMOUT logging ################################## +# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all +debugLogger.level=INFO +# Set level for metrics file. Set OFF to disable; set ON to enable +metricsLogger.level=ON +# Set level for error file. Set OFF to disable; set ON to enable +error.level=ON +# Set level for audit file. Set OFF to disable; set ON to enable +audit.level=ON diff --git a/PolicyEngineUtils/pom.xml b/PolicyEngineUtils/pom.xml new file mode 100644 index 000000000..0588453c3 --- /dev/null +++ b/PolicyEngineUtils/pom.xml @@ -0,0 +1,85 @@ +<!-- + ============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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.openecomp.policy.engine</groupId> + <artifactId>PolicyEngineSuite</artifactId> + <version>1.0.0-SNAPSHOT</version> + </parent> + <groupId>org.openecomp.policy.engine</groupId> + <artifactId>PolicyEngineUtils</artifactId> + <dependencies> + <dependency> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + <version>1.2.17</version> + </dependency> + <dependency> + <groupId>org.eclipse.persistence</groupId> + <artifactId>javax.persistence</artifactId> + <version>2.1.0</version> + </dependency> + <dependency> + <groupId>org.eclipse.persistence</groupId> + <artifactId>eclipselink</artifactId> + <version>2.6.0</version> + </dependency> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + <version>[1.4.186,)</version> + </dependency> + <dependency> + <groupId>mysql</groupId> + <artifactId>mysql-connector-java</artifactId> + <version>5.1.30</version> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + <version>2.7.5</version> + </dependency> + <dependency> + <groupId>com.github.fge</groupId> + <artifactId>json-patch</artifactId> + <version>1.9</version> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.11</version> + </dependency> + <!-- https://mvnrepository.com/artifact/com.att.cadi/cadi-aaf --> + <dependency> + <groupId>com.att.cadi</groupId> + <artifactId>cadi-aaf</artifactId> + <version>1.3.0</version> + <exclusions> + <exclusion> + <groupId>com.att.aft</groupId> + <artifactId>dme2</artifactId> + </exclusion> + </exclusions> + </dependency> + </dependencies> +</project> diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/LoadedPolicy.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/LoadedPolicy.java new file mode 100644 index 000000000..574580bac --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/LoadedPolicy.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.api; + +import java.util.Map; +/** + * <code>LoadedPolicy</code> defines the Policy that has been Loaded into the PDP. + * + * @version 0.2 + */ +public interface LoadedPolicy { + /** + * Gets the <code>String</code> format of the Policy Name that has been Loaded into the PDP. + * + * @return <code>String</code> format of Policy Name + */ + public String getPolicyName(); + + /** + * Gets the <code>String</code> format of the Policy Version that has been Loaded into the PDP. + * + * @return <code>String</code> format of the Policy Version. + */ + public String getVersionNo(); + + /** + * Gets the <code>Map</code> of <code>String,String</code> format of the Matches if the policy Loaded is of Config Type. + * + * @return the <code>Map</code> of <code>String,String</code> format of the matches in the policy. + */ + public Map<String, String> getMatches(); + + /** + * Gets the <code>UpdateType</code> of {@link org.openecomp.policy.api.UpdateType} received. + * + * @return <code>UpdateType</code> associated with this <code>PDPNotification</code> + */ + public UpdateType getUpdateType(); +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/NotificationHandler.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/NotificationHandler.java new file mode 100644 index 000000000..9661b72f1 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/NotificationHandler.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.api; +/** + * Defines the methods which need to run when an Event or Notification is received. + * + * @version 0.1 + */ +public interface NotificationHandler { + /** + * <code>notificationReceived</code> method will be triggered automatically whenever a Notification is received by the PEP. + * + * @param notification <code>PDPNotification</code> of {@link org.openecomp.policy.api.PDPNotification} is the object that has information of the notification. + */ + public void notificationReceived(PDPNotification notification); +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/NotificationType.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/NotificationType.java new file mode 100644 index 000000000..8bd5bc8db --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/NotificationType.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.api; + +/** + * Enumeration of the Update Type that has occurred in the <code>PDPNotification</code> of + * {@link org.openecomp.policy.api.PDPNotification} + * + * @version 0.1 + */ +public enum NotificationType { + /** + * Indicates that a policy has been updated + */ + UPDATE("update"), + /** + * Indicates that a policy has been removed + */ + REMOVE("remove"), + /** + * Indicates that both update and removal of policy events has occurred. + */ + BOTH("both") + ; + + private String name; + + private NotificationType(String name){ + this.name = name; + } + + /** + * Returns the <code>String</code> format of the Type for this <code>UpdateType</code> + * @return the <code>String</code> Type of <code>UpdateType</code> + */ + @Override + public String toString(){ + return this.name; + } +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/PDPNotification.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/PDPNotification.java new file mode 100644 index 000000000..18da617cf --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/PDPNotification.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.api; + +import java.util.Collection; + +/** + * Defines the <code>Notification</code> event sent from PDP to Client PEP. + * + * @version 0.2 + */ +public interface PDPNotification { + /** + * Gets the <code>Collection</code> of {@link org.openecomp.policy.api.RemovedPolicy} objects received. + * + * @return the <code>Collection</code> which consists of <code>RemovedPolicy</code> objects. + */ + public Collection<RemovedPolicy> getRemovedPolicies(); + + /** + * Gets the <code>Collection</code> of {@link org.openecomp.policy.api.LoadedPolicy} objects receieved. + * + * @return the <code>Collection</code> which consists of <code>UpdatedPolicy</code> objects. + */ + public Collection<LoadedPolicy> getLoadedPolicies(); + + /** + * Gets the <code>NotificationType</code> of {@link org.openecomp.policy.api.NotificationType} received. + * + * @return <code>NotificationType</code> associated with this <code>PDPNotification</code> + */ + public NotificationType getNotificationType(); + +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/RemovedPolicy.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/RemovedPolicy.java new file mode 100644 index 000000000..b94fdce42 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/RemovedPolicy.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.api; +/** + * <code>RemovedPolicy</code> defines the Policy that has been removed + * + * @version 0.1 + */ +public interface RemovedPolicy { + /** + * Gets the <code>String</code> format of the Policy Name that has been removed. + * + * @return <code>String</code> format of Policy Name + */ + public String getPolicyName(); + + /** + * Gets the <code>String</code> format of the Policy Version that has been removed. + * + * @return <code>String</code> format of Policy Version + */ + public String getVersionNo(); +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/UpdateType.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/UpdateType.java new file mode 100644 index 000000000..d48121b69 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/api/UpdateType.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.api; + +/** + * Enumeration of the Update Type that has occurred in the <code>UpdatedPolicy</code> of + * {@link org.openecomp.policy.api.LoadedPolicy} + * + * @version 0.1 + */ +public enum UpdateType { + /** + * Indicates that a policy has been updated + */ + UPDATE("update"), + /** + * Indicates that a policy is new + */ + NEW("new") + ; + + private String name; + + private UpdateType(String name){ + this.name = name; + } + + /** + * Returns the <code>String</code> format of the Type for this <code>UpdateType</code> + * @return the <code>String</code> Type of <code>UpdateType</code> + */ + @Override + public String toString(){ + return this.name; + } +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/jpa/BackUpMonitorEntity.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/jpa/BackUpMonitorEntity.java new file mode 100644 index 000000000..731cfc7f7 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/jpa/BackUpMonitorEntity.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.NamedQuery; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + + +@Entity +@Table(name="BackUpMonitorEntity") +@NamedQuery(name="BackUpMonitorEntity.findAll", query= "SELECT b FROM BackUpMonitorEntity b ") +public class BackUpMonitorEntity implements Serializable{ + private static final long serialVersionUID = -9190606334322230630L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="node_name", nullable=false) + private String resourceNodeName; + + @Column(name="resource_name", nullable=false, unique=true) + private String resourceName; + + @Column(name="flag", nullable=false) + private String flag; + + @Lob + @Column(name="notification_record") + private String notificationRecord; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="last_seen") + private Date timeStamp; + + @PrePersist + public void prePersist(){ + this.timeStamp = new Date(); + } + + @PreUpdate + public void preUpdate(){ + this.timeStamp = new Date(); + } + + public String getResourceName(){ + return this.resourceName; + } + + public String getResourceNodeName(){ + return this.resourceNodeName; + } + + public String getFlag(){ + return this.flag; + } + + public String getNotificationRecord(){ + return this.notificationRecord; + } + + public Date getTimeStamp(){ + return this.timeStamp; + } + + public void setResourceName(String resourceName){ + this.resourceName = resourceName; + } + + public void setResoruceNodeName(String resourceNodeName){ + this.resourceNodeName = resourceNodeName; + } + + public void setFlag(String flag){ + this.flag = flag; + } + + public void setNotificationRecord(String notificationRecord){ + this.notificationRecord = notificationRecord; + } + + public void setTimeStamp(Date timeStamp){ + this.timeStamp = timeStamp; + } +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/NotificationStore.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/NotificationStore.java new file mode 100644 index 000000000..1c5950c5d --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/NotificationStore.java @@ -0,0 +1,264 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.std; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; + +import org.openecomp.policy.api.LoadedPolicy; +import org.openecomp.policy.api.NotificationType; +import org.openecomp.policy.api.PDPNotification; +import org.openecomp.policy.api.RemovedPolicy; + + +/* + * This Should Compare and save the Notifications from the beginning of Time. + * If there is something new (missed) We notify the client. + * Works for PDP failures. + * + */ +public class NotificationStore { + private static StdPDPNotification notificationRecord = new StdPDPNotification(); + + public static StdPDPNotification getDeltaNotification(StdPDPNotification newNotification){ + StdPDPNotification notificationDelta = new StdPDPNotification(); + ArrayList<StdRemovedPolicy> removedDelta = new ArrayList<StdRemovedPolicy>(); + ArrayList<StdLoadedPolicy> updatedDelta = new ArrayList<StdLoadedPolicy>(); + Collection<StdLoadedPolicy> newUpdatedPolicies = new ArrayList<StdLoadedPolicy>(); + Collection<StdRemovedPolicy> newRemovedPolicies = new ArrayList<StdRemovedPolicy>(); + Collection<LoadedPolicy> oldUpdatedLostPolicies = notificationRecord.getLoadedPolicies(); + Collection<RemovedPolicy> oldRemovedPolicies = notificationRecord.getRemovedPolicies(); + Collection<LoadedPolicy> oldUpdatedPolicies = notificationRecord.getLoadedPolicies(); + Boolean update = false; + Boolean remove = false; + // if the NotificationRecord is empty + if(notificationRecord.getRemovedPolicies()==null || notificationRecord.getLoadedPolicies()==null){ + if(newNotification!=null){ + notificationRecord = newNotification; + } + return notificationDelta; + } + // do the Delta operation. + if(newNotification!=null){ + // check for old removed policies. + if(!newNotification.getRemovedPolicies().isEmpty()){ + for(RemovedPolicy newRemovedPolicy: newNotification.getRemovedPolicies()){ + //Look for policy Not in Remove + Boolean removed = true; + for(RemovedPolicy oldRemovedPolicy: notificationRecord.getRemovedPolicies()){ + if(newRemovedPolicy.getPolicyName().equals(oldRemovedPolicy.getPolicyName())){ + if(newRemovedPolicy.getVersionNo().equals(oldRemovedPolicy.getVersionNo())){ + removed = false; + // Don't want a duplicate. + oldRemovedPolicies.remove(oldRemovedPolicy); + } + } + } + //We need to change our record we have an Update record of this remove. + for(LoadedPolicy oldUpdatedPolicy: notificationRecord.getLoadedPolicies()){ + if(newRemovedPolicy.getPolicyName().equals(oldUpdatedPolicy.getPolicyName())){ + if(newRemovedPolicy.getVersionNo().equals(oldUpdatedPolicy.getVersionNo())){ + oldUpdatedPolicies.remove(oldUpdatedPolicy); + oldUpdatedLostPolicies.remove(oldUpdatedPolicy); + } + } + } + if(removed){ + remove = true; + notificationRecord.getRemovedPolicies().add(newRemovedPolicy); + removedDelta.add((StdRemovedPolicy)newRemovedPolicy); + } + // This will be converted to New Later. + oldRemovedPolicies.add(newRemovedPolicy); + } + } + // Check for old Updated Policies. + if(!newNotification.getLoadedPolicies().isEmpty()){ + for(LoadedPolicy newUpdatedPolicy: newNotification.getLoadedPolicies()){ + // Look for policies which are not in Update + Boolean updated = true; + for(LoadedPolicy oldUpdatedPolicy: notificationRecord.getLoadedPolicies()){ + if(newUpdatedPolicy.getPolicyName().equals(oldUpdatedPolicy.getPolicyName())){ + if(newUpdatedPolicy.getVersionNo().equals(oldUpdatedPolicy.getVersionNo())){ + updated = false; + // Remove the policy from copy. + oldUpdatedLostPolicies.remove(oldUpdatedPolicy); + // Eliminating Duplicate. + oldUpdatedPolicies.remove(oldUpdatedPolicy); + } + } + } + // Change the record if the policy has been Removed earlier. + for(RemovedPolicy oldRemovedPolicy: notificationRecord.getRemovedPolicies()){ + if(oldRemovedPolicy.getPolicyName().equals(newUpdatedPolicy.getPolicyName())){ + if(oldRemovedPolicy.getVersionNo().equals(newUpdatedPolicy.getVersionNo())){ + oldRemovedPolicies.remove(oldRemovedPolicy); + } + } + } + if(updated){ + update = true; + updatedDelta.add((StdLoadedPolicy)newUpdatedPolicy); + } + // This will be converted to new Later + oldUpdatedPolicies.add(newUpdatedPolicy); + } + // Conversion of Update to Remove if that occurred. + if(!oldUpdatedLostPolicies.isEmpty()){ + for(LoadedPolicy updatedPolicy: oldUpdatedLostPolicies){ + StdRemovedPolicy removedPolicy = new StdRemovedPolicy(); + removedPolicy.setPolicyName(updatedPolicy.getPolicyName()); + removedPolicy.setVersionNo(updatedPolicy.getVersionNo()); + removedDelta.add(removedPolicy); + remove = true; + } + } + } + // Update our Record. + if(!oldUpdatedPolicies.isEmpty()){ + for(LoadedPolicy updatedPolicy: oldUpdatedPolicies){ + newUpdatedPolicies.add((StdLoadedPolicy)updatedPolicy); + } + } + if(!oldRemovedPolicies.isEmpty()){ + for(RemovedPolicy removedPolicy: oldRemovedPolicies){ + newRemovedPolicies.add((StdRemovedPolicy)removedPolicy); + } + } + notificationRecord.setRemovedPolicies(newRemovedPolicies); + notificationRecord.setLoadedPolicies(newUpdatedPolicies); + // Update the notification Result. + notificationDelta.setRemovedPolicies(removedDelta); + notificationDelta.setLoadedPolicies(updatedDelta); + if(remove&&update){ + notificationDelta.setNotificationType(NotificationType.BOTH); + }else if(remove){ + notificationDelta.setNotificationType(NotificationType.REMOVE); + }else if(update){ + notificationDelta.setNotificationType(NotificationType.UPDATE); + } + } + return notificationDelta; + } + + public static void recordNotification(StdPDPNotification notification){ + if(notification!=null){ + if(notificationRecord.getRemovedPolicies()==null || notificationRecord.getLoadedPolicies()==null){ + notificationRecord = notification; + }else{ + // Check if there is anything new and update the record. + if(notificationRecord.getLoadedPolicies()!=null || notificationRecord.getRemovedPolicies()!=null){ + HashSet<StdRemovedPolicy> removedPolicies = new HashSet<StdRemovedPolicy>(); + for(RemovedPolicy rPolicy: notificationRecord.getRemovedPolicies()){ + StdRemovedPolicy sRPolicy = new StdRemovedPolicy(); + sRPolicy.setPolicyName(rPolicy.getPolicyName()); + sRPolicy.setVersionNo(rPolicy.getVersionNo()); + removedPolicies.add(sRPolicy); + } + HashSet<StdLoadedPolicy> updatedPolicies = new HashSet<StdLoadedPolicy>(); + for(LoadedPolicy uPolicy: notificationRecord.getLoadedPolicies()){ + StdLoadedPolicy sUPolicy = new StdLoadedPolicy(); + sUPolicy.setMatches(uPolicy.getMatches()); + sUPolicy.setPolicyName(uPolicy.getPolicyName()); + sUPolicy.setVersionNo(uPolicy.getVersionNo()); + updatedPolicies.add(sUPolicy); + } + + // Checking with the new updated policies. + if(notification.getLoadedPolicies()!=null && !notification.getLoadedPolicies().isEmpty()){ + for(LoadedPolicy newUpdatedPolicy: notification.getLoadedPolicies()){ + // If it was removed earlier then we need to remove from our record + Iterator<StdRemovedPolicy> oldRemovedPolicy = removedPolicies.iterator(); + while(oldRemovedPolicy.hasNext()){ + RemovedPolicy policy = oldRemovedPolicy.next(); + if(newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if(newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldRemovedPolicy.remove(); + } + } + } + // If it was previously updated need to Overwrite it to the record. + Iterator<StdLoadedPolicy> oldUpdatedPolicy = updatedPolicies.iterator(); + while(oldUpdatedPolicy.hasNext()){ + LoadedPolicy policy = oldUpdatedPolicy.next(); + if(newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if(newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldUpdatedPolicy.remove(); + } + } + } + StdLoadedPolicy sUPolicy = new StdLoadedPolicy(); + sUPolicy.setMatches(newUpdatedPolicy.getMatches()); + sUPolicy.setPolicyName(newUpdatedPolicy.getPolicyName()); + sUPolicy.setVersionNo(newUpdatedPolicy.getVersionNo()); + updatedPolicies.add(sUPolicy); + } + } + // Checking with New Removed Policies. + if(notification.getRemovedPolicies()!=null && !notification.getRemovedPolicies().isEmpty()){ + for(RemovedPolicy newRemovedPolicy : notification.getRemovedPolicies()){ + // If it was previously removed Overwrite it to the record. + Iterator<StdRemovedPolicy> oldRemovedPolicy = removedPolicies.iterator(); + while(oldRemovedPolicy.hasNext()){ + RemovedPolicy policy = oldRemovedPolicy.next(); + if(newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if(newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldRemovedPolicy.remove(); + } + } + } + // If it was added earlier then we need to remove from our record. + Iterator<StdLoadedPolicy> oldUpdatedPolicy = updatedPolicies.iterator(); + while(oldUpdatedPolicy.hasNext()){ + LoadedPolicy policy = oldUpdatedPolicy.next(); + if(newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if(newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldUpdatedPolicy.remove(); + } + } + } + StdRemovedPolicy sRPolicy = new StdRemovedPolicy(); + sRPolicy.setPolicyName(newRemovedPolicy.getPolicyName()); + sRPolicy.setVersionNo(newRemovedPolicy.getVersionNo()); + removedPolicies.add(sRPolicy); + } + } + notificationRecord.setRemovedPolicies(removedPolicies); + notificationRecord.setLoadedPolicies(updatedPolicies); + } + if(!notificationRecord.getLoadedPolicies().isEmpty() && !notificationRecord.getRemovedPolicies().isEmpty()){ + notificationRecord.setNotificationType(NotificationType.BOTH); + }else if(!notificationRecord.getLoadedPolicies().isEmpty()){ + notificationRecord.setNotificationType(NotificationType.UPDATE); + }else if(!notificationRecord.getRemovedPolicies().isEmpty()){ + notificationRecord.setNotificationType(NotificationType.REMOVE); + } + } + } + } + + // This should return the current Notification Record. + public static PDPNotification getNotificationRecord(){ + return notificationRecord; + } +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdLoadedPolicy.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdLoadedPolicy.java new file mode 100644 index 000000000..e11ec8ce7 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdLoadedPolicy.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.std; + +import java.util.Map; + +import org.openecomp.policy.api.LoadedPolicy; +import org.openecomp.policy.api.UpdateType; + +public class StdLoadedPolicy implements LoadedPolicy{ + private String policyName = null; + private String versionNo = null; + private Map<String,String> matches = null; + private UpdateType updateType = null; + + @Override + public String getPolicyName() { + if(policyName!=null && policyName.contains(".xml")){ + return (policyName.substring(0, policyName.substring(0, policyName.lastIndexOf(".")).lastIndexOf("."))); + } + return this.policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + @Override + public String getVersionNo() { + return this.versionNo; + } + + public void setVersionNo(String versionNo) { + this.versionNo = versionNo; + } + + @Override + public Map<String,String> getMatches() { + return this.matches; + } + + public void setMatches(Map<String,String> matches) { + this.matches = matches; + } + + @Override + public UpdateType getUpdateType() { + return this.updateType; + } + + public void setUpdateType(UpdateType updateType){ + this.updateType = updateType; + } +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdPDPNotification.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdPDPNotification.java new file mode 100644 index 000000000..6a6bf23e5 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdPDPNotification.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.std; + +import java.util.Collection; +import java.util.HashSet; + +import org.openecomp.policy.api.LoadedPolicy; +import org.openecomp.policy.api.NotificationType; +import org.openecomp.policy.api.PDPNotification; +import org.openecomp.policy.api.RemovedPolicy; + +public class StdPDPNotification implements PDPNotification{ + private Collection<StdRemovedPolicy> removedPolicies = null; + private Collection<StdLoadedPolicy> loadedPolicies = null; + private Collection<RemovedPolicy> removed = null; + private Collection<LoadedPolicy> updated = null; + private NotificationType notificationType= null; + + @Override + public Collection<RemovedPolicy> getRemovedPolicies() { + removed = new HashSet<RemovedPolicy>(); + if(removedPolicies!=null){ + for(RemovedPolicy removedPolicy: removedPolicies){ + removed.add(removedPolicy); + } + return this.removed; + }else{ + return null; + } + } + + @Override + public Collection<LoadedPolicy> getLoadedPolicies() { + updated = new HashSet<LoadedPolicy>(); + if(loadedPolicies!=null){ + for(LoadedPolicy updatedPolicy: loadedPolicies){ + updated.add(updatedPolicy); + } + return updated; + }else{ + return null; + } + } + + @Override + public NotificationType getNotificationType() { + return notificationType; + } + + public void setNotificationType(NotificationType notificationType){ + this.notificationType= notificationType; + } + + public void setLoadedPolicies(Collection<StdLoadedPolicy> loadedPolicies) { + this.loadedPolicies = loadedPolicies; + } + + public void setRemovedPolicies(Collection<StdRemovedPolicy> removedPolicies) { + this.removedPolicies = removedPolicies; + } +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdRemovedPolicy.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdRemovedPolicy.java new file mode 100644 index 000000000..665f3c584 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdRemovedPolicy.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.std; + +import org.openecomp.policy.api.RemovedPolicy; + +public class StdRemovedPolicy implements RemovedPolicy{ + private String policyName = null; + private String versionNo = null; + + @Override + public String getVersionNo() { + return this.versionNo; + } + + public void setVersionNo(String versionNo) { + this.versionNo = versionNo; + } + + @Override + public String getPolicyName() { + if(policyName!=null && policyName.contains(".xml")){ + return (policyName.substring(0, policyName.substring(0, policyName.lastIndexOf(".")).lastIndexOf("."))); + } + return this.policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClient.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClient.java new file mode 100644 index 000000000..1565c18d0 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClient.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.util.Properties; + +import org.apache.log4j.Logger; + +import com.att.cadi.Access; +import com.att.cadi.Access.Level; +import com.att.cadi.CadiException; +import com.att.cadi.aaf.AAFPermission; +import com.att.cadi.aaf.v2_0.AAFAuthn; +import com.att.cadi.aaf.v2_0.AAFCon; +import com.att.cadi.aaf.v2_0.AAFConDME2; +import com.att.cadi.aaf.v2_0.AAFLurPerm; +import com.att.cadi.config.Config; + + +/** + * AAF Client: Generic AAF Client implementation to connect to AAF Resources to validate permissions and authorization. + * + */ +public class AAFPolicyClient { + private static Logger LOGGER = Logger.getLogger(AAFPolicyClient.class.getName()); + + private static final String DEFAULT_AFT_LATITUDE = "32.780140"; + private static final String DEFAULT_AFT_LONGITUDE = "-96.800451"; + private static final String DEFAULT_AAF_USER_EXPIRES = Integer.toString(5*60000); // 5 minutes for found items to live in cache + private static final String DEFAULT_AAF_HIGH_COUNT = Integer.toString(400); // Maximum number of items in Cache + + private static AAFPolicyClient instance = null; + private static Properties props = new Properties(); + private static AAFCon<?> aafCon = null; + private static AAFLurPerm aafLurPerm = null; + private static AAFAuthn<?> aafAuthn = null; + private static Access access = null; + + + private AAFPolicyClient(Properties properties) throws AAFPolicyException{ + if(instance == null){ + instance = this; + } + setup(properties); + } + + /** + * Gets the instance of the AAFClient instance. Needs Proper properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT + * + * @param properties Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT + * @return AAFClient instance. + * @throws AAFPolicyException Exceptions. + */ + public static synchronized AAFPolicyClient getInstance(Properties properties) throws AAFPolicyException{ + if(instance == null) { + LOGGER.info("Creating AAFClient Instance "); + instance = new AAFPolicyClient(properties); + } + return instance; + } + + // To set Property values && Connections. + private void setup(Properties properties) throws AAFPolicyException { + /*if(properties!=null && !properties.isEmpty()){ + props = System.getProperties(); + props.setProperty("AFT_LATITUDE", properties.getProperty("AFT_LATITUDE", DEFAULT_AFT_LATITUDE)); + props.setProperty("AFT_LONGITUDE", properties.getProperty("AFT_LONGITUDE", DEFAULT_AFT_LONGITUDE)); + props.setProperty("aaf_id",properties.getProperty("aaf_id", "aafID")); + props.setProperty("aaf_password", properties.getProperty("aaf_password", "aafPass")); + if(properties.containsKey(Config.AAF_URL)){ + // if given a value in properties file. + props.setProperty(Config.AAF_URL, properties.getProperty(Config.AAF_URL)); + }else{ + LOGGER.error("Required Property value is missing : " + Config.AAF_URL); + throw new AAFPolicyException("Required Property value is missing : " + Config.AAF_URL); + } + + if(properties.containsKey("AFT_ENVIRONMENT")){ + props.setProperty("AFT_ENVIRONMENT", properties.getProperty("AFT_ENVIRONMENT")); + }else{ + LOGGER.error("Required Property value is missing : AFT_ENVIRONMENT"); + throw new AAFPolicyException("Required Property value is missing : AFT_ENVIRONMENT"); + } + props.setProperty(Config.AAF_USER_EXPIRES, properties.getProperty(Config.AAF_USER_EXPIRES, DEFAULT_AAF_USER_EXPIRES)); + props.setProperty(Config.AAF_HIGH_COUNT, properties.getProperty(Config.AAF_HIGH_COUNT, DEFAULT_AAF_HIGH_COUNT)); + }else{ + LOGGER.error("Required Property value is missing "); + throw new AAFPolicyException("Required Property value is missing"); + } + access = new PolicyAccess(props, Level.valueOf(properties.getProperty("AAF_LOG_LEVEL", Level.INFO.toString()))); + setUpAAF();*/ + } + + /** + * Updates the Properties file in case if required. + * + * @param properties Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT + * @throws AAFPolicyException exceptions if any. + */ + public void updateProperties(Properties properties) throws AAFPolicyException{ + setup(properties); + } + + /** + * Checks the Authentication and Permissions for the given values. + * + * @param pass Password pertaining to the loginId + * @param type Permissions Type. + * @param instance Permissions Instance. + * @param action Permissions Action. + * @return + */ + public boolean checkAuthPerm(String mechID, String pass, String type, String instance, String action){ + if(checkAuth(mechID, pass) && checkPerm(mechID, pass, type, instance, action)){ + return true; + } + return false; + } + + /** + * Checks the Authentication of the UserName and Password Given. + * + * @param userName UserName + * @param pass Password. + * @return True or False. + */ + public boolean checkAuth(String userName, String pass){ + /*if(aafAuthn!=null){ + try { + int i=0; + do{ + if(aafAuthn.validate(userName, pass)==null){ + return true; + } + i++; + }while(i<2); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + } + } + LOGGER.debug("Authentication failed for : " + userName + " in " + props.getProperty("AAF_URL")); + return false;*/ + return true; + } + + /** + * Checks Permissions for the given UserName, Password and Type, Instance Action. + * + * @param userName UserName + * @param pass Password. + * @param type Permissions Type. + * @param instance Permissions Instance. + * @param action Permissions Action. + * @return True or False. + */ + public boolean checkPerm(String userName, String pass, String type, String instance, String action){ + /*int i =0; + Boolean result= false; + do{ + if(aafCon!=null && aafLurPerm !=null){ + try { + aafCon.basicAuth(userName, pass); + AAFPermission perm = new AAFPermission(type, instance, action); + result = aafLurPerm.fish(userName, perm); + } catch (CadiException e) { + LOGGER.error(e.getMessage()); + aafLurPerm.destroy(); + } + } + LOGGER.debug("Permissions for : " + userName + " in " + props.getProperty("AAF_URL") + "for " + type + "," + instance + "," + action + "\n Result is: " + result); + i++; + }while(i<2 && !result); // Try once more to check if this can be passed. AAF has some issues. + return result;*/ + return true; + } + + /*private boolean setUpAAF(){ + try { + aafCon = new AAFConDME2(access); + aafLurPerm = aafCon.newLur();//new AAFLurPerm(aafCon); + aafAuthn = aafCon.newAuthn(aafLurPerm);//new AAFAuthn(aafCon, aafLurPerm); + return true; + } catch (Exception e) { + LOGGER.error("Error while creating Connection " + e.getMessage()); + return false; + } + }*/ +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyException.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyException.java new file mode 100644 index 000000000..a798b6e53 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyException.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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; + +/** + * AAFPolicyException to show exception messages. + * + */ +public class AAFPolicyException extends Exception { + private static final long serialVersionUID = 1910606668038621L; + + public AAFPolicyException() { + } + + public AAFPolicyException(String message) { + super(message); + } + + public AAFPolicyException(Throwable cause){ + super(cause); + } + + public AAFPolicyException(String message, Throwable cause) { + super(message, cause); + } + + public AAFPolicyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpHandler.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpHandler.java new file mode 100644 index 000000000..227d0ceff --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpHandler.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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 org.openecomp.policy.api.NotificationHandler; +import org.openecomp.policy.api.PDPNotification; + +public interface BackUpHandler extends NotificationHandler{ + + /** + * <code>notificationReceived</code> method will be triggered automatically whenever a Notification is received by the PEP. + * + * @param notification <code>PDPNotification</code> of {@link org.openecomp.policy.api.PDPNotification} is the object that has information of the notification. + */ + public void notificationReceived(PDPNotification notification); + + /** + * <code>runOnNotification</code> method will be triggered automatically whenever a Notification is received by the PEP This needs to be the main implementation. + * + * @param notification <code>PDPNotification</code> of {@link org.openecomp.policy.api.PDPNotification} is the object that has information of the notification. + */ + public void runOnNotification(PDPNotification notification); +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpMonitor.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpMonitor.java new file mode 100644 index 000000000..1b35dcc57 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpMonitor.java @@ -0,0 +1,378 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.util.Date; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.persistence.Query; + +import org.apache.log4j.Logger; +import org.eclipse.persistence.config.PersistenceUnitProperties; +import org.openecomp.policy.api.PDPNotification; +import org.openecomp.policy.jpa.BackUpMonitorEntity; +import org.openecomp.policy.std.NotificationStore; +import org.openecomp.policy.std.StdPDPNotification; + +import com.fasterxml.jackson.databind.JsonNode; +import com.github.fge.jackson.JsonLoader; +import com.github.fge.jsonpatch.JsonPatch; +import com.github.fge.jsonpatch.JsonPatchException; +import com.github.fge.jsonpatch.diff.JsonDiff; + +/** + * BackUp Monitor checks Backup Status with the Database and maintains Redundancy for Gateway Applications. + * + */ +public class BackUpMonitor { + private static final Logger logger = Logger.getLogger(BackUpMonitor.class.getName()); + private static final int DEFAULT_PING = 60000; // Value is in milliseconds. + + private static BackUpMonitor instance = null; + private static String resourceName = null; + private static String resourceNodeName = null; + private static String notificationRecord = null; + private static String lastMasterNotification= null; + private static int pingInterval = DEFAULT_PING; + private static Boolean masterFlag = false; + private static Object lock = new Object(); + private static Object notificationLock = new Object(); + private static BackUpHandler handler= null; + private EntityManager em; + private EntityManagerFactory emf; + + /* + * Enumeration for the Resource Node Naming. Add here if required. + */ + public enum ResourceNode{ + BRMS, + ASTRA + } + + private BackUpMonitor(String resourceNodeName, String resourceName, Properties properties, BackUpHandler handler) throws Exception{ + if(instance == null){ + instance = this; + } + BackUpMonitor.resourceNodeName = resourceNodeName; + BackUpMonitor.resourceName = resourceName; + BackUpMonitor.handler = handler; + // Create Persistence Entity + properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePU.xml"); + emf = Persistence.createEntityManagerFactory("PolicyEngineUtils", properties); + if(emf==null){ + logger.error("Unable to create Entity Manger Factory "); + throw new Exception("Unable to create Entity Manger Factory"); + } + em = emf.createEntityManager(); + + // Check Database if this is Master or Slave. + checkDataBase(); + + // Start thread. + Thread t = new Thread(new BMonitor()); + t.start(); + } + + /** + * Gets the BackUpMonitor Instance if given proper resourceName and properties. Else returns null. + * + * @param resourceNodeName String format of the Resource Node to which the resource Belongs to. + * @param resourceName String format of the ResourceName. This needs to be Unique. + * @param properties Properties format of the properties file. + * @return BackUpMonitor instance. + */ + public static synchronized BackUpMonitor getInstance(String resourceNodeName, String resourceName, Properties properties, BackUpHandler handler) throws Exception { + if(resourceNodeName==null || resourceNodeName.trim().equals("") ||resourceName==null|| resourceName.trim().equals("") || properties == null || handler==null){ + logger.error("Error while getting Instance. Please check resourceName and/or properties file"); + return null; + }else if((resourceNodeName.equals(ResourceNode.ASTRA.toString()) || resourceNodeName.equals(ResourceNode.BRMS.toString())) && validate(properties) && instance==null){ + logger.info("Creating Instance of BackUpMonitor"); + instance = new BackUpMonitor(resourceNodeName, resourceName, properties, handler); + } + return instance; + } + + // This is to validate given Properties with required values. + private static Boolean validate(Properties properties){ + if(properties.getProperty("javax.persistence.jdbc.driver")==null ||properties.getProperty("javax.persistence.jdbc.driver").trim().equals("")){ + logger.error("javax.persistence.jdbc.driver property is empty"); + return false; + } + if(properties.getProperty("javax.persistence.jdbc.url")==null || properties.getProperty("javax.persistence.jdbc.url").trim().equals("")){ + logger.error("javax.persistence.jdbc.url property is empty"); + return false; + } + if(properties.getProperty("javax.persistence.jdbc.user")==null || properties.getProperty("javax.persistence.jdbc.user").trim().equals("")){ + logger.error("javax.persistence.jdbc.user property is empty"); + return false; + } + if(properties.getProperty("javax.persistence.jdbc.password")==null || properties.getProperty("javax.persistence.jdbc.password").trim().equals("")){ + logger.error("javax.persistence.jdbc.password property is empty"); + return false; + } + if(properties.getProperty("ping_interval")==null || properties.getProperty("ping_interval").trim().equals("")){ + logger.info("ping_interval property not specified. Taking default value"); + }else{ + try{ + pingInterval = Integer.parseInt(properties.getProperty("ping_interval").trim()); + }catch(NumberFormatException e){ + logger.warn("Ignored invalid proeprty ping_interval. Taking default value."); + pingInterval = DEFAULT_PING; + } + } + return true; + } + + // Sets the Flag for masterFlag to either True or False. + private static void setFlag(Boolean flag){ + synchronized (lock) { + masterFlag = flag; + } + } + + /** + * Gets the Boolean value of Master(True) or Slave mode (False) + * + * @return Boolean flag which if True means that the operation needs to be performed(Master mode) or if false the operation is in slave mode. + */ + public synchronized Boolean getFlag(){ + synchronized (lock) { + return masterFlag; + } + } + + // BackUpMonitor Thread + private class BMonitor implements Runnable{ + @Override + public void run() { + logger.info("Starting BackUpMonitor Thread.. "); + while(true){ + try { + TimeUnit.MILLISECONDS.sleep(pingInterval); + checkDataBase(); + } catch (Exception e) { + logger.error("Error during Thread execution " + e.getMessage()); + } + } + } + } + + // Set Master + private static BackUpMonitorEntity setMaster(BackUpMonitorEntity bMEntity){ + bMEntity.setFlag("MASTER"); + setFlag(true); + return bMEntity; + } + + // Set Slave + private static BackUpMonitorEntity setSlave(BackUpMonitorEntity bMEntity){ + bMEntity.setFlag("SLAVE"); + setFlag(false); + return bMEntity; + } + + // Check Database and set the Flag. + private void checkDataBase() throws Exception { + EntityTransaction et = em.getTransaction(); + notificationRecord = PolicyUtils.objectToJsonString(NotificationStore.getNotificationRecord()); + // Clear Cache. + logger.info("Clearing Cache"); + em.getEntityManagerFactory().getCache().evictAll(); + try{ + logger.info("Checking Datatbase for BackUpMonitor.. "); + et.begin(); + Query query = em.createQuery("select b from BackUpMonitorEntity b where b.resourceNodeName = :nn"); + if(resourceNodeName.equals(ResourceNode.ASTRA.toString())){ + query.setParameter("nn", ResourceNode.ASTRA.toString()); + }else if(resourceNodeName.equals(ResourceNode.BRMS.toString())){ + query.setParameter("nn", ResourceNode.BRMS.toString()); + } + List<?> bMList = query.getResultList(); + if(bMList.isEmpty()){ + // This is New. create an entry as Master. + logger.info("Adding resource " + resourceName + " to Database"); + BackUpMonitorEntity bMEntity = new BackUpMonitorEntity(); + bMEntity.setResoruceNodeName(resourceNodeName); + bMEntity.setResourceName(resourceName); + bMEntity = setMaster(bMEntity); + bMEntity.setTimeStamp(new Date()); + em.persist(bMEntity); + em.flush(); + }else{ + // Check if resourceName already exists and if there is a Master in Node. + Boolean masterFlag = false; + Boolean alreadyMaster = false; + Date currentTime; + BackUpMonitorEntity masterEntity = null; + BackUpMonitorEntity slaveEntity = null; + long timeDiff = 0; + for(int i=0; i< bMList.size(); i++){ + BackUpMonitorEntity bMEntity = (BackUpMonitorEntity) bMList.get(i); + logger.info("Refreshing Entity. "); + em.refresh(bMEntity); + if(bMEntity.getResourceName().equals(resourceName)){ + logger.info("Resource Name already Exists. " + resourceName); + if(bMEntity.getFlag().equalsIgnoreCase("MASTER")){ + // Master mode + setFlag(true); + logger.info(resourceName + " is on Master Mode"); + bMEntity.setTimeStamp(new Date()); + bMEntity.setNotificationRecord(notificationRecord); + em.persist(bMEntity); + em.flush(); + setLastNotification(null); + alreadyMaster = true; + break; + }else{ + // Slave mode. + setFlag(false); + slaveEntity = bMEntity; + logger.info(resourceName + " is on Slave Mode"); + } + }else{ + if(bMEntity.getFlag().equalsIgnoreCase("MASTER")){ + // check if its time stamp is old. + currentTime = new Date(); + timeDiff = currentTime.getTime()-bMEntity.getTimeStamp().getTime(); + masterEntity = bMEntity; + masterFlag = true; + } + } + } + // If there is master and no slave entry then add the slave entry to database. + // If we are slave and there is a masterFlag then check timeStamp to find if master is down. + if(!alreadyMaster){ + BackUpMonitorEntity bMEntity; + if(slaveEntity==null){ + bMEntity = new BackUpMonitorEntity(); + }else{ + bMEntity = slaveEntity; + } + if(masterFlag && !getFlag()){ + if(timeDiff > pingInterval){ + // This is down or has an issue and we need to become Master while turning the Master to slave. + masterEntity = setSlave(masterEntity); + String lastNotification = null; + if(masterEntity.getNotificationRecord()!=null){ + lastNotification = calculatePatch(masterEntity.getNotificationRecord()); + } + setLastNotification(lastNotification); + em.persist(masterEntity); + em.flush(); + bMEntity = setMaster(bMEntity); + logger.info(resourceName + " changed to Master Mode"); + }else{ + bMEntity = setSlave(bMEntity); + setLastNotification(null); + logger.info(resourceName + " is on Slave Mode"); + } + }else{ + // If there is no Master. we need to become Master. + bMEntity = setMaster(bMEntity); + logger.info(resourceName + " is on Master Mode"); + setLastNotification(null); + } + bMEntity.setNotificationRecord(notificationRecord); + bMEntity.setResoruceNodeName(resourceNodeName); + bMEntity.setResourceName(resourceName); + bMEntity.setTimeStamp(new Date()); + em.persist(bMEntity); + em.flush(); + } + } + et.commit(); + }catch(Exception e){ + logger.error("failed Database Operation " + e.getMessage()); + if(et.isActive()){ + et.rollback(); + } + throw new Exception(e); + } + } + + // Calculate Patch and return String JsonPatch of the notification Delta. + private synchronized String calculatePatch(String oldNotificationRecord) { + try{ + JsonNode notification = JsonLoader.fromString(notificationRecord); + JsonNode oldNotification = JsonLoader.fromString(oldNotificationRecord); + JsonNode patchNode = JsonDiff.asJson(oldNotification, notification); + logger.info("Generated JSON Patch is " + patchNode.toString()); + JsonPatch patch = JsonPatch.fromJson(patchNode); + try { + JsonNode patched = patch.apply(oldNotification); + logger.info("Generated New Notification is : " + patched.toString()); + return patched.toString(); + } catch (JsonPatchException e) { + logger.error("Error generating Patched " +e.getMessage()); + return null; + } + }catch(IOException e){ + logger.error("Error generating Patched " +e.getMessage()); + return null; + } + } + + /** + * Updates Notification in the Database while Performing the health check. + * + * @param notification String format of notification record to store in the Database. + * @throws Exception + */ + public synchronized void updateNotification() throws Exception{ + checkDataBase(); + } + + // Take in string notification and send the record delta to Handler. + private static void callHandler(String notification){ + if(handler!=null){ + try { + PDPNotification notificationObject = PolicyUtils.jsonStringToObject(notification, StdPDPNotification.class); + if(notificationObject.getNotificationType()!=null){ + logger.info("Performing Patched notification "); + try{ + handler.runOnNotification(notificationObject); + }catch (Exception e){ + logger.error("Error in Clients Handler Object : " + e.getMessage()); + } + } + } catch (IOException e) { + logger.info("Error while notification Conversion " + e.getMessage()); + } + } + } + + // Used to set LastMasterNotification Record. + private static void setLastNotification(String notification){ + synchronized(notificationLock){ + lastMasterNotification = notification; + if(lastMasterNotification!=null && !lastMasterNotification.equals("\"notificationType\":null")){ + callHandler(notification); + } + } + } +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyAccess.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyAccess.java new file mode 100644 index 000000000..6141a5f73 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyAccess.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.util.Date; +import java.util.Properties; + +import org.apache.log4j.Logger; + +import com.att.cadi.Access; + +/** + * PolicyAccess used by AAF for logging purposes. + * + */ +public class PolicyAccess implements Access { + private static final Logger logger = Logger.getLogger(PolicyAccess.class.getName()); + + private Properties properties = new Properties(); + private Access.Level logLevel = Access.Level.INFO; + + public PolicyAccess(Properties properties, Level level) { + this.properties = properties; + if(level!=null){ + logLevel = level; + } + } + + @Override + public ClassLoader classLoader() { + return getClass().getClassLoader(); + } + + @Override + public String decrypt(String enc, boolean arg1) throws IOException { + return enc; + } + + @Override + public String getProperty(String prop, String def) { + return properties.getProperty(prop, def); + } + + @Override + public void load(InputStream in) throws IOException { + properties.load(in); + } + + @Override + public void log(Level level, Object... args) { + if (logLevel.compareTo(level) > 0) { + return; + } + StringBuffer sb = new StringBuffer(); + sb.append(new Date()).append(' ').append(level); + logtail(sb, args); + } + + @Override + public void log(Exception e, Object... args) { + StringBuffer sb = new StringBuffer(); + sb.append(new Date()).append(" EXCEPTION ").append(e.getMessage()); + logtail(sb, args); + logger.error(e.getMessage() + e); + } + + @Override + public void setLogLevel(Level level) { + logLevel = level; + } + + private void logtail(StringBuffer sb, Object[] args) { + for (Object o: args) { + String s = o.toString(); + if (s.length() > 0) { + sb.append(' ').append(s); + } + } + logger.info(sb.toString()); + } + + @Override + public boolean willLog(Level arg0) { + // TODO Auto-generated method stub + return false; + } +} diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java new file mode 100644 index 000000000..fd8102af3 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.util.Base64; +import java.util.StringTokenizer; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PolicyUtils { + + public static String objectToJsonString(Object o) throws JsonProcessingException{ + ObjectMapper mapper = new ObjectMapper(); + return mapper.writeValueAsString(o); + } + + public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws JsonParseException, JsonMappingException, IOException{ + ObjectMapper mapper = new ObjectMapper(); + T t = mapper.readValue(jsonString, className); + return t; + } + + public static String[] decodeBasicEncoding(String encodedValue) throws Exception{ + if(encodedValue!=null && encodedValue.contains("Basic ")){ + String encodedUserPassword = encodedValue.replaceFirst("Basic" + " ", ""); + String usernameAndPassword = null; + byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + String username = tokenizer.nextToken(); + String password = tokenizer.nextToken(); + return new String[]{username, password}; + }else{ + return null; + } + } +} diff --git a/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml b/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml new file mode 100644 index 000000000..147dddf8e --- /dev/null +++ b/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + PolicyEngineUtils + ================================================================================ + 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========================================================= + --> + +<persistence version="2.1" + xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> + <persistence-unit name="PolicyEngineUtils" transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <class>org.openecomp.policy.jpa.BackUpMonitorEntity</class> + </persistence-unit> +</persistence> diff --git a/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/Handler.java b/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/Handler.java new file mode 100644 index 000000000..eb811ab22 --- /dev/null +++ b/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/Handler.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.test; + +import org.openecomp.policy.api.PDPNotification; +import org.openecomp.policy.utils.BackUpHandler; + +public class Handler implements BackUpHandler{ + + @Override + public void notificationReceived(PDPNotification notification) { + System.out.println("Received Notification from PDP. "); + } + + @Override + public void runOnNotification(PDPNotification notification) { + System.out.println("Running main Notification Function. "); + } + +} diff --git a/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/PolicyUtilsTest.java b/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/PolicyUtilsTest.java new file mode 100644 index 000000000..c3f8bedb0 --- /dev/null +++ b/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/PolicyUtilsTest.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.test; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.openecomp.policy.api.NotificationType; +import org.openecomp.policy.api.PDPNotification; +import org.openecomp.policy.api.UpdateType; +import org.openecomp.policy.std.StdLoadedPolicy; +import org.openecomp.policy.std.StdPDPNotification; +import org.openecomp.policy.std.StdRemovedPolicy; +import org.openecomp.policy.utils.PolicyUtils; + +public class PolicyUtilsTest { + + @Test + public void testJsonConversions() throws Exception{ + @SuppressWarnings("unused") + PolicyUtils policyUtils = new PolicyUtils(); + StdPDPNotification notification = new StdPDPNotification(); + notification.setNotificationType(NotificationType.BOTH); + Collection<StdRemovedPolicy> removedPolicies = new ArrayList<StdRemovedPolicy>(); + Collection<StdLoadedPolicy> loadedPolicies = new ArrayList<StdLoadedPolicy>(); + StdRemovedPolicy removedPolicy = new StdRemovedPolicy(); + StdLoadedPolicy updatedPolicy = new StdLoadedPolicy(); + removedPolicy.setPolicyName("Test"); + removedPolicy.setVersionNo("1"); + removedPolicies.add(removedPolicy); + updatedPolicy.setPolicyName("Testing"); + updatedPolicy.setVersionNo("1"); + updatedPolicy.setUpdateType(UpdateType.NEW); + Map<String, String> matches = new HashMap<String, String>(); + matches.put("key", "value"); + updatedPolicy.setMatches(matches); + loadedPolicies.add(updatedPolicy); + notification.setRemovedPolicies(removedPolicies); + notification.setLoadedPolicies(loadedPolicies); + + String json = PolicyUtils.objectToJsonString(notification); + PDPNotification getBackObject = PolicyUtils.jsonStringToObject(json, StdPDPNotification.class); + assertEquals(0,getBackObject.getNotificationType().compareTo(notification.getNotificationType())); + + } +} diff --git a/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/testBackUpMonitor.java b/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/testBackUpMonitor.java new file mode 100644 index 000000000..8763f0fca --- /dev/null +++ b/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/testBackUpMonitor.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * 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.test; + +import static org.junit.Assert.assertNull; +import java.util.Properties; + +import org.junit.Test; +import org.openecomp.policy.utils.BackUpMonitor; + + +public class testBackUpMonitor { + + @Test + public void backUpMonitorTestFail() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", "policy_user"); + properties.setProperty("javax.persistence.jdbc.password", ""); + //properties.setProperty("ping_interval", "500000"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoUser() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", ""); + properties.setProperty("javax.persistence.jdbc.password", "password"); + //properties.setProperty("ping_interval", "500000"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoURL() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", ""); + properties.setProperty("javax.persistence.jdbc.user", "test"); + properties.setProperty("javax.persistence.jdbc.password", "password"); + //properties.setProperty("ping_interval", "500000"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoDriver() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", ""); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", "test"); + properties.setProperty("javax.persistence.jdbc.password", "password"); + //properties.setProperty("ping_interval", "500000"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoNode() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", "test"); + properties.setProperty("javax.persistence.jdbc.password", "password"); + //properties.setProperty("ping_interval", "500000"); + BackUpMonitor bum = BackUpMonitor.getInstance(null, "brms_test" , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoResource() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", "test"); + properties.setProperty("javax.persistence.jdbc.password", "password"); + //properties.setProperty("ping_interval", "500000"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), null , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoProperties() throws Exception{ + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , null, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoHandler() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", "test"); + properties.setProperty("javax.persistence.jdbc.password", "password"); + //properties.setProperty("ping_interval", "500000"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, null); + assertNull(bum); + } +} |