625145f634f5faee0e1789aa5a949858b1baa54b
[aai/model-loader.git] / src / main / java / org / openecomp / modelloader / entity / model / ModelArtifactParser.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * MODEL LOADER SERVICE
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.modelloader.entity.model;
22
23 import org.openecomp.cl.api.Logger;
24 import org.openecomp.cl.eelf.LoggerFactory;
25 import org.openecomp.modelloader.entity.Artifact;
26 import org.openecomp.modelloader.entity.ArtifactType;
27 import org.openecomp.modelloader.service.ModelLoaderMsgs;
28 import org.openecomp.modelloader.util.JsonXmlConverter;
29 import org.w3c.dom.Document;
30 import org.w3c.dom.Node;
31 import org.w3c.dom.NodeList;
32 import org.xml.sax.InputSource;
33
34 import java.io.StringReader;
35 import java.io.StringWriter;
36 import java.util.ArrayList;
37 import java.util.List;
38
39 import javax.xml.parsers.DocumentBuilder;
40 import javax.xml.parsers.DocumentBuilderFactory;
41 import javax.xml.transform.OutputKeys;
42 import javax.xml.transform.Transformer;
43 import javax.xml.transform.TransformerException;
44 import javax.xml.transform.TransformerFactory;
45 import javax.xml.transform.dom.DOMSource;
46 import javax.xml.transform.stream.StreamResult;
47
48 public class ModelArtifactParser {
49
50   private static String MODELS_ELEMENT = "models";
51   private static String MODEL_ELEMENT = "model";
52   private static String NAMED_QUERIES_ELEMENT = "named-queries";
53   private static String NAMED_QUERY_ELEMENT = "named-query";
54   private static String MODEL_NAME_VERSION_ID = "model-name-version-id";
55   private static String NAMED_QUERY_VERSION_ID = "named-query-uuid";
56   private static String RELATIONSHIP_DATA = "relationship-data";
57   private static String RELATIONSHIP_KEY = "relationship-key";
58   private static String RELATIONSHIP_VALUE = "relationship-value";
59   private static String MODEL_ELEMENT_RELATIONSHIP_KEY = "model.model-name-version-id";
60
61   private static Logger logger = LoggerFactory.getInstance()
62       .getLogger(ModelArtifactParser.class.getName());
63
64   /**
65    * This method parses the given artifact payload in byte array format and
66    * generates a list of model artifacts according to the content.
67    * 
68    * @param artifactPayload
69    *          artifact content to be parsed
70    * @param artifactName
71    *          name of the artifact
72    * @return a list of model artifacts
73    */
74   public List<Artifact> parse(byte[] artifactPayload, String artifactName) {
75     String payload = new String(artifactPayload);
76     List<Artifact> modelList = new ArrayList<Artifact>();
77
78     try {
79       // Artifact could be JSON or XML
80       if (JsonXmlConverter.isValidJson(payload)) {
81         payload = JsonXmlConverter.convertJsonToXml(payload);
82       }
83
84       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
85       DocumentBuilder builder = factory.newDocumentBuilder();
86       InputSource is = new InputSource(new StringReader(payload));
87       Document doc = builder.parse(is);
88
89       if ((doc.getDocumentElement().getNodeName().equalsIgnoreCase(MODEL_ELEMENT))
90           || (doc.getDocumentElement().getNodeName().equalsIgnoreCase(NAMED_QUERY_ELEMENT))) {
91         ModelArtifact model = parseModel(doc.getDocumentElement(), payload);
92         if (model != null) {
93           modelList.add(model);
94         } else {
95           // TODO: A WARN message?
96           logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
97               "Unable to parse artifact " + artifactName);
98         }
99       } else if ((doc.getDocumentElement().getNodeName().equalsIgnoreCase(MODELS_ELEMENT))
100           || (doc.getDocumentElement().getNodeName().equalsIgnoreCase(NAMED_QUERIES_ELEMENT))) {
101         // The complete set of models/named-queries were contained in this
102         // artifact
103         NodeList nodeList = doc.getDocumentElement().getChildNodes();
104         for (int i = 0; i < nodeList.getLength(); i++) {
105           Node childNode = nodeList.item(i);
106           if ((childNode.getNodeName().equalsIgnoreCase(MODEL_ELEMENT))
107               || (childNode.getNodeName().equalsIgnoreCase(NAMED_QUERY_ELEMENT))) {
108             String modelPayload = nodeToString(childNode);
109             ModelArtifact model = parseModel(childNode, modelPayload);
110             if (model != null) {
111               modelList.add(model);
112             } else {
113               // TODO: A WARN message?
114               logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
115                   "Unable to parse artifact " + artifactName);
116               modelList.clear();
117               break;
118             }
119           }
120         }
121       }
122     } catch (Exception ex) {
123       // This may not be an error. We may be receiving an artifact that is
124       // unrelated
125       // to models. In this case, we just ignore it.
126       // TODO: A WARN message?
127       logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT,
128           "Unable to parse artifact " + artifactName + ": " + ex.getLocalizedMessage());
129     }
130
131     return modelList;
132   }
133
134   private ModelArtifact parseModel(Node modelNode, String payload) {
135     ModelArtifact model = new ModelArtifact();
136     model.setPayload(payload);
137
138     if (modelNode.getNodeName().equalsIgnoreCase(MODEL_ELEMENT)) {
139       model.setType(ArtifactType.MODEL);
140     } else {
141       model.setType(ArtifactType.NAMED_QUERY);
142     }
143
144     parseNode(modelNode, model);
145
146     if (model.getNameVersionId() == null) {
147       return null;
148     }
149
150     return model;
151   }
152
153   private void parseNode(Node node, ModelArtifact model) {
154     if (node.getNodeName().equalsIgnoreCase(MODEL_NAME_VERSION_ID)) {
155       model.setNameVersionId(node.getTextContent().trim());
156     } else if (node.getNodeName().equalsIgnoreCase(NAMED_QUERY_VERSION_ID)) {
157       model.setNameVersionId(node.getTextContent().trim());
158     } else if (node.getNodeName().equalsIgnoreCase(RELATIONSHIP_DATA)) {
159       parseRelationshipNode(node, model);
160     } else {
161       NodeList nodeList = node.getChildNodes();
162       for (int i = 0; i < nodeList.getLength(); i++) {
163         Node childNode = nodeList.item(i);
164         parseNode(childNode, model);
165       }
166     }
167   }
168
169   private void parseRelationshipNode(Node node, ModelArtifact model) {
170     String key = null;
171     String value = null;
172
173     NodeList nodeList = node.getChildNodes();
174     for (int i = 0; i < nodeList.getLength(); i++) {
175       Node childNode = nodeList.item(i);
176       if (childNode.getNodeName().equalsIgnoreCase(RELATIONSHIP_KEY)) {
177         key = childNode.getTextContent().trim();
178       } else if (childNode.getNodeName().equalsIgnoreCase(RELATIONSHIP_VALUE)) {
179         value = childNode.getTextContent().trim();
180       }
181     }
182
183     if ((key != null) && (key.equalsIgnoreCase(MODEL_ELEMENT_RELATIONSHIP_KEY))) {
184       if (value != null) {
185         model.addDependentModelId(value);
186       }
187     }
188   }
189
190   private String nodeToString(Node node) throws TransformerException {
191     StringWriter sw = new StringWriter();
192     Transformer transfomer = TransformerFactory.newInstance().newTransformer();
193     transfomer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
194     transfomer.transform(new DOMSource(node), new StreamResult(sw));
195     return sw.toString();
196   }
197 }