aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/aai/modelloader/entity/model/ModelArtifactParser.java
blob: de99880e93a1f2d26151772000f26a1bda9eccb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017-2018 European Software Marketing Ltd.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.aai.modelloader.entity.model;

import java.io.StringWriter;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collector;
import java.util.stream.IntStream;
import javax.xml.XMLConstants;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.onap.aai.cl.api.Logger;
import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.modelloader.entity.Artifact;
import org.onap.aai.modelloader.service.ModelLoaderMsgs;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ModelArtifactParser extends AbstractModelArtifactParser {

    public static final String MODEL_VER = "model-ver";
    public static final String MODEL_VERSION_ID = "model-version-id";
    public static final String MODEL_INVARIANT_ID = "model-invariant-id";
    private static final String RELATIONSHIP = "relationship";
    private static final String MODEL_ELEMENT_RELATIONSHIP_KEY = "model." + MODEL_INVARIANT_ID;
    private static final String MODEL_VER_ELEMENT_RELATIONSHIP_KEY = MODEL_VER + "." + MODEL_VERSION_ID;

    private static Logger logger = LoggerFactory.getInstance().getLogger(ModelArtifactParser.class.getName());

    @Override
    void parseNode(Node node, IModelArtifact model) {
        if (node.getNodeName().equalsIgnoreCase(MODEL_INVARIANT_ID)
                || node.getNodeName().equalsIgnoreCase(MODEL_VERSION_ID)) {
            setVersionId(model, node);
        } else if (node.getNodeName().equalsIgnoreCase(RELATIONSHIP)) {
            parseRelationshipNode(node, model);
        } else {
            if (node.getNodeName().equalsIgnoreCase(MODEL_VER)) {
                String modelVersion;
                try {
                    modelVersion = nodeToString(node);
                    ((ModelArtifact) model).setModelVer(modelVersion);
                } catch (TransformerException e) {
                    logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, "Failed to parse resource version for input: " + node.toString());
                }
                if (((ModelArtifact) model).getModelNamespace() != null
                        && !((ModelArtifact) model).getModelNamespace().isEmpty()) {
                    Element e = (Element) node;
                    e.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns",
                            ((ModelArtifact) model).getModelNamespace());
                }
            }

            parseChildNodes(node, model);
        }
    }

    private String nodeToString(Node node) throws TransformerException {
        StringWriter sw = new StringWriter();
        TransformerFactory transFact = TransformerFactory.newInstance();
        transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
        transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
        Transformer t = transFact.newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.transform(new DOMSource(node), new StreamResult(sw));
        return sw.toString();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void setVersionId(IModelArtifact model, Node node) {
        if (MODEL_INVARIANT_ID.equals(node.getNodeName())) {
            ((ModelArtifact) model).setModelInvariantId(node.getTextContent().trim());
        } else if (MODEL_VERSION_ID.equals(node.getNodeName())) {
            ((ModelArtifact) model).setModelVerId(node.getTextContent().trim());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    ModelId buildModelId(NodeList nodeList) {
        return IntStream.range(0, nodeList.getLength()).mapToObj(nodeList::item)
                .filter(childNode -> childNode.getNodeName().equalsIgnoreCase(RELATIONSHIP_DATA))
                .map(this::getRelationship) //
                .collect(Collector.of(ModelId::new, ModelId::setRelationship, (m, p) -> m));
    }

    /**
     * Find a relationship key and value pair from the children of the supplied node.
     *
     * @param node containing children storing relationship keys and values
     * @return a pair containing a relationship key and its value. Note: if multiple relationships are found, existing
     *         values stored in the pair will be overwritten.
     */
    private Pair<String, String> getRelationship(Node node) {
        Objects.requireNonNull(node);
        NodeList relDataChildList = node.getChildNodes();
        Objects.requireNonNull(relDataChildList);

        return IntStream.range(0, relDataChildList.getLength()).mapToObj(relDataChildList::item)
                .filter(this::filterRelationshipNode)
                .collect(Collector.of(Pair::new, applyRelationshipValue, (p, n) -> p));
    }

    /**
     * This method is responsible for creating an instance of {@link ModelArtifactParser.ModelId}
     *
     * @return IModelId instance of {@link ModelArtifactParser.ModelId}
     */
    @Override
    IModelId createModelIdInstance() {
        return new ModelId();
    }

    private class ModelId implements IModelId {

        private String modelInvariantIdValue;
        private String modelVersionIdValue;

        @Override
        public void setRelationship(Pair<String, String> p) {
            if (p.getKey().equalsIgnoreCase(MODEL_VER_ELEMENT_RELATIONSHIP_KEY)) {
                modelVersionIdValue = p.getValue();
            } else if (p.getKey().equalsIgnoreCase(MODEL_ELEMENT_RELATIONSHIP_KEY)) {
                modelInvariantIdValue = p.getValue();
            }
        }

        @Override
        public boolean defined() {
            return modelInvariantIdValue != null && modelVersionIdValue != null;
        }

        @Override
        public String toString() {
            return modelInvariantIdValue + "|" + modelVersionIdValue;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    String buildArtifactParseExceptionMessage(String artifactName, String localisedMessage) {
        return "Unable to parse legacy model artifact " + artifactName + ": " + localisedMessage;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    IModelArtifact createModelArtifactInstance() {
        return new ModelArtifact();
    }

    @Override
    boolean modelIsValid(IModelArtifact model) {
        return ((ModelArtifact) model).getModelInvariantId() != null && ((ModelArtifact) model).getModelVerId() != null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    boolean processParsedModel(List<Artifact> modelList, String artifactName, IModelArtifact model) {
        boolean valid = false;

        if (model != null) {
            ModelArtifact modelImpl = (ModelArtifact) model;
            logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Model parsed =====>>>> " + "Model-invariant-Id: "
                    + modelImpl.getModelInvariantId() + " Model-Version-Id: " + modelImpl.getModelVerId());
            modelList.add(modelImpl);
            valid = true;
        } else {
            logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, "Unable to parse artifact " + artifactName);
        }

        return valid;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    String getModelElementRelationshipKey() {
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    String getVersionIdNodeName() {
        return null;
    }
}