Return List<Artifact> in ArtifactDownloadManager
[aai/model-loader.git] / src / main / java / org / onap / aai / modelloader / entity / model / AbstractModelArtifactParser.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.modelloader.entity.model;
22
23 import java.io.StringReader;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Objects;
27 import java.util.function.BiConsumer;
28 import java.util.stream.Collector;
29 import java.util.stream.IntStream;
30 import javax.xml.parsers.DocumentBuilder;
31 import javax.xml.parsers.DocumentBuilderFactory;
32 import org.onap.aai.cl.api.Logger;
33 import org.onap.aai.cl.eelf.LoggerFactory;
34 import org.onap.aai.modelloader.entity.Artifact;
35 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.Element;
38 import org.w3c.dom.Node;
39 import org.w3c.dom.NodeList;
40 import org.xml.sax.InputSource;
41
42 /**
43  * This class provides common behaviour for implementations of IModelParser.
44  *
45  * Some of the common behaviour takes the form of abstract methods that will be implemented in concrete classes.
46  *
47  * Some other behaviour will be overridden in concrete classes.
48  */
49 public abstract class AbstractModelArtifactParser implements IModelParser {
50     private static Logger logger = LoggerFactory.getInstance().getLogger(AbstractModelArtifactParser.class);
51
52     protected static final String RELATIONSHIP_DATA = "relationship-data";
53     private static final String RELATIONSHIP_KEY = "relationship-key";
54     private static final String RELATIONSHIP_VALUE = "relationship-value";
55
56     BiConsumer<Pair<String, String>, Node> applyRelationshipValue = (p, n) -> {
57         if (n.getNodeName().equalsIgnoreCase(RELATIONSHIP_KEY)) {
58             p.setKey(n.getTextContent().trim());
59         } else {
60             p.setValue(n.getTextContent().trim());
61         }
62     };
63
64
65     /**
66      * This method is responsible for parsing the payload to produce a list of artifacts.
67      *
68      * @param artifactPayload the payload to be parsed
69      * @param artifactName the name of the artifact to be parsed
70      * @return List<Artifact> a list of artifacts that have been parsed from the payload.
71      */
72     @Override
73     public List<Artifact> parse(String artifactPayload, String artifactName) {
74         List<Artifact> modelList = new ArrayList<>();
75
76         try {
77             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
78             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
79             DocumentBuilder builder = factory.newDocumentBuilder();
80             InputSource is = new InputSource(new StringReader(artifactPayload));
81             Document doc = builder.parse(is);
82
83             IModelArtifact model = parseModel(doc.getDocumentElement(), artifactPayload);
84
85             boolean success = processParsedModel(modelList, artifactName, model);
86             if (!success) {
87                 modelList = null;
88             }
89         } catch (Exception ex) {
90             logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR,
91                     buildArtifactParseExceptionMessage(artifactName, ex.getLocalizedMessage()));
92         }
93
94         return modelList;
95     }
96
97     private IModelArtifact parseModel(Node modelNode, String payload) {
98         IModelArtifact model = createModelArtifactInstance();
99         model.setPayload(payload);
100
101         Element e = (Element) modelNode;
102         model.setModelNamespace(e.getAttribute("xmlns"));
103
104         parseNode(modelNode, model);
105
106         return modelIsValid(model) ? model : null;
107     }
108
109     /**
110      * This method is responsible for creating a new instance of IModel that represents the model id for a concrete
111      * implementation of IArtifactParser.
112      *
113      * @return IModelArtifact implementation of IModel that represents the model id for a concrete implementation of
114      *         IArtifactParser
115      */
116     abstract IModelArtifact createModelArtifactInstance();
117
118     /**
119      * This method is responsible for the actual parsing of a node.
120      *
121      * It will do one of three things:
122      * <ol>
123      * <li>set the version id if the name of the node is the same as the name of the node that is the version Id</li>
124      * <li>if the node is contains data about the relationship it will parse the node accordingly</li>
125      * <li>if it does neither of option 1 or 2 it will parse the children of this node</li>
126      * </ol>
127      * 
128      * @param node node to be parsed
129      * @param model the model artifact to be updated with either the versionId or details of dependent node
130      */
131     void parseNode(Node node, IModelArtifact model) {
132         if (node.getNodeName().equalsIgnoreCase(getVersionIdNodeName())) {
133             setVersionId(model, node);
134         } else if (node.getNodeName().equalsIgnoreCase(RELATIONSHIP_DATA)) {
135             parseRelationshipNode(node, model);
136         } else {
137             parseChildNodes(node, model);
138         }
139     }
140
141     /**
142      * This method gets the name of the node that acts as the version Id for the node.
143      *
144      * @return String name of the node that acts as the version Id for the node
145      */
146     abstract String getVersionIdNodeName();
147
148     /**
149      * This method is responsible for setting the values on the model artifact that represent the version Id. Each
150      * implementation of a IModelArtifact has its own properties that define the version Id.
151      *
152      * @param model the model artifact upon which the version Id will be set
153      * @param node the source of the data that holds the actual value of the version id to be set on the model artifact
154      */
155     abstract void setVersionId(IModelArtifact model, Node node);
156
157     /**
158      * @param relationshipNode a node containing child nodes storing relationship data
159      * @param model artifact whose dependent node id will be update with any relationship data if it exists
160      */
161     void parseRelationshipNode(Node relationshipNode, IModelArtifact model) {
162         NodeList nodeList = getChildNodes(relationshipNode);
163
164         IModelId modelId = buildModelId(nodeList);
165
166         updateModelsDependentNodeId(model, modelId);
167     }
168
169     private NodeList getChildNodes(Node relationshipNode) {
170         Objects.requireNonNull(relationshipNode);
171         NodeList nodeList = relationshipNode.getChildNodes();
172         Objects.requireNonNull(nodeList);
173
174         return nodeList;
175     }
176
177     /**
178      * This method is responsible for building an instance of IModelId representing the id of the model.
179      *
180      * @param nodeList list of modes used to build the model id.
181      * @return IModelId instance of IModelId representing the id of the model
182      */
183     IModelId buildModelId(NodeList nodeList) {
184         Pair<String, String> relationship = IntStream.range(0, nodeList.getLength()).mapToObj(nodeList::item) //
185                 .filter(this::filterRelationshipNode)
186                 .collect(Collector.of(Pair::new, applyRelationshipValue, (p, n) -> p));
187
188         IModelId modelId = createModelIdInstance();
189         modelId.setRelationship(relationship);
190
191         return modelId;
192     }
193
194     /**
195      * This method tests if a node is either one that either represents a relationship key or a relationship value.
196      *
197      * @param n the node to to be tested
198      * @return <code>true</code> if the node is either represents a relationship key or a relationship value
199      */
200     boolean filterRelationshipNode(Node n) {
201         return n.getNodeName().equalsIgnoreCase(RELATIONSHIP_KEY)
202                 || n.getNodeName().equalsIgnoreCase(RELATIONSHIP_VALUE);
203     }
204
205     /**
206      * This method is responsible for creating an instance of {@link AbstractModelArtifactParser.ModelId}
207      *
208      * @return IModelId instance of {@link AbstractModelArtifactParser.ModelId}
209      */
210     IModelId createModelIdInstance() {
211         return new ModelId();
212     }
213
214     private void updateModelsDependentNodeId(IModelArtifact model, IModelId modelId) {
215         if (modelId.defined()) {
216             model.addDependentModelId(modelId.toString());
217         }
218     }
219
220     /**
221      * This method is responsible for parsing the children of a given node.
222      *
223      * @param node node whose children, if any, should be parsed.
224      * @param model model to be updated as a result of parsing the node
225      */
226     void parseChildNodes(Node node, IModelArtifact model) {
227         NodeList nodeList = node.getChildNodes();
228         for (int i = 0; i < nodeList.getLength(); i++) {
229             Node childNode = nodeList.item(i);
230             parseNode(childNode, model);
231         }
232     }
233
234     /**
235      * Validates if the mode is valid or not by examining specific properties of the model.
236      *
237      * @param model model to be validated
238      * @return <code>true</code> if the mode is valid otherwise <code>false</code>
239      */
240     abstract boolean modelIsValid(IModelArtifact model);
241
242     /**
243      * This method is responsible for building a message used for logging artifact parsing errors.
244      *
245      * @param artifactName the name of the artifact
246      * @param localisedMessage the message associated with the exception that is raised by the error
247      * @return String a message used for logging artifact parsing errors
248      */
249     abstract String buildArtifactParseExceptionMessage(String artifactName, String localisedMessage);
250
251     /**
252      * This method is responsible for either adding the model artifact to the list of model artifacts or reporting an
253      * error.
254      *
255      * If the model is not null then it will be added to the list of artifacts otherwise an error will be logged.
256      *
257      * @param modelList the list of artifacts to which the model will be added if it is not null
258      * @param artifactName the name of the artifact
259      * @param artifactModel the model artifact to be added to the list of model artifacts
260      * @return <code>true/code> if the model is not null otherwise <code>false</code>
261      */
262     abstract boolean processParsedModel(List<Artifact> modelList, String artifactName, IModelArtifact artifactModel);
263
264     private class ModelId implements IModelId {
265         private String modelIdValue;
266
267         @Override
268         public void setRelationship(Pair<String, String> p) {
269             if (getModelElementRelationshipKey().equals(p.getKey())) {
270                 modelIdValue = p.getValue();
271             }
272         }
273
274         @Override
275         public boolean defined() {
276             return modelIdValue != null;
277         }
278
279         @Override
280         public String toString() {
281             return modelIdValue;
282         }
283     }
284
285     /**
286      * This method gets the name of the key of the element relationship for the model.
287      *
288      * @return String name of the key of the element relationship for the model
289      */
290     abstract String getModelElementRelationshipKey();
291 }