Merge "Fixing Sonar bugs and code smells"
diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexException.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexException.java
index 2dcbf7b..896f72a 100644
--- a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexException.java
+++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexException.java
@@ -29,7 +29,7 @@
private static final long serialVersionUID = -8507246953751956974L;
// The object on which the exception was thrown
- private transient Object object = null;
+ private final transient Object object;
/**
* Instantiates a new apex exception.
@@ -38,6 +38,7 @@
*/
public ApexException(final String message) {
super(message);
+ this.object = null;
}
/**
@@ -59,6 +60,7 @@
*/
public ApexException(final String message, final Exception e) {
super(message, e);
+ this.object = null;
}
/**
diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexRuntimeException.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexRuntimeException.java
index f3db3ae..c3ecd2f 100644
--- a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexRuntimeException.java
+++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexRuntimeException.java
@@ -1,4 +1,4 @@
-/*
+/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* ================================================================================
@@ -29,7 +29,7 @@
private static final long serialVersionUID = -8507246953751956974L;
// The object on which the exception was thrown
- private transient Object object = null;
+ private final transient Object object;
/**
* Instantiates a new apex runtime exception.
@@ -38,6 +38,7 @@
*/
public ApexRuntimeException(final String message) {
super(message);
+ this.object = null;
}
/**
@@ -59,6 +60,7 @@
*/
public ApexRuntimeException(final String message, final Exception e) {
super(message, e);
+ this.object = null;
}
/**
diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriter.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriter.java
index 180c244..7e56b18 100644
--- a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriter.java
+++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriter.java
@@ -1,4 +1,4 @@
-/*
+/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* ================================================================================
@@ -33,6 +33,7 @@
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
@@ -55,11 +56,11 @@
* @param <C> the type of Apex concept to write, must be a sub class of {@link AxConcept}
*/
public class ApexModelWriter<C extends AxConcept> {
- private static final String CONCEPT_MAY_NOT_BE_NULL = "concept may not be null";
+ private static final String CONCEPT_MAY_NOT_BE_NULL = "concept may not be null";
private static final String CONCEPT_WRITER_MAY_NOT_BE_NULL = "concept writer may not be null";
- private static final String CONCEPT_STREAM_MAY_NOT_BE_NULL = "concept stream may not be null";
+ private static final String CONCEPT_STREAM_MAY_NOT_BE_NULL = "concept stream may not be null";
- // Get a reference to the logger
+ // Get a reference to the logger
private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelWriter.class);
// Writing as JSON or XML
@@ -91,8 +92,7 @@
marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
- }
- catch (final JAXBException e) {
+ } catch (final JAXBException e) {
LOGGER.error("JAXB marshaller creation exception", e);
throw new ApexModelException("JAXB marshaller creation exception", e);
}
@@ -130,17 +130,14 @@
try {
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
- }
- catch (final Exception e) {
+ } catch (final Exception e) {
LOGGER.warn("JAXB error setting marshaller for JSON output", e);
throw new ApexModelException("JAXB error setting marshaller for JSON output", e);
}
- }
- else {
+ } else {
try {
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
- }
- catch (final Exception e) {
+ } catch (final Exception e) {
LOGGER.warn("JAXB error setting marshaller for XML output", e);
throw new ApexModelException("JAXB error setting marshaller for XML output", e);
}
@@ -157,7 +154,7 @@
public void write(final C concept, final OutputStream apexConceptStream) throws ApexModelException {
Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL);
Assertions.argumentNotNull(apexConceptStream, CONCEPT_STREAM_MAY_NOT_BE_NULL);
-
+
this.write(concept, new OutputStreamWriter(apexConceptStream));
}
@@ -185,8 +182,7 @@
if (jsonOutput) {
writeJSON(concept, apexConceptWriter);
- }
- else {
+ } else {
writeXML(concept, apexConceptWriter);
}
}
@@ -204,38 +200,44 @@
LOGGER.debug("writing Apex concept XML . . .");
try {
- // Write the concept into a DOM document, then transform to add CDATA fields and pretty print, then write out the result
+ // Write the concept into a DOM document, then transform to add CDATA fields and pretty
+ // print, then write out the result
final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
final Document document = docBuilderFactory.newDocumentBuilder().newDocument();
// Marshal the concept into the empty document.
marshaller.marshal(concept, document);
- // Transform the DOM to the output stream
- final TransformerFactory transformerFactory = TransformerFactory.newInstance();
- final Transformer domTransformer = transformerFactory.newTransformer();
-
- // Pretty print
- try {
- domTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
- // May fail if not using XALAN XSLT engine. But not in any way vital
- domTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
- }
- catch (final Exception ignore) {
- // We ignore exceptions here and catch errors below
- }
+ final Transformer domTransformer = getTransformer();
// Convert the cDataFieldSet into a space delimited string
- domTransformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cDataFieldSet.toString().replaceAll("[\\[\\]\\,]", " "));
+ domTransformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS,
+ cDataFieldSet.toString().replaceAll("[\\[\\]\\,]", " "));
domTransformer.transform(new DOMSource(document), new StreamResult(apexConceptWriter));
- }
- catch (JAXBException | TransformerException | ParserConfigurationException e) {
+ } catch (JAXBException | TransformerException | ParserConfigurationException e) {
LOGGER.warn("Unable to marshal Apex concept XML", e);
throw new ApexModelException("Unable to marshal Apex concept XML", e);
}
LOGGER.debug("wrote Apex concept XML");
}
+
+ private Transformer getTransformer() throws TransformerConfigurationException {
+ // Transform the DOM to the output stream
+ final TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ final Transformer domTransformer = transformerFactory.newTransformer();
+
+ // Pretty print
+ try {
+ domTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ // May fail if not using XALAN XSLT engine. But not in any way vital
+ domTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
+ } catch (final Exception ignore) {
+ LOGGER.trace("Unable to set indent property...");
+ }
+ return domTransformer;
+ }
+
/**
* This method writes the Apex concept into a writer in JSON format.
*
@@ -250,8 +252,7 @@
try {
marshaller.marshal(concept, apexConceptWriter);
- }
- catch (final JAXBException e) {
+ } catch (final JAXBException e) {
LOGGER.warn("Unable to marshal Apex concept JSON", e);
throw new ApexModelException("Unable to marshal Apex concept JSON", e);
}
diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbums.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbums.java
index f9d34ce..a6e2ad9 100644
--- a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbums.java
+++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbums.java
@@ -51,21 +51,22 @@
import org.onap.policy.apex.model.utilities.Assertions;
/**
- * This class is a context album container and holds a map of the context albums for an entire Apex model. All Apex
- * models that use context albums must have an {@link AxContextAlbums} field. The {@link AxContextAlbums} class
- * implements the helper methods of the {@link AxConceptGetter} interface to allow {@link AxContextAlbum} instances to
- * be retrieved by calling methods directly on this class without referencing the contained map.
+ * This class is a context album container and holds a map of the context albums for an entire Apex
+ * model. All Apex models that use context albums must have an {@link AxContextAlbums} field. The
+ * {@link AxContextAlbums} class implements the helper methods of the {@link AxConceptGetter}
+ * interface to allow {@link AxContextAlbum} instances to be retrieved by calling methods directly
+ * on this class without referencing the contained map.
* <p>
- * Validation checks that the container key is not null. An observation is issued if no context albums are defined in
- * the container. If context albums do exist, they are checked to ensure that keys and values are not null and that the
- * map key matches the key in the map value for all album entries. Each context album entry is then validated
- * individually.
+ * Validation checks that the container key is not null. An observation is issued if no context
+ * albums are defined in the container. If context albums do exist, they are checked to ensure that
+ * keys and values are not null and that the map key matches the key in the map value for all album
+ * entries. Each context album entry is then validated individually.
*/
@Entity
@Table(name = "AxContextAlbums")
@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "AxContextAlbums", namespace = "http://www.onap.org/policy/apex-pdp", propOrder = { "key", "albums" })
+@XmlType(name = "AxContextAlbums", namespace = "http://www.onap.org/policy/apex-pdp", propOrder = {"key", "albums"})
public final class AxContextAlbums extends AxConcept implements AxConceptGetter<AxContextAlbum> {
private static final long serialVersionUID = -4844259809024470975L;
@@ -83,8 +84,8 @@
// @formatter:on
/**
- * The Default Constructor creates a {@link AxContextAlbums} object with a null artifact key and creates an empty
- * context album map.
+ * The Default Constructor creates a {@link AxContextAlbums} object with a null artifact key and
+ * creates an empty context album map.
*/
public AxContextAlbums() {
this(new AxArtifactKey());
@@ -100,8 +101,8 @@
}
/**
- * The Key Constructor creates a {@link AxContextAlbums} object with the given artifact key and creates an empty
- * context album map.
+ * The Key Constructor creates a {@link AxContextAlbums} object with the given artifact key and
+ * creates an empty context album map.
*
* @param key the key of the context album container
*/
@@ -126,9 +127,10 @@
}
/**
- * When a model is unmarshalled from disk or from the database, the context album map is returned as a raw hash map.
- * This method is called by JAXB after unmarshaling and is used to convert the hash map to a {@link NavigableMap} so
- * that it will work with the {@link AxConceptGetter} interface.
+ * When a model is unmarshalled from disk or from the database, the context album map is
+ * returned as a raw hash map. This method is called by JAXB after unmarshaling and is used to
+ * convert the hash map to a {@link NavigableMap} so that it will work with the
+ * {@link AxConceptGetter} interface.
*
* @param u the unmarshaler that is unmarshaling the model
* @param parent the parent object of this object in the unmarshaler
@@ -234,7 +236,8 @@
/*
* (non-Javadoc)
*
- * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.
+ * @see
+ * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.
* basicmodel.concepts.AxValidationResult)
*/
@Override
@@ -260,13 +263,7 @@
result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
"value on context album entry " + contextAlbumEntry.getKey() + " may not be null"));
} else {
- if (!contextAlbumEntry.getKey().equals(contextAlbumEntry.getValue().getKey())) {
- result.addValidationMessage(
- new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "key on context album entry key " + contextAlbumEntry.getKey()
- + " does not equal context album value key "
- + contextAlbumEntry.getValue().getKey()));
- }
+ validateContextAlbumKey(result, contextAlbumEntry);
result = contextAlbumEntry.getValue().validate(result);
}
@@ -276,10 +273,20 @@
return result;
}
+ private void validateContextAlbumKey(final AxValidationResult result,
+ final Entry<AxArtifactKey, AxContextAlbum> contextAlbumEntry) {
+ if (!contextAlbumEntry.getKey().equals(contextAlbumEntry.getValue().getKey())) {
+ result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
+ "key on context album entry key " + contextAlbumEntry.getKey()
+ + " does not equal context album value key " + contextAlbumEntry.getValue().getKey()));
+ }
+ }
+
/*
* (non-Javadoc)
*
- * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.
+ * @see
+ * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.
* basicmodel.concepts.AxConcept)
*/
@Override
@@ -371,8 +378,8 @@
/*
* (non-Javadoc)
*
- * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#get(org.onap.policy.apex.model.
- * basicmodel.concepts.AxArtifactKey)
+ * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#get(org.onap.policy.apex.
+ * model.basicmodel.concepts.AxArtifactKey)
*/
@Override
public AxContextAlbum get(final AxArtifactKey conceptKey) {
@@ -392,7 +399,8 @@
/*
* (non-Javadoc)
*
- * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#get(java.lang.String, java.lang.String)
+ * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#get(java.lang.String,
+ * java.lang.String)
*/
@Override
public AxContextAlbum get(final String conceptKeyName, final String conceptKeyVersion) {
@@ -413,7 +421,8 @@
/*
* (non-Javadoc)
*
- * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String, java.lang.String)
+ * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String,
+ * java.lang.String)
*/
@Override
public Set<AxContextAlbum> getAll(final String conceptKeyName, final String conceptKeyVersion) {
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
index b7593e7..b354923 100644
--- 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
@@ -530,16 +530,14 @@
if (lastExecutionTime != other.lastExecutionTime) {
return (int) (lastExecutionTime - other.lastExecutionTime);
}
- if (averageExecutionTime != other.averageExecutionTime) {
- return (int) (averageExecutionTime - other.averageExecutionTime);
+ final int result = Double.compare(averageExecutionTime, other.averageExecutionTime);
+ if (result != 0) {
+ return result;
}
if (upTime != other.upTime) {
return (int) (upTime - other.upTime);
}
- if (getLastStart() != other.getLastStart()) {
- return (int) (getLastStart() - other.getLastStart());
- }
- return 0;
+ return Long.compare(lastStart, other.lastStart);
}
}
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
index f5fdcbb..2d20964 100644
--- 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
@@ -104,7 +104,6 @@
}
stats.executionExit();
final double avExecutionTime = stats.getAverageExecutionTime();
- System.err.println(avExecutionTime);
assertTrue(avExecutionTime >= 2.0 && avExecutionTime < 3.0);
stats.engineStop();
@@ -179,6 +178,8 @@
assertTrue(stats.equals(new AxEngineStats(statsKey)));
assertEquals(0, stats.compareTo(new AxEngineStats(statsKey)));
+ assertEquals(-1, stats.compareTo(new AxEngineStats(statsKey, 0, 0, 0, 0.0, 0, 1)));
+
stats.engineStart();
assertFalse(stats.equals(new AxEngineStats(statsKey)));
final AxEngineStats newStats = new AxEngineStats(statsKey);
@@ -190,4 +191,5 @@
assertTrue(stats.equals(new AxEngineStats(statsKey)));
assertEquals(0, stats.compareTo(new AxEngineStats(statsKey)));
}
+
}
diff --git a/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/ApexModelImpl.java b/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/ApexModelImpl.java
index 5303e95..738178d 100644
--- a/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/ApexModelImpl.java
+++ b/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/ApexModelImpl.java
@@ -33,17 +33,12 @@
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public final class ApexModelImpl implements ApexModel {
- private static final int HASH_CODE_PRIME_0 = 31;
- private static final int HASH_CODE_PRIME_1 = 1231;
- private static final int HASH_CODE_PRIME_2 = 1237;
-
// The policy model being acted upon
private AxPolicyModel policyModel = new AxPolicyModel();
// The file name for the loaded file
private String fileName = null;
- // Facade classes for working towards the real Apex model
// @formatter:off
private ModelFacade modelFacade;
private KeyInformationFacade keyInformationFacade;
@@ -1183,30 +1178,6 @@
/*
* (non-Javadoc)
*
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- final int prime = HASH_CODE_PRIME_0;
- int result = 1;
- result = prime * result + ((apexProperties == null) ? 0 : apexProperties.hashCode());
- result = prime * result + ((contextAlbumFacade == null) ? 0 : contextAlbumFacade.hashCode());
- result = prime * result + ((contextSchemaFacade == null) ? 0 : contextSchemaFacade.hashCode());
- result = prime * result + ((eventFacade == null) ? 0 : eventFacade.hashCode());
- result = prime * result + ((fileName == null) ? 0 : fileName.hashCode());
- result = prime * result + (jsonMode ? HASH_CODE_PRIME_1 : HASH_CODE_PRIME_2);
- result = prime * result + ((keyInformationFacade == null) ? 0 : keyInformationFacade.hashCode());
- result = prime * result + ((modelFacade == null) ? 0 : modelFacade.hashCode());
- result = prime * result + ((modelHandlerFacade == null) ? 0 : modelHandlerFacade.hashCode());
- result = prime * result + ((policyFacade == null) ? 0 : policyFacade.hashCode());
- result = prime * result + ((policyModel == null) ? 0 : policyModel.hashCode());
- result = prime * result + ((taskFacade == null) ? 0 : taskFacade.hashCode());
- return result;
- }
-
- /*
- * (non-Javadoc)
- *
* @see org.onap.policy.apex.auth.api.ApexModel#getModel()
*/
@Override
diff --git a/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/ContextAlbumFacade.java b/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/ContextAlbumFacade.java
index 57d0502..afd518d 100644
--- a/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/ContextAlbumFacade.java
+++ b/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/ContextAlbumFacade.java
@@ -115,7 +115,7 @@
contextAlbum.setItemSchema(schema.getKey());
if (writable != null
- && (writable.trim().equalsIgnoreCase("true") || writable.trim().equalsIgnoreCase("t"))) {
+ && ("true".equalsIgnoreCase(writable.trim()) || "t".equalsIgnoreCase(writable.trim()))) {
contextAlbum.setWritable(true);
} else {
contextAlbum.setWritable(false);
diff --git a/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/PolicyFacade.java b/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/PolicyFacade.java
index f33627e..97bf3da 100644
--- a/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/PolicyFacade.java
+++ b/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/PolicyFacade.java
@@ -20,6 +20,7 @@
package org.onap.policy.apex.model.modelapi.impl;
+import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
@@ -1118,29 +1119,20 @@
final ApexAPIResult result = new ApexAPIResult();
boolean found = false;
- for (final Entry<AxArtifactKey, AxStateTaskReference> taskReferenceEntry : state.getTaskReferences()
- .entrySet()) {
- if (taskName == null) {
- result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false)
- .writeString(taskReferenceEntry.getKey(), AxArtifactKey.class, jsonMode));
- result.addMessage(new ApexModelStringWriter<AxStateTaskReference>(false)
- .writeString(taskReferenceEntry.getValue(), AxStateTaskReference.class, jsonMode));
- found = true;
- continue;
- }
- if (!taskReferenceEntry.getKey().getName().equals(taskName)) {
- continue;
- }
-
- if (taskVersion != null && !taskReferenceEntry.getKey().getVersion().equals(taskVersion)) {
+ final Map<AxArtifactKey, AxStateTaskReference> taskReferences = state.getTaskReferences();
+ for (final Entry<AxArtifactKey, AxStateTaskReference> taskReferenceEntry : taskReferences.entrySet()) {
+ final AxArtifactKey key = taskReferenceEntry.getKey();
+ final AxStateTaskReference value = taskReferenceEntry.getValue();
+ if ((taskName != null && !key.getName().equals(taskName))
+ || (taskVersion != null && !key.getVersion().equals(taskVersion))) {
continue;
}
found = true;
- result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false)
- .writeString(taskReferenceEntry.getKey(), AxArtifactKey.class, jsonMode));
- result.addMessage(new ApexModelStringWriter<AxStateTaskReference>(false)
- .writeString(taskReferenceEntry.getValue(), AxStateTaskReference.class, jsonMode));
+ result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false).writeString(key, AxArtifactKey.class,
+ jsonMode));
+ result.addMessage(new ApexModelStringWriter<AxStateTaskReference>(false).writeString(value,
+ AxStateTaskReference.class, jsonMode));
}
if (found) {
return result;
@@ -1183,15 +1175,8 @@
final Set<AxArtifactKey> deleteSet = new TreeSet<>();
for (final AxArtifactKey taskReferenceKey : state.getTaskReferences().keySet()) {
- if (taskName == null) {
- deleteSet.add(taskReferenceKey);
- continue;
- }
- if (!taskReferenceKey.getName().equals(taskName)) {
- continue;
- }
-
- if (taskVersion != null && !taskReferenceKey.getVersion().equals(taskVersion)) {
+ if ((taskName != null && !taskReferenceKey.getName().equals(taskName))
+ || (taskVersion != null && !taskReferenceKey.getVersion().equals(taskVersion))) {
continue;
}
deleteSet.add(taskReferenceKey);
@@ -1292,22 +1277,13 @@
final ApexAPIResult result = new ApexAPIResult();
boolean found = false;
for (final AxArtifactKey albumKey : state.getContextAlbumReferences()) {
- if (contextAlbumName == null) {
- result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false).writeString(albumKey,
- AxArtifactKey.class, jsonMode));
- found = true;
+ if ((contextAlbumName != null && !albumKey.getName().equals(contextAlbumName))
+ || (contextAlbumVersion != null && !albumKey.getVersion().equals(contextAlbumVersion))) {
continue;
}
-
- if (!albumKey.getName().equals(contextAlbumName)) {
- continue;
- }
-
- if (contextAlbumVersion == null || albumKey.getVersion().equals(contextAlbumVersion)) {
- result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false).writeString(albumKey,
- AxArtifactKey.class, jsonMode));
- found = true;
- }
+ result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false).writeString(albumKey,
+ AxArtifactKey.class, jsonMode));
+ found = true;
}
if (!found) {
return new ApexAPIResult(ApexAPIResult.RESULT.CONCEPT_DOES_NOT_EXIST, CONCEPT + contextAlbumName + ':'
@@ -1351,18 +1327,13 @@
final Set<AxArtifactKey> deleteSet = new TreeSet<>();
for (final AxArtifactKey albumKey : state.getContextAlbumReferences()) {
- if (contextAlbumName == null) {
- deleteSet.add(albumKey);
+
+ if ((contextAlbumName != null && !albumKey.getName().equals(contextAlbumName))
+ || (contextAlbumVersion != null && !albumKey.getVersion().equals(contextAlbumVersion))) {
+
continue;
}
-
- if (!albumKey.getName().equals(contextAlbumName)) {
- continue;
- }
-
- if (contextAlbumVersion == null || albumKey.getVersion().equals(contextAlbumVersion)) {
- deleteSet.add(albumKey);
- }
+ deleteSet.add(albumKey);
}
if (deleteSet.isEmpty()) {
return new ApexAPIResult(ApexAPIResult.RESULT.CONCEPT_DOES_NOT_EXIST, CONCEPT + contextAlbumName + ':'
diff --git a/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/TaskFacade.java b/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/TaskFacade.java
index 923814d..dd00da7 100644
--- a/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/TaskFacade.java
+++ b/model/model-api/src/main/java/org/onap/policy/apex/model/modelapi/impl/TaskFacade.java
@@ -811,22 +811,13 @@
final ApexAPIResult result = new ApexAPIResult();
boolean found = false;
for (final AxArtifactKey albumKey : task.getContextAlbumReferences()) {
- if (contextAlbumName == null) {
- result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false).writeString(albumKey,
- AxArtifactKey.class, jsonMode));
- found = true;
+ if ((contextAlbumName != null && !albumKey.getName().equals(contextAlbumName))
+ || (contextAlbumVersion != null && !albumKey.getVersion().equals(contextAlbumVersion))) {
continue;
}
-
- if (!albumKey.getName().equals(contextAlbumName)) {
- continue;
- }
-
- if (contextAlbumVersion == null || albumKey.getVersion().equals(contextAlbumVersion)) {
- result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false).writeString(albumKey,
- AxArtifactKey.class, jsonMode));
- found = true;
- }
+ result.addMessage(new ApexModelStringWriter<AxArtifactKey>(false).writeString(albumKey,
+ AxArtifactKey.class, jsonMode));
+ found = true;
}
if (!found) {
return new ApexAPIResult(ApexAPIResult.RESULT.CONCEPT_DOES_NOT_EXIST,
@@ -861,18 +852,11 @@
final Set<AxArtifactKey> deleteSet = new TreeSet<>();
for (final AxArtifactKey albumKey : task.getContextAlbumReferences()) {
- if (contextAlbumName == null) {
- deleteSet.add(albumKey);
+ if ((contextAlbumName != null && !albumKey.getName().equals(contextAlbumName))
+ || (contextAlbumVersion != null && !albumKey.getVersion().equals(contextAlbumVersion))) {
continue;
}
-
- if (!albumKey.getName().equals(contextAlbumName)) {
- continue;
- }
-
- if (contextAlbumVersion == null || albumKey.getVersion().equals(contextAlbumVersion)) {
- deleteSet.add(albumKey);
- }
+ deleteSet.add(albumKey);
}
if (deleteSet.isEmpty()) {
diff --git a/model/model-api/src/test/java/org/onap/policy/apex/model/modelapi/TestApexModelAPI.java b/model/model-api/src/test/java/org/onap/policy/apex/model/modelapi/TestApexModelAPI.java
index 52029d3..6834124 100644
--- a/model/model-api/src/test/java/org/onap/policy/apex/model/modelapi/TestApexModelAPI.java
+++ b/model/model-api/src/test/java/org/onap/policy/apex/model/modelapi/TestApexModelAPI.java
@@ -249,7 +249,6 @@
assertEquals(ApexAPIResult.RESULT.SUCCESS, result.getResult());
result = apexModelImpl.mergeWithString(modelString, true);
- System.err.println(result);
assertEquals(ApexAPIResult.RESULT.SUCCESS, result.getResult());
assertNotEquals(0, apexModelImpl.hashCode());
diff --git a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxPolicies.java b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxPolicies.java
index 248e4fd..1937eda 100644
--- a/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxPolicies.java
+++ b/model/policy-model/src/main/java/org/onap/policy/apex/model/policymodel/concepts/AxPolicies.java
@@ -225,19 +225,15 @@
"policyMap may not be empty"));
} else {
for (final Entry<AxArtifactKey, AxPolicy> policyEntry : policyMap.entrySet()) {
- if (policyEntry.getKey().equals(AxArtifactKey.getNullKey())) {
+ final AxArtifactKey entryKey = policyEntry.getKey();
+ if (entryKey.equals(AxArtifactKey.getNullKey())) {
result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "key on policy entry " + policyEntry.getKey() + " may not be the null key"));
+ "key on policy entry " + entryKey + " may not be the null key"));
} else if (policyEntry.getValue() == null) {
result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "value on policy entry " + policyEntry.getKey() + " may not be null"));
+ "value on policy entry " + entryKey + " may not be null"));
} else {
- if (!policyEntry.getKey().equals(policyEntry.getValue().getKey())) {
- result.addValidationMessage(new AxValidationMessage(key, this.getClass(),
- ValidationResult.INVALID, "key on policy entry key " + policyEntry.getKey()
- + " does not equal policy value key " + policyEntry.getValue().getKey()));
- }
-
+ validate(result, policyEntry, entryKey);
result = policyEntry.getValue().validate(result);
}
}
@@ -246,6 +242,15 @@
return result;
}
+ private void validate(final AxValidationResult result, final Entry<AxArtifactKey, AxPolicy> policyEntry,
+ final AxArtifactKey entryKey) {
+ if (!entryKey.equals(policyEntry.getValue().getKey())) {
+ result.addValidationMessage(
+ new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key on policy entry key "
+ + entryKey + " does not equal policy value key " + policyEntry.getValue().getKey()));
+ }
+ }
+
/*
* (non-Javadoc)
*
diff --git a/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/CollectionUtils.java b/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/CollectionUtils.java
index fb7207e..7ca50a6 100644
--- a/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/CollectionUtils.java
+++ b/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/CollectionUtils.java
@@ -1,4 +1,4 @@
-/*
+/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* ================================================================================
diff --git a/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TextFileUtils.java b/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TextFileUtils.java
index d05245f..d119a3a 100644
--- a/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TextFileUtils.java
+++ b/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TextFileUtils.java
@@ -1,4 +1,4 @@
-/*
+/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* ================================================================================
@@ -22,15 +22,15 @@
import java.io.BufferedReader;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
+import java.nio.file.Files;
+import java.nio.file.Paths;
/**
- * The Class TextFileUtils is class that provides useful functions for handling text files. Functions to read and wrtie text files to strings and strings are
- * provided.
+ * The Class TextFileUtils is class that provides useful functions for handling text files.
+ * Functions to read and wrtie text files to strings and strings are provided.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
@@ -38,9 +38,9 @@
private static final int READER_CHAR_BUFFER_SIZE_4096 = 4096;
private TextFileUtils() {
- // This class cannot be initialized
+ // This class cannot be initialized
}
-
+
/**
* Method to return the contents of a text file as a string.
*
@@ -49,12 +49,7 @@
* @throws IOException on errors reading text from the file
*/
public static String getTextFileAsString(final String textFilePath) throws IOException {
- final File textFile = new File(textFilePath);
- final FileInputStream textFileInputStream = new FileInputStream(textFile);
- final byte[] textData = new byte[(int) textFile.length()];
- textFileInputStream.read(textData);
- textFileInputStream.close();
- return new String(textData);
+ return new String(Files.readAllBytes(Paths.get(textFilePath)));
}
/**
@@ -77,9 +72,7 @@
* @throws IOException on errors reading text from the file
*/
public static void putStringAsFile(final String outString, final File textFile) throws IOException {
- final FileOutputStream textFileOutputStream = new FileOutputStream(textFile);
- textFileOutputStream.write(outString.getBytes());
- textFileOutputStream.close();
+ Files.write(textFile.toPath(), outString.getBytes());
}
/**
@@ -110,8 +103,7 @@
if (charsRead > 0) {
builder.append(chars, 0, charsRead);
}
- }
- while (charsRead > 0);
+ } while (charsRead > 0);
return builder.toString();
}
}
diff --git a/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TreeMapUtils.java b/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TreeMapUtils.java
index 02ab0dd..cb0f799 100644
--- a/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TreeMapUtils.java
+++ b/model/utilities/src/main/java/org/onap/policy/apex/model/utilities/TreeMapUtils.java
@@ -1,4 +1,4 @@
-/*
+/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* ================================================================================
@@ -24,10 +24,11 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
-import java.util.TreeMap;
+import java.util.NavigableMap;
/**
- * This class provides utility functions for tree maps. A function to find the nearest match in the tree map to an input string is provided.
+ * This class provides utility functions for tree maps. A function to find the nearest match in the
+ * tree map to an input string is provided.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
@@ -36,18 +37,19 @@
/**
* This class is a utility class that can't be instantiated.
*/
- private TreeMapUtils() {
- }
+ private TreeMapUtils() {}
/**
- * Find the list of entries that matches a given word, for example "p" will match "put", "policy", and "push".
+ * Find the list of entries that matches a given word, for example "p" will match "put",
+ * "policy", and "push".
*
* @param <T> the generic type for the value of the tree map
* @param searchMap the map that the method operates on
* @param word the word to search for
* @return the list of entries in the {@code searchMap} that match the {@code word}
*/
- public static <T> List<Entry<String, T>> findMatchingEntries(final TreeMap<String, T> searchMap, final String word) {
+ public static <T> List<Entry<String, T>> findMatchingEntries(final NavigableMap<String, T> searchMap,
+ final String word) {
final List<Entry<String, T>> foundNodes = new ArrayList<>();
// A straight match check
@@ -60,8 +62,7 @@
String foundKeyword = searchMap.floorKey(word);
if (foundKeyword == null) {
foundKeyword = searchMap.firstKey();
- }
- else {
+ } else {
foundKeyword = searchMap.higherKey(foundKeyword);
}
@@ -70,8 +71,7 @@
if (foundKeyword.startsWith(word)) {
foundNodes.add(new SimpleEntry<>(foundKeyword, searchMap.get(foundKeyword)));
foundKeyword = searchMap.higherKey(foundKeyword);
- }
- else {
+ } else {
break;
}
}
diff --git a/model/utilities/src/test/java/org/onap/policy/apex/model/utilities/TextFileUtilsTest.java b/model/utilities/src/test/java/org/onap/policy/apex/model/utilities/TextFileUtilsTest.java
index 4e5cba3..c84ee86 100644
--- a/model/utilities/src/test/java/org/onap/policy/apex/model/utilities/TextFileUtilsTest.java
+++ b/model/utilities/src/test/java/org/onap/policy/apex/model/utilities/TextFileUtilsTest.java
@@ -1,4 +1,4 @@
-/*
+/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* ================================================================================
@@ -27,26 +27,27 @@
import java.io.IOException;
import org.junit.Test;
-import org.onap.policy.apex.model.utilities.TextFileUtils;
/**
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class TextFileUtilsTest {
+ private static final String FILE_CONTENT = "This is the contents of a text file";
+
@Test
public void test() throws IOException {
- File tempTextFile = File.createTempFile("Test", "txt");
-
- TextFileUtils.putStringAsTextFile("This is the contents of a text file", tempTextFile.getAbsolutePath());
-
- String textFileString0 = TextFileUtils.getTextFileAsString(tempTextFile.getAbsolutePath());
- assertEquals("This is the contents of a text file", textFileString0);
-
- FileInputStream fis = new FileInputStream(tempTextFile);
- String textFileString1 = TextFileUtils.getStreamAsString(fis);
+ final File tempTextFile = File.createTempFile("Test", "txt");
+
+ TextFileUtils.putStringAsTextFile(FILE_CONTENT, tempTextFile.getAbsolutePath());
+
+ final String textFileString0 = TextFileUtils.getTextFileAsString(tempTextFile.getAbsolutePath());
+ assertEquals(FILE_CONTENT, textFileString0);
+
+ final FileInputStream fis = new FileInputStream(tempTextFile);
+ final String textFileString1 = TextFileUtils.getStreamAsString(fis);
assertEquals(textFileString0, textFileString1);
-
+
}
}