From 8bad2ad828fad2f5f99a9a291ca0f5c51b62e4ca Mon Sep 17 00:00:00 2001 From: "waqas.ikram" Date: Wed, 30 May 2018 09:48:40 +0100 Subject: Fixing Sonar bugs and code smells Change-Id: I661cd409d01320fe11a29b7ea72b9e8f70e72a6c Issue-ID: POLICY-856 Signed-off-by: waqas.ikram --- .../model/basicmodel/concepts/ApexException.java | 4 +- .../basicmodel/concepts/ApexRuntimeException.java | 6 +- .../model/basicmodel/handling/ApexModelWriter.java | 69 ++++++++++---------- .../contextmodel/concepts/AxContextAlbums.java | 67 +++++++++++--------- .../model/enginemodel/concepts/AxEngineStats.java | 10 ++- .../enginemodel/concepts/TestEngineStats.java | 4 +- .../apex/model/modelapi/impl/ApexModelImpl.java | 29 --------- .../model/modelapi/impl/ContextAlbumFacade.java | 2 +- .../apex/model/modelapi/impl/PolicyFacade.java | 73 +++++++--------------- .../apex/model/modelapi/impl/TaskFacade.java | 32 +++------- .../apex/model/modelapi/TestApexModelAPI.java | 1 - .../model/policymodel/concepts/AxPolicies.java | 23 ++++--- .../apex/model/utilities/CollectionUtils.java | 2 +- .../policy/apex/model/utilities/TextFileUtils.java | 28 +++------ .../policy/apex/model/utilities/TreeMapUtils.java | 22 +++---- .../apex/model/utilities/TextFileUtilsTest.java | 25 ++++---- 16 files changed, 167 insertions(+), 230 deletions(-) (limited to 'model') 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 2dcbf7bcf..896f72a89 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 @@ public class ApexException extends Exception { 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 class ApexException extends Exception { */ public ApexException(final String message) { super(message); + this.object = null; } /** @@ -59,6 +60,7 @@ public class ApexException extends Exception { */ 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 f3db3ae60..c3ecd2fd8 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 @@ public class ApexRuntimeException extends RuntimeException { 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 class ApexRuntimeException extends RuntimeException { */ public ApexRuntimeException(final String message) { super(message); + this.object = null; } /** @@ -59,6 +60,7 @@ public class ApexRuntimeException extends RuntimeException { */ 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 180c2447a..7e56b18ae 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.DocumentBuilderFactory; 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 @@ import org.w3c.dom.Document; * @param the type of Apex concept to write, must be a sub class of {@link AxConcept} */ public class ApexModelWriter { - 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 @@ public class ApexModelWriter { 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 @@ public class ApexModelWriter { 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 class ApexModelWriter { 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 @@ public class ApexModelWriter { if (jsonOutput) { writeJSON(concept, apexConceptWriter); - } - else { + } else { writeXML(concept, apexConceptWriter); } } @@ -204,38 +200,44 @@ public class ApexModelWriter { 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 @@ public class ApexModelWriter { 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 f9d34cef6..a6e2ad9ac 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.basicmodel.concepts.AxValidationResult.Validat 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. *

- * 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 { private static final long serialVersionUID = -4844259809024470975L; @@ -83,8 +84,8 @@ public final class AxContextAlbums extends AxConcept implements AxConceptGetter< // @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 @@ public final class AxContextAlbums extends AxConcept implements AxConceptGetter< } /** - * 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 @@ public final class AxContextAlbums extends AxConcept implements AxConceptGetter< } /** - * 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 @@ public final class AxContextAlbums extends AxConcept implements AxConceptGetter< /* * (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 @@ public final class AxContextAlbums extends AxConcept implements AxConceptGetter< 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 @@ public final class AxContextAlbums extends AxConcept implements AxConceptGetter< return result; } + private void validateContextAlbumKey(final AxValidationResult result, + final Entry 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 @@ public final class AxContextAlbums extends AxConcept implements AxConceptGetter< /* * (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 @@ public final class AxContextAlbums extends AxConcept implements AxConceptGetter< /* * (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 @@ public final class AxContextAlbums extends AxConcept implements AxConceptGetter< /* * (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 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 b7593e751..b35492356 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 @@ public class AxEngineStats extends AxConcept { 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 f5fdcbb1f..2d20964f5 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 @@ public class TestEngineStats { } stats.executionExit(); final double avExecutionTime = stats.getAverageExecutionTime(); - System.err.println(avExecutionTime); assertTrue(avExecutionTime >= 2.0 && avExecutionTime < 3.0); stats.engineStop(); @@ -179,6 +178,8 @@ public class TestEngineStats { 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 @@ public class TestEngineStats { 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 5303e9502..738178d17 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 @@ import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; * @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; @@ -1180,30 +1175,6 @@ public final class ApexModelImpl implements ApexModel { return modelHandlerFacade.mergeWithString(otherModelString, keepOriginal); } - /* - * (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) * 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 57d05025a..afd518d7a 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 @@ public class ContextAlbumFacade { 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 f33627e44..97bf3da0d 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 @@ public class PolicyFacade { final ApexAPIResult result = new ApexAPIResult(); boolean found = false; - for (final Entry taskReferenceEntry : state.getTaskReferences() - .entrySet()) { - if (taskName == null) { - result.addMessage(new ApexModelStringWriter(false) - .writeString(taskReferenceEntry.getKey(), AxArtifactKey.class, jsonMode)); - result.addMessage(new ApexModelStringWriter(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 taskReferences = state.getTaskReferences(); + for (final Entry 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(false) - .writeString(taskReferenceEntry.getKey(), AxArtifactKey.class, jsonMode)); - result.addMessage(new ApexModelStringWriter(false) - .writeString(taskReferenceEntry.getValue(), AxStateTaskReference.class, jsonMode)); + result.addMessage(new ApexModelStringWriter(false).writeString(key, AxArtifactKey.class, + jsonMode)); + result.addMessage(new ApexModelStringWriter(false).writeString(value, + AxStateTaskReference.class, jsonMode)); } if (found) { return result; @@ -1183,15 +1175,8 @@ public class PolicyFacade { final Set 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 @@ public class PolicyFacade { final ApexAPIResult result = new ApexAPIResult(); boolean found = false; for (final AxArtifactKey albumKey : state.getContextAlbumReferences()) { - if (contextAlbumName == null) { - result.addMessage(new ApexModelStringWriter(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(false).writeString(albumKey, - AxArtifactKey.class, jsonMode)); - found = true; - } + result.addMessage(new ApexModelStringWriter(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 @@ public class PolicyFacade { final Set deleteSet = new TreeSet<>(); for (final AxArtifactKey albumKey : state.getContextAlbumReferences()) { - if (contextAlbumName == null) { - deleteSet.add(albumKey); - continue; - } + + if ((contextAlbumName != null && !albumKey.getName().equals(contextAlbumName)) + || (contextAlbumVersion != null && !albumKey.getVersion().equals(contextAlbumVersion))) { - 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 923814daf..dd00da7d4 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 @@ public class TaskFacade { final ApexAPIResult result = new ApexAPIResult(); boolean found = false; for (final AxArtifactKey albumKey : task.getContextAlbumReferences()) { - if (contextAlbumName == null) { - result.addMessage(new ApexModelStringWriter(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(false).writeString(albumKey, - AxArtifactKey.class, jsonMode)); - found = true; - } + result.addMessage(new ApexModelStringWriter(false).writeString(albumKey, + AxArtifactKey.class, jsonMode)); + found = true; } if (!found) { return new ApexAPIResult(ApexAPIResult.RESULT.CONCEPT_DOES_NOT_EXIST, @@ -861,18 +852,11 @@ public class TaskFacade { final Set 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 52029d3a4..68341249c 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 @@ public class TestApexModelAPI { 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 248e4fdae..1937edac0 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 @@ public class AxPolicies extends AxConcept implements AxConceptGetter { "policyMap may not be empty")); } else { for (final Entry 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 @@ public class AxPolicies extends AxConcept implements AxConceptGetter { return result; } + private void validate(final AxValidationResult result, final Entry 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 fb7207e0b..7ca50a613 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 d05245f23..d119a3a35 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 @@ package org.onap.policy.apex.model.utilities; 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 @@ public abstract class TextFileUtils { 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 @@ public abstract class TextFileUtils { * @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 @@ public abstract class TextFileUtils { * @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 @@ public abstract class TextFileUtils { 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 02ab0dd24..cb0f799a0 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.AbstractMap.SimpleEntry; 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 @@ public abstract class TreeMapUtils { /** * 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 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 List> findMatchingEntries(final TreeMap searchMap, final String word) { + public static List> findMatchingEntries(final NavigableMap searchMap, + final String word) { final List> foundNodes = new ArrayList<>(); // A straight match check @@ -60,8 +62,7 @@ public abstract class TreeMapUtils { String foundKeyword = searchMap.floorKey(word); if (foundKeyword == null) { foundKeyword = searchMap.firstKey(); - } - else { + } else { foundKeyword = searchMap.higherKey(foundKeyword); } @@ -70,8 +71,7 @@ public abstract class TreeMapUtils { 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 4e5cba374..c84ee8618 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.FileInputStream; 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); - + } } -- cgit 1.2.3-korg