diff options
author | waqas.ikram <waqas.ikram@ericsson.com> | 2018-05-28 10:58:07 +0100 |
---|---|---|
committer | waqas.ikram <waqas.ikram@ericsson.com> | 2018-05-28 14:35:30 +0100 |
commit | 55d93a12cc5575c872724f48585304b5eec77fea (patch) | |
tree | ac5e44c5670bbcc5e68cceb1694f87348c371e1b /model/engine-model/src | |
parent | 6029d25f5f3ad43fe02ffe1a4beb1eda0a6ae5e3 (diff) |
Adding policy-model, model-api & engine-model
Change-Id: I56702b8f0953457d493f894d155b2a6ddc87b10c
Issue-ID: POLICY-856
Signed-off-by: waqas.ikram <waqas.ikram@ericsson.com>
Diffstat (limited to 'model/engine-model/src')
10 files changed, 1770 insertions, 0 deletions
diff --git a/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineModel.java b/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineModel.java new file mode 100644 index 000000000..b7733c6a3 --- /dev/null +++ b/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineModel.java @@ -0,0 +1,395 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.enginemodel.concepts; + +import java.text.SimpleDateFormat; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Enumerated; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationMessage; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextModel; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * A container class for an Apex engine model. This class is a container class that allows an Apex + * model to be constructed that contains the current context {@link AxContextModel}, current state + * {@link AxEngineState} and current statistics {@link AxEngineStats} of an Apex engine. This model + * is used by an Apex engine to pass its current execution state to any system that wishes to query + * that information. The time stamp of the engine model is the time at which the state and + * statistics of the engine were read. + * <p> + * Validation checks that the current state {@link AxEngineState} is defined and that the time stamp + * is set on the engine model. + */ +@Entity +@Table(name = "AxEngineModel") +@XmlRootElement(name = "apexEngineModel", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AxEngineModel", namespace = "http://www.onap.org/policy/apex-pdp", + propOrder = {"timestamp", "state", "stats"}) + +public class AxEngineModel extends AxContextModel { + private static final long serialVersionUID = 6381235864606564046L; + private static final int HASH_CODE_PRIME = 32; + + @Column(name = "timestamp") + private long timestamp; + + @Enumerated + @Column(name = "state") + @XmlElement(required = true) + private AxEngineState state; + + // @formatter:off + @JoinColumns({ + @JoinColumn(name = "statsParentKeyName", referencedColumnName = "parentKeyName", updatable = false, + insertable = false), + @JoinColumn(name = "statsParentKeyVersion", referencedColumnName = "parentKeyVersion", updatable = false, + insertable = false), + @JoinColumn(name = "statsParentLocalName ", referencedColumnName = "parentLocalName", updatable = false, + insertable = false), + @JoinColumn(name = "statsLocalName", referencedColumnName = "localName", updatable = false, + insertable = false)}) + private AxEngineStats stats; + // @formatter:on + + /** + * The Default Constructor creates an engine model with a null key and all its fields undefined. + */ + public AxEngineModel() { + this(new AxArtifactKey()); + timestamp = -1; + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxEngineModel(final AxEngineModel copyConcept) { + super(copyConcept); + } + + /** + * The Keyed Constructor creates an engine model with the given key and all its fields + * undefined. + * + * @param key the engine model key + */ + public AxEngineModel(final AxArtifactKey key) { + this(key, new AxContextSchemas(new AxArtifactKey(key.getName() + "_DataTypes", key.getVersion())), + new AxKeyInformation(new AxArtifactKey(key.getName() + "_KeyInfo", key.getVersion())), + new AxContextAlbums(new AxArtifactKey(key.getName() + "_Context", key.getVersion()))); + } + + /** + * This Constructor creates an engine model with its context model data types all defined, the + * state of the engine model is undefined. + * + * @param key the engine model key + * @param contextSchemas the context schemas used by the engine model + * @param keyInformation the key information used by the engine model + * @param contextAlbums the context albums used by the engine model + */ + public AxEngineModel(final AxArtifactKey key, final AxContextSchemas contextSchemas, + final AxKeyInformation keyInformation, final AxContextAlbums contextAlbums) { + this(key, contextSchemas, keyInformation, contextAlbums, AxEngineState.UNDEFINED, + new AxEngineStats(new AxReferenceKey(key, "_EngineStats", key.getVersion()))); + } + + /** + * This Constructor creates an engine model with all its fields defined. + * + * @param key the engine model key + * @param contextSchemas the context schemas used by the engine model + * @param keyInformation the key information used by the engine model + * @param contextAlbums the context albums used by the engine model + * @param state the state of the engine in the engine model + * @param stats the statistics of the engine in the engine model + */ + public AxEngineModel(final AxArtifactKey key, final AxContextSchemas contextSchemas, + final AxKeyInformation keyInformation, final AxContextAlbums contextAlbums, final AxEngineState state, + final AxEngineStats stats) { + super(key, contextSchemas, contextAlbums, keyInformation); + Assertions.argumentNotNull(state, "state may not be null"); + Assertions.argumentNotNull(stats, "stats may not be null"); + + this.state = state; + this.stats = stats; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.contextmodel.concepts.AxContextModel#getKeys() + */ + @Override + public List<AxKey> getKeys() { + final List<AxKey> keyList = super.getKeys(); + keyList.addAll(stats.getKeys()); + return keyList; + } + + /** + * Gets the time stamp at which the engine model measurements were taken. + * + * @return the time stamp at which the engine model measurements were taken + */ + public long getTimestamp() { + return timestamp; + } + + /** + * Gets the time stamp at which the engine model measurements were taken as a string. + * + * @return the time stamp string + */ + public String getTimeStampString() { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(timestamp); + } + + /** + * Sets the time stamp at which the engine model measurements were taken. + * + * @param timestamp the time stamp at which the engine model measurements were taken + */ + public void setTimestamp(final long timestamp) { + this.timestamp = timestamp; + } + + /** + * Gets the state of the engine at the time the measurements were taken. + * + * @return the state of the engine at the time the measurements were taken + */ + public AxEngineState getState() { + return state; + } + + /** + * Sets the state of the engine. + * + * @param state the state of the engine + */ + public void setState(final AxEngineState state) { + Assertions.argumentNotNull(state, "state may not be null"); + this.state = state; + } + + /** + * Gets the statistics of the engine at the time the measurements were taken. + * + * @return the statistics of the engine at the time the measurements were taken + */ + public AxEngineStats getStats() { + return stats; + } + + /** + * Sets the the statistics of the engine. + * + * @param stats the the statistics of the engine + */ + public void setStats(final AxEngineStats stats) { + Assertions.argumentNotNull(stats, "stats may not be null"); + this.stats = stats; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.contextmodel.concepts.AxContextModel#validate(org.onap.policy.apex + * .model .basicmodel.concepts.AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + result = stats.validate(result); + + if (timestamp == -1) { + result.addValidationMessage(new AxValidationMessage(getKey(), this.getClass(), ValidationResult.INVALID, + this.getClass().getSimpleName() + " - timestamp is not set")); + } + + if (state == AxEngineState.UNDEFINED) { + result.addValidationMessage(new AxValidationMessage(getKey(), this.getClass(), ValidationResult.INVALID, + this.getClass().getSimpleName() + " - state is UNDEFINED")); + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.contextmodel.concepts.AxContextModel#clean() + */ + @Override + public void clean() { + super.clean(); + stats.clean(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.contextmodel.concepts.AxContextModel#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append(super.toString()); + builder.append(",timestamp="); + builder.append(timestamp); + builder.append(",state="); + builder.append(state); + builder.append(",stats="); + builder.append(stats); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model. + * basicmodel.concepts.AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept targetObject) { + Assertions.argumentNotNull(targetObject, "target may not be null"); + + final Object copyObject = targetObject; + Assertions.instanceOf(copyObject, AxEngineModel.class); + + final AxEngineModel copy = ((AxEngineModel) copyObject); + super.copyTo(targetObject); + copy.timestamp = timestamp; + copy.setState(state); + copy.setStats(new AxEngineStats(stats)); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.contextmodel.concepts.AxContextModel#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + super.hashCode(); + result = prime * result + (int) (timestamp ^ (timestamp >>> HASH_CODE_PRIME)); + result = prime * result + state.hashCode(); + result = prime * result + stats.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.contextmodel.concepts.AxContextModel#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + throw new IllegalArgumentException("comparison object may not be null"); + } + + if (this == obj) { + return true; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final AxEngineModel other = (AxEngineModel) obj; + if (!super.equals(other)) { + return false; + } + if (timestamp != other.timestamp) { + return false; + } + if (!state.equals(other.state)) { + return false; + } + return stats.equals(other.stats); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.contextmodel.concepts.AxContextModel#compareTo(org.onap.policy. + * apex.model.basicmodel.concepts.AxConcept) + */ + @Override + public int compareTo(final AxConcept otherObj) { + Assertions.argumentNotNull(otherObj, "comparison object may not be null"); + + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxEngineModel other = (AxEngineModel) otherObj; + if (!super.equals(other)) { + return super.compareTo(other); + } + if (timestamp != other.timestamp) { + return (int) (timestamp - other.timestamp); + } + if (!state.equals(other.state)) { + return state.compareTo(other.state); + } + return stats.compareTo(other.stats); + } +} diff --git a/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineState.java b/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineState.java new file mode 100644 index 000000000..f77fe1910 --- /dev/null +++ b/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineState.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.enginemodel.concepts; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; + +/** + * This enumeration indicates the execution state of an Apex engine. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AxEngineState", namespace = "http://www.onap.org/policy/apex-pdp") +public enum AxEngineState { + /** The state of the engine is not known. */ + UNDEFINED, + /** The engine is stopped. */ + STOPPED, + /** The engine is running and is waiting to execute a policy. */ + READY, + /** The engine is running and is executing a policy. */ + EXECUTING, + /** The engine has been ordered to stop and is stoping. */ + STOPPING; +} diff --git a/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineStats.java b/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineStats.java new file mode 100644 index 000000000..b7593e751 --- /dev/null +++ b/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/AxEngineStats.java @@ -0,0 +1,545 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.enginemodel.concepts; + +import java.text.SimpleDateFormat; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.persistence.Transient; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationMessage; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class is a java bean that is used to record statistics on Apex engines as they execute. + * Statistics on the number of events, the amount of time taken to execute the last policy, the + * average policy execution time, the up time of the engine, and the time stamp of the last engine + * start are recorded. + */ + +@Entity +@Table(name = "AxEngineStats") + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "apexEngineStats", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlType(name = "AxEngineStats", namespace = "http://www.onap.org/policy/apex-pdp", propOrder = {"key", "timeStamp", + "eventCount", "lastExecutionTime", "averageExecutionTime", "upTime", "lastStart"}) +public class AxEngineStats extends AxConcept { + private static final long serialVersionUID = -6981129081962785368L; + private static final int HASH_CODE_PRIME = 32; + + @EmbeddedId + @XmlElement(name = "key", required = true) + private AxReferenceKey key; + + @Column + @XmlElement(required = true) + private long timeStamp; + + @Column + @XmlElement(required = true) + private long eventCount; + + @Column + @XmlElement(required = true) + private long lastExecutionTime; + + @Column + @XmlElement(required = true) + private double averageExecutionTime; + + @Column + @XmlElement(required = true) + private long upTime; + + @Transient + private transient long lastEnterTime; + + @Column + @XmlElement(required = true) + private long lastStart; + + /** + * The Default Constructor creates an engine statistics instance with a null key and with all + * values cleared. + */ + public AxEngineStats() { + this(new AxReferenceKey()); + timeStamp = 0; + eventCount = 0; + lastExecutionTime = 0; + averageExecutionTime = 0; + upTime = 0; + lastEnterTime = 0; + lastStart = 0; + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxEngineStats(final AxEngineStats copyConcept) { + super(copyConcept); + } + + /** + * The Keyed Constructor creates an engine statistics instance with the given key and all values + * cleared. + * + * @param key the key + */ + public AxEngineStats(final AxReferenceKey key) { + this(key, 0, 0, 0, 0, 0, 0); + } + + /** + * This Constructor creates an engine statistics instance with all its fields set. + * + * @param key the engine statistics key + * @param timeStamp the time stamp at which the statistics were recorded + * @param eventCount the number of events processed by the engine + * @param lastExecutionTime the amount of time taken to execute the last policy + * @param averageExecutionTime the average amount of time taken to execute a policy + * @param upTime the time that has elapsed since the policy engine was started + * @param lastStart the time at which the policy engine was last started + */ + public AxEngineStats(final AxReferenceKey key, final long timeStamp, final long eventCount, + final long lastExecutionTime, final double averageExecutionTime, final long upTime, final long lastStart) { + super(); + Assertions.argumentNotNull(key, "key may not be null"); + + this.key = key; + this.timeStamp = timeStamp; + this.eventCount = eventCount; + this.lastExecutionTime = lastExecutionTime; + this.averageExecutionTime = averageExecutionTime; + this.upTime = upTime; + this.lastStart = lastStart; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxReferenceKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List<AxKey> getKeys() { + return key.getKeys(); + } + + /** + * Sets the engine statistics key. + * + * @param key the engine statistics key + */ + public void setKey(final AxReferenceKey key) { + Assertions.argumentNotNull(key, "key may not be null"); + this.key = key; + } + + /** + * Gets the time stamp at which the statistics were recorded. + * + * @return the time stamp at which the statistics were recorded + */ + public long getTimeStamp() { + return timeStamp; + } + + /** + * Gets the time stamp at which the statistics were recorded as a string. + * + * @return the time stamp at which the statistics were recorded as a string + */ + public String getTimeStampString() { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(timeStamp); + } + + /** + * Sets the time stamp at which the statistics were recorded. + * + * @param timeStamp the time stamp at which the statistics were recorded + */ + public void setTimeStamp(final long timeStamp) { + this.timeStamp = timeStamp; + } + + /** + * Gets the number of events processed by the engine. + * + * @return the number of events processed by the engine + */ + public long getEventCount() { + return eventCount; + } + + /** + * Sets the number of events processed by the engine. + * + * @param eventCount the number of events processed by the engine + */ + public void setEventCount(final long eventCount) { + this.eventCount = eventCount; + } + + /** + * Gets the amount of time taken to execute the last policy. + * + * @return the amount of time taken to execute the last policy + */ + public long getLastExecutionTime() { + return lastExecutionTime; + } + + /** + * Sets the amount of time taken to execute the last policy. + * + * @param lastExecutionTime the amount of time taken to execute the last policy + */ + public void setLastExecutionTime(final long lastExecutionTime) { + this.lastExecutionTime = lastExecutionTime; + } + + /** + * Gets the average amount of time taken to execute a policy. + * + * @return the average amount of time taken to execute a policy + */ + public double getAverageExecutionTime() { + return averageExecutionTime; + } + + /** + * Sets the average amount of time taken to execute a policy. + * + * @param averageExecutionTime the average amount of time taken to execute a policy + */ + public void setAverageExecutionTime(final double averageExecutionTime) { + this.averageExecutionTime = averageExecutionTime; + } + + /** + * Gets the time that has elapsed since the policy engine was started. + * + * @return the time that has elapsed since the policy engine was started + */ + public long getUpTime() { + if (this.getLastStart() != 0) { + return upTime + (timeStamp - this.getLastStart()); + } + return upTime; + } + + /** + * Sets the time that has elapsed since the policy engine was started. + * + * @param upTime the time that has elapsed since the policy engine was started + */ + public void setUpTime(final long upTime) { + this.upTime = upTime; + } + + /** + * Sets the time at which the policy engine was last started. + * + * @param lastStart the time at which the policy engine was last started + */ + private void setLastStart(final long lastStart) { + this.lastStart = lastStart; + } + + /** + * Gets the time at which the policy engine was last started. + * + * @return the time at which the policy engine was last started + */ + private long getLastStart() { + return lastStart; + } + + /** + * Resets all the statistic values to zero. + */ + public synchronized void reset() { + timeStamp = 0; + eventCount = 0; + lastExecutionTime = 0; + averageExecutionTime = 0; + upTime = 0; + lastEnterTime = 0; + lastStart = 0; + } + + /** + * Updates the statistics when called, used by the Apex engine when it starts executing a + * policy. + * + * @param eventkey the key of the event that is being executed + */ + public synchronized void executionEnter(final AxArtifactKey eventkey) { + final long now = System.currentTimeMillis(); + eventCount++; + if (eventCount < 0) { + eventCount = 2; + } + lastEnterTime = now; + timeStamp = now; + } + + /** + * Updates the statistics when called, used by the Apex engine when it completes executing a + * policy. + */ + public synchronized void executionExit() { + final long now = System.currentTimeMillis(); + lastExecutionTime = now - lastEnterTime; + + averageExecutionTime = ((averageExecutionTime * (eventCount - 1.0)) + lastExecutionTime) / eventCount; + lastEnterTime = 0; + timeStamp = System.currentTimeMillis(); + } + + /** + * Updates the statistics when called, used by the Apex engine when it is started. + */ + public synchronized void engineStart() { + final long now = System.currentTimeMillis(); + timeStamp = now; + this.setLastStart(now); + } + + /** + * Updates the statistics when called, used by the Apex engine when it is stopped. + */ + public synchronized void engineStop() { + final long now = System.currentTimeMillis(); + timeStamp = now; + upTime += (timeStamp - this.getLastStart()); + this.setLastStart(0); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model. + * basicmodel.concepts.AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult result) { + if (key.equals(AxReferenceKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + + return key.validate(result); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("engineKey="); + builder.append(key); + builder.append(",timeStamp="); + builder.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(timeStamp)); + builder.append(",eventCount="); + builder.append(eventCount); + builder.append(",lastExecutionTime="); + builder.append(lastExecutionTime); + builder.append(",averageExecutionTime="); + builder.append(averageExecutionTime); + builder.append(",upTime="); + builder.append(getUpTime()); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model. + * basicmodel.concepts.AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept targetObject) { + Assertions.argumentNotNull(targetObject, "target may not be null"); + + final Object copyObject = targetObject; + Assertions.instanceOf(copyObject, AxEngineStats.class); + + final AxEngineStats copy = ((AxEngineStats) copyObject); + copy.setKey(new AxReferenceKey(key)); + copy.setTimeStamp(timeStamp); + copy.setEventCount(eventCount); + copy.setLastExecutionTime(lastExecutionTime); + copy.setAverageExecutionTime(averageExecutionTime); + copy.setUpTime(upTime); + copy.setLastStart(lastStart); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + (int) (timeStamp ^ (timeStamp >>> HASH_CODE_PRIME)); + result = prime * result + (int) (eventCount ^ (eventCount >>> HASH_CODE_PRIME)); + result = prime * result + (int) (lastExecutionTime ^ (lastExecutionTime >>> HASH_CODE_PRIME)); + result = prime * result + ((int) averageExecutionTime ^ ((int) averageExecutionTime >>> HASH_CODE_PRIME)); + result = prime * result + (int) (upTime ^ (upTime >>> HASH_CODE_PRIME)); + result = prime * result + (int) (getLastStart() ^ (getLastStart() >>> HASH_CODE_PRIME)); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final AxEngineStats other = (AxEngineStats) obj; + if (!key.equals(other.key)) { + return false; + } + if (timeStamp != other.timeStamp) { + return false; + } + if (eventCount != other.eventCount) { + return false; + } + if (lastExecutionTime != other.lastExecutionTime) { + return false; + } + if (averageExecutionTime != other.averageExecutionTime) { + return false; + } + if (upTime != other.upTime) { + return false; + } + return getLastStart() == other.getLastStart(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return -1; + } + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxEngineStats other = (AxEngineStats) otherObj; + if (!key.equals(other.key)) { + return key.compareTo(other.key); + } + if (timeStamp != other.timeStamp) { + return (int) (timeStamp - other.timeStamp); + } + if (eventCount != other.eventCount) { + return (int) (eventCount - other.eventCount); + } + if (lastExecutionTime != other.lastExecutionTime) { + return (int) (lastExecutionTime - other.lastExecutionTime); + } + if (averageExecutionTime != other.averageExecutionTime) { + return (int) (averageExecutionTime - other.averageExecutionTime); + } + if (upTime != other.upTime) { + return (int) (upTime - other.upTime); + } + if (getLastStart() != other.getLastStart()) { + return (int) (getLastStart() - other.getLastStart()); + } + + return 0; + } +} diff --git a/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/package-info.java b/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/package-info.java new file mode 100644 index 000000000..ea47c6993 --- /dev/null +++ b/model/engine-model/src/main/java/org/onap/policy/apex/model/enginemodel/concepts/package-info.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Contains the concepts required to receive state information and statistcs from running APEX + * engines. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +@XmlSchema(namespace = "http://www.onap.org/policy/apex-pdp", elementFormDefault = XmlNsForm.QUALIFIED, + xmlns = {@XmlNs(namespaceURI = "http://www.onap.org/policy/apex-pdp", prefix = "")}) + +package org.onap.policy.apex.model.enginemodel.concepts; + +import javax.xml.bind.annotation.XmlNs; +import javax.xml.bind.annotation.XmlNsForm; +import javax.xml.bind.annotation.XmlSchema; diff --git a/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/concepts/TestEngineModel.java b/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/concepts/TestEngineModel.java new file mode 100644 index 000000000..86530462c --- /dev/null +++ b/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/concepts/TestEngineModel.java @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.enginemodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestEngineModel { + + @Test + public void testEnginetModel() { + assertNotNull(new AxEngineModel()); + assertNotNull(new AxEngineModel(new AxArtifactKey())); + assertNotNull(new AxEngineModel(new AxArtifactKey(), new AxContextSchemas(), new AxKeyInformation(), + new AxContextAlbums())); + assertNotNull(new AxEngineModel(new AxArtifactKey(), new AxContextSchemas(), new AxKeyInformation(), + new AxContextAlbums(), AxEngineState.UNDEFINED, new AxEngineStats())); + + final AxArtifactKey modelKey = new AxArtifactKey("ModelName", "0.0.1"); + final AxArtifactKey schemasKey = new AxArtifactKey("SchemasKey", "0.0.1"); + final AxArtifactKey albumKey = new AxArtifactKey("AlbumKey", "0.0.1"); + final AxArtifactKey keyInfoKey = new AxArtifactKey("SchemasKey", "0.0.1"); + final AxEngineStats stats = new AxEngineStats(new AxReferenceKey(modelKey, "EngineStats")); + final AxEngineStats otherStats = new AxEngineStats(); + otherStats.setAverageExecutionTime(100); + + final AxEngineModel model = new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.READY, stats); + model.register(); + + try { + model.setKey(null); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertEquals("key may not be null", e.getMessage()); + } + + model.setKey(modelKey); + assertEquals("ModelName:0.0.1", model.getKey().getID()); + assertEquals("ModelName:0.0.1", model.getKeys().get(0).getID()); + + final long timestamp = System.currentTimeMillis(); + model.setTimestamp(timestamp); + assertEquals(timestamp, model.getTimestamp()); + model.setTimestamp(-1); + assertTrue(model.getTimeStampString().matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.\\d{3}")); + + try { + model.setState(null); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertEquals("state may not be null", e.getMessage()); + } + + for (final AxEngineState state : AxEngineState.values()) { + model.setState(state); + assertEquals(state, model.getState()); + } + + model.setState(AxEngineState.READY); + assertEquals(AxEngineState.READY, model.getState()); + + try { + model.setStats(null); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertEquals("stats may not be null", e.getMessage()); + } + + model.setStats(stats); + assertEquals(stats, model.getStats()); + + model.clean(); + assertNotNull(model); + assertEquals("AxEngineModel:(AxEngineModel:(AxEngineModel:(key=A", model.toString().substring(0, 50)); + + final AxEngineModel clonedModel = new AxEngineModel(model); + + assertFalse(model.hashCode() == 0); + + assertTrue(model.equals(model)); + assertTrue(model.equals(clonedModel)); + assertFalse(model.equals("Hello")); + assertFalse(model.equals(new AxEngineModel(new AxArtifactKey()))); + assertFalse(model.equals(new AxEngineModel(new AxArtifactKey(), new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.READY, stats))); + assertFalse(model.equals(new AxEngineModel(modelKey, new AxContextSchemas(), new AxKeyInformation(keyInfoKey), + new AxContextAlbums(albumKey), AxEngineState.READY, stats))); + assertFalse(model.equals(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), new AxKeyInformation(), + new AxContextAlbums(albumKey), AxEngineState.READY, stats))); + assertFalse(model.equals(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(), AxEngineState.READY, stats))); + assertFalse(model.equals(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.STOPPED, stats))); + assertFalse(model.equals(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.READY, otherStats))); + model.setTimestamp(timestamp); + assertFalse(model.equals(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.READY, stats))); + model.setTimestamp(0); + assertTrue(model.equals(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.READY, stats))); + + model.setTimestamp(-1); + assertEquals(0, model.compareTo(model)); + assertEquals(0, model.compareTo(clonedModel)); + assertNotEquals(0, model.compareTo(new AxArtifactKey())); + assertFalse(model.equals(new AxEngineModel(new AxArtifactKey()))); + assertNotEquals(0, model.compareTo(new AxEngineModel(new AxArtifactKey(), new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.READY, stats))); + assertNotEquals(0, model.compareTo(new AxEngineModel(modelKey, new AxContextSchemas(), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.READY, stats))); + assertNotEquals(0, model.compareTo(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(), new AxContextAlbums(albumKey), AxEngineState.READY, stats))); + assertNotEquals(0, model.compareTo(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(), AxEngineState.READY, stats))); + assertNotEquals(0, model.compareTo(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.STOPPED, stats))); + assertNotEquals(0, model.compareTo(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.READY, otherStats))); + model.setTimestamp(timestamp); + assertNotEquals(0, model.compareTo(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.READY, stats))); + model.setTimestamp(0); + assertEquals(0, model.compareTo(new AxEngineModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxContextAlbums(albumKey), AxEngineState.READY, stats))); + + model.setTimestamp(timestamp); + AxValidationResult result = new AxValidationResult(); + result = model.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + model.setTimestamp(-1); + result = new AxValidationResult(); + result = model.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + model.setTimestamp(timestamp); + result = new AxValidationResult(); + result = model.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + model.setState(AxEngineState.UNDEFINED); + result = new AxValidationResult(); + result = model.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + model.setState(AxEngineState.READY); + result = new AxValidationResult(); + result = model.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + } +} diff --git a/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/concepts/TestEngineStats.java b/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/concepts/TestEngineStats.java new file mode 100644 index 000000000..f5fdcbb1f --- /dev/null +++ b/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/concepts/TestEngineStats.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.enginemodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestEngineStats { + + @Test + public void testEngineStats() { + assertNotNull(new AxEngineStats()); + assertNotNull(new AxEngineStats(new AxReferenceKey())); + + final AxReferenceKey statsKey = new AxReferenceKey("EngineKey", "0.0.1", "EngineStats"); + final AxEngineStats stats = new AxEngineStats(statsKey); + + try { + stats.setKey(null); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertEquals("key may not be null", e.getMessage()); + } + + stats.setKey(statsKey); + assertEquals("EngineKey:0.0.1:NULL:EngineStats", stats.getKey().getID()); + assertEquals("EngineKey:0.0.1:NULL:EngineStats", stats.getKeys().get(0).getID()); + + stats.setAverageExecutionTime(123.45); + assertEquals(new Double(123.45), new Double(stats.getAverageExecutionTime())); + + stats.setEventCount(987); + assertEquals(987, stats.getEventCount()); + + final long lastExecutionTime = System.currentTimeMillis(); + stats.setLastExecutionTime(lastExecutionTime); + assertEquals(lastExecutionTime, stats.getLastExecutionTime()); + + final long timestamp = System.currentTimeMillis(); + stats.setTimeStamp(timestamp); + assertEquals(timestamp, stats.getTimeStamp()); + assertNotNull(stats.getTimeStampString()); + + final long upTime = System.currentTimeMillis() - timestamp; + stats.setUpTime(upTime); + assertEquals(upTime, stats.getUpTime()); + + stats.engineStart(); + assertTrue(stats.getUpTime() > -1); + stats.engineStop(); + assertTrue(stats.getUpTime() >= 0); + + stats.engineStop(); + + stats.reset(); + + stats.setEventCount(-2); + stats.executionEnter(new AxArtifactKey()); + assertEquals(2, stats.getEventCount()); + + stats.setEventCount(10); + stats.executionEnter(new AxArtifactKey()); + assertEquals(11, stats.getEventCount()); + + stats.reset(); + stats.engineStart(); + stats.setEventCount(4); + stats.executionEnter(new AxArtifactKey()); + try { + Thread.sleep(10); + } catch (final Exception e) { + fail("test should not throw an exeption"); + } + stats.executionExit(); + final double avExecutionTime = stats.getAverageExecutionTime(); + System.err.println(avExecutionTime); + assertTrue(avExecutionTime >= 2.0 && avExecutionTime < 3.0); + stats.engineStop(); + + AxValidationResult result = new AxValidationResult(); + result = stats.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + stats.setKey(new AxReferenceKey()); + result = new AxValidationResult(); + result = stats.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + stats.setKey(statsKey); + result = new AxValidationResult(); + result = stats.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + stats.clean(); + stats.reset(); + + final AxEngineStats clonedStats = new AxEngineStats(stats); + assertEquals("AxEngineStats:(engineKey=AxReferenceKey:(parentKey", clonedStats.toString().substring(0, 50)); + + assertNotNull(stats.getKeys()); + + assertFalse(stats.hashCode() == 0); + + assertTrue(stats.equals(stats)); + assertTrue(stats.equals(clonedStats)); + assertFalse(stats.equals(null)); + assertFalse(stats.equals("Hello")); + assertFalse(stats.equals(new AxEngineStats(new AxReferenceKey()))); + + assertEquals(0, stats.compareTo(stats)); + assertEquals(0, stats.compareTo(clonedStats)); + assertNotEquals(0, stats.compareTo(new AxArtifactKey())); + assertNotEquals(0, stats.compareTo(null)); + assertNotEquals(0, stats.compareTo(new AxEngineStats(new AxReferenceKey()))); + + stats.setTimeStamp(1); + assertFalse(stats.equals(new AxEngineStats(statsKey))); + assertNotEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + stats.setTimeStamp(0); + assertTrue(stats.equals(new AxEngineStats(statsKey))); + assertEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + + stats.setEventCount(1); + assertFalse(stats.equals(new AxEngineStats(statsKey))); + assertNotEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + stats.setEventCount(0); + assertTrue(stats.equals(new AxEngineStats(statsKey))); + assertEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + + stats.setLastExecutionTime(1); + assertFalse(stats.equals(new AxEngineStats(statsKey))); + assertNotEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + stats.setLastExecutionTime(0); + assertTrue(stats.equals(new AxEngineStats(statsKey))); + assertEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + + stats.setAverageExecutionTime(1); + assertFalse(stats.equals(new AxEngineStats(statsKey))); + assertNotEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + stats.setAverageExecutionTime(0); + assertTrue(stats.equals(new AxEngineStats(statsKey))); + assertEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + + stats.setUpTime(1); + assertFalse(stats.equals(new AxEngineStats(statsKey))); + assertNotEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + stats.setUpTime(0); + assertTrue(stats.equals(new AxEngineStats(statsKey))); + assertEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + + stats.engineStart(); + assertFalse(stats.equals(new AxEngineStats(statsKey))); + final AxEngineStats newStats = new AxEngineStats(statsKey); + newStats.setTimeStamp(stats.getTimeStamp()); + assertFalse(stats.equals(newStats)); + assertNotEquals(0, stats.compareTo(newStats)); + stats.engineStop(); + stats.reset(); + assertTrue(stats.equals(new AxEngineStats(statsKey))); + assertEquals(0, stats.compareTo(new AxEngineStats(statsKey))); + } +} diff --git a/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/handling/TestApexEngineModel.java b/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/handling/TestApexEngineModel.java new file mode 100644 index 000000000..c1e6f3f37 --- /dev/null +++ b/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/handling/TestApexEngineModel.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.enginemodel.handling; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.DAOParameters; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel; + +public class TestApexEngineModel { + private Connection connection; + TestApexModel<AxEngineModel> testApexModel; + + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel<AxEngineModel>(AxEngineModel.class, new TestApexEngineModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testModelValid() throws Exception { + final AxValidationResult result = testApexModel.testApexModelValid(); + assertTrue(result.toString().equals(VALID_MODEL_STRING)); + } + + @Test + public void testModelVaidateInvalidModel() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateInvalidModel(); + assertTrue(result.toString().equals(INVALID_MODEL_STRING)); + } + + @Test + public void testModelVaidateMalstructured() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateMalstructured(); + assertTrue(result.toString().equals(INVALID_MODEL_MALSTRUCTURED_STRING)); + } + + @Test + public void testModelWriteReadXML() throws Exception { + testApexModel.testApexModelWriteReadXML(); + } + + @Test + public void testModelWriteReadJSON() throws Exception { + testApexModel.testApexModelWriteReadJSON(); + } + + @Test + public void testModelWriteReadJPA() throws Exception { + final DAOParameters daoParameters = new DAOParameters(); + daoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + daoParameters.setPersistenceUnit("DAOTest"); + + testApexModel.testApexModelWriteReadJPA(daoParameters); + } + + private static final String VALID_MODEL_STRING = "***validation of model successful***"; + + private static final String INVALID_MODEL_STRING = "\n" + "***validation of model failed***\n" + + "AxArtifactKey:(name=AnEngine,version=0.0.1):org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel:INVALID:AxEngineModel - state is UNDEFINED\n" + + "********************************"; + + private static final String INVALID_MODEL_MALSTRUCTURED_STRING = "\n" + "***validation of model failed***\n" + + "AxArtifactKey:(name=AnEngine,version=0.0.1):org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel:INVALID:AxEngineModel - timestamp is not set\n" + + "AxArtifactKey:(name=AnEngine,version=0.0.1):org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel:INVALID:AxEngineModel - state is UNDEFINED\n" + + "********************************"; +} diff --git a/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/handling/TestApexEngineModelCreator.java b/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/handling/TestApexEngineModelCreator.java new file mode 100644 index 000000000..4a4a0cc88 --- /dev/null +++ b/model/engine-model/src/test/java/org/onap/policy/apex/model/enginemodel/handling/TestApexEngineModelCreator.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.enginemodel.handling; + +import java.util.UUID; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel; +import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState; +import org.onap.policy.apex.model.enginemodel.concepts.AxEngineStats; + +public class TestApexEngineModelCreator implements TestApexModelCreator<AxEngineModel> { + + @Override + public AxEngineModel getModel() { + final AxContextSchema schema0 = new AxContextSchema(new AxArtifactKey("StringType", "0.0.1"), "Java", + "org.onap.policy.apex.model.enginemodel.concepts.TestContextItem000"); + final AxContextSchema schema1 = new AxContextSchema(new AxArtifactKey("MapType", "0.0.1"), "Java", + "org.onap.policy.apex.model.enginemodel.concepts.TestContextItem00A"); + + final AxContextSchemas schemas = new AxContextSchemas(new AxArtifactKey("ContextSchemas", "0.0.1")); + schemas.getSchemasMap().put(schema0.getKey(), schema0); + schemas.getSchemasMap().put(schema1.getKey(), schema1); + + final AxContextAlbum album0 = + new AxContextAlbum(new AxArtifactKey("contextAlbum0", "0.0.1"), "APPLICATION", true, schema1.getKey()); + + final AxContextAlbums albums = new AxContextAlbums(new AxArtifactKey("context", "0.0.1")); + albums.getAlbumsMap().put(album0.getKey(), album0); + + final AxEngineModel engineModel = new AxEngineModel(new AxArtifactKey("AnEngine", "0.0.1")); + engineModel.setSchemas(schemas); + engineModel.setAlbums(albums); + engineModel.setTimestamp(System.currentTimeMillis()); + engineModel.setState(AxEngineState.EXECUTING); + engineModel.setStats(new AxEngineStats(new AxReferenceKey(engineModel.getKey(), "EngineStats"), + System.currentTimeMillis(), 100, 205, 200, 12345, 9876)); + engineModel.getKeyInformation().generateKeyInfo(engineModel); + + final AxValidationResult result = new AxValidationResult(); + engineModel.validate(result); + + return engineModel; + } + + @Override + public AxEngineModel getInvalidModel() { + final AxEngineModel engineModel = getModel(); + + engineModel.setTimestamp(System.currentTimeMillis()); + engineModel.setState(AxEngineState.UNDEFINED); + engineModel.setStats(new AxEngineStats(new AxReferenceKey(engineModel.getKey(), "EngineStats"), + System.currentTimeMillis(), 100, 205, 200, 12345, 9876)); + engineModel.getKeyInformation().generateKeyInfo(engineModel); + + return engineModel; + } + + public AxEngineModel getMalstructuredModel() { + final AxEngineModel engineModel = getModel(); + + engineModel.setTimestamp(-1); + engineModel.setState(AxEngineState.UNDEFINED); + + return engineModel; + } + + @Override + public AxEngineModel getObservationModel() { + final AxEngineModel engineModel = getModel(); + + final AxContextSchema schema0 = new AxContextSchema(new AxArtifactKey("StringType", "0.0.1"), "Java", + "org.onap.policy.apex.model.enginemodel.concepts.TestContextItem000"); + final AxContextSchema schema1 = new AxContextSchema(new AxArtifactKey("MapType", "0.0.1"), "Java", + "org.onap.policy.apex.model.enginemodel.concepts.TestContextItem00A"); + + engineModel.getKeyInformation().getKeyInfoMap().put(schema0.getKey(), + new AxKeyInfo(schema0.getKey(), UUID.fromString("00000000-0000-0000-0000-000000000001"), "")); + engineModel.getKeyInformation().getKeyInfoMap().put(schema1.getKey(), + new AxKeyInfo(schema1.getKey(), UUID.fromString("00000000-0000-0000-0000-000000000002"), "")); + + return engineModel; + } + + @Override + public AxEngineModel getWarningModel() { + final AxEngineModel engineModel = getModel(); + + final AxContextSchema schema0 = new AxContextSchema(new AxArtifactKey("StringType", "0.0.1"), "Java", + "org.onap.policy.apex.model.enginemodel.concepts.TestContextItem000"); + final AxContextSchema schema1 = new AxContextSchema(new AxArtifactKey("MapType", "0.0.1"), "Java", + "org.onap.policy.apex.model.enginemodel.concepts.TestContextItem00A"); + + engineModel.getKeyInformation().getKeyInfoMap().put(schema0.getKey(), + new AxKeyInfo(schema0.getKey(), UUID.fromString("00000000-0000-0000-0000-000000000000"), "")); + engineModel.getKeyInformation().getKeyInfoMap().put(schema1.getKey(), + new AxKeyInfo(schema1.getKey(), UUID.fromString("00000000-0000-0000-0000-000000000001"), "")); + + return engineModel; + } +} diff --git a/model/engine-model/src/test/resources/META-INF/persistence.xml b/model/engine-model/src/test/resources/META-INF/persistence.xml new file mode 100644 index 000000000..717d1a540 --- /dev/null +++ b/model/engine-model/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + Copyright (C) 2016-2018 Ericsson. 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. + + SPDX-License-Identifier: Apache-2.0 + ============LICENSE_END========================================================= +--> + +<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> + <persistence-unit name="DAOTest" transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + + <class>org.onap.policy.apex.model.basicmodel.dao.converters.CDATAConditioner</class> + <class>org.onap.policy.apex.model.basicmodel.dao.converters.UUID2String</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.AxConcept</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.AxModel</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.TestEntity</class> + <class>org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema</class> + <class>org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas</class> + <class>org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum</class> + <class>org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums</class> + <class>org.onap.policy.apex.model.contextmodel.concepts.AxContextModel</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxField</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxInputField</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxOutputField</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxEvent</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxEvents</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxEventModel</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxLogic</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxTaskLogic</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxTask</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxTasks</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxStateFinalizerLogic</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxStateOutput</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxState</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxPolicy</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxPolicies</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel</class> + <class>org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel</class> + <class>org.onap.policy.apex.model.enginemodel.concepts.AxEngineStats</class> + + <properties> + <property name="javax.persistence.jdbc.url" value="jdbc:derby:memory:apex_test" /> + <property name="javax.persistence.target-database" value="Derby" /> + <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" /> + + <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> + <property name="eclipselink.ddl-generation.output-mode" value="database" /> + <property name="eclipselink.logging.level" value="INFO" /> + </properties> + </persistence-unit> +</persistence> diff --git a/model/engine-model/src/test/resources/logback-test.xml b/model/engine-model/src/test/resources/logback-test.xml new file mode 100644 index 000000000..034511335 --- /dev/null +++ b/model/engine-model/src/test/resources/logback-test.xml @@ -0,0 +1,70 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + Copyright (C) 2016-2018 Ericsson. 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. + + SPDX-License-Identifier: Apache-2.0 + ============LICENSE_END========================================================= +--> + +<configuration> + + <contextName>Apex</contextName> + <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /> + <property name="LOG_DIR" value="${java.io.tmpdir}/apex_logging/" /> + + <!-- USE FOR STD OUT ONLY --> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <Pattern>%d %contextName [%t] %level %logger{36} - %msg%n</Pattern> + </encoder> + </appender> + + <root level="INFO"> + <appender-ref ref="STDOUT" /> + </root> + + <logger name="org.infinispan" level="INFO" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + + <logger name="org.apache.zookeeper.ClientCnxn" level="OFF" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + + <appender name="FILE" class="ch.qos.logback.core.FileAppender"> + <file>${LOG_DIR}/apex.log</file> + <encoder> + <pattern>%d %-5relative [procId=${processId}] [%thread] %-5level + %logger{26} - %msg %n %ex{full}</pattern> + </encoder> + </appender> + + <appender name="CTXT_FILE" class="ch.qos.logback.core.FileAppender"> + <file>${LOG_DIR}/apex_ctxt.log</file> + <encoder> + <pattern>%d %-5relative [procId=${processId}] [%thread] %-5level + %logger{26} - %msg %n %ex{full}</pattern> + </encoder> + </appender> + + <logger name="org.onap.policy.apex.core.context.impl.monitoring" level="TRACE" additivity="false"> + <appender-ref ref="CTXT_FILE" /> + </logger> + + <logger name="org.onap.policy.apex.core.context" level="INFO" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> +</configuration> |