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