Update license files, sonar plugin and fix tests
[aai/aai-common.git] / aai-core / src / main / java / org / openecomp / aai / introspection / MoxyLoader.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.openecomp.aai
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.aai.introspection;
22
23 import java.io.IOException;
24 import java.io.StringReader;
25 import java.util.HashSet;
26 import java.util.Map;
27 import java.util.Set;
28
29 import javax.xml.XMLConstants;
30 import javax.xml.bind.JAXBException;
31 import javax.xml.bind.Unmarshaller;
32 import javax.xml.parsers.DocumentBuilder;
33 import javax.xml.parsers.DocumentBuilderFactory;
34 import javax.xml.parsers.ParserConfigurationException;
35 import javax.xml.transform.stream.StreamSource;
36
37 import org.eclipse.persistence.dynamic.DynamicEntity;
38 import org.eclipse.persistence.jaxb.UnmarshallerProperties;
39 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
40 import org.w3c.dom.Document;
41 import org.w3c.dom.NodeList;
42 import org.xml.sax.SAXException;
43
44 import org.openecomp.aai.exceptions.AAIException;
45 import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException;
46 import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException;
47 import org.openecomp.aai.logging.ErrorLogHelper;
48 import org.openecomp.aai.restcore.MediaType;
49 import org.openecomp.aai.workarounds.NamingExceptions;
50 import com.att.eelf.configuration.EELFLogger;
51 import com.att.eelf.configuration.EELFManager;
52 import com.google.common.base.CaseFormat;
53 import com.google.common.collect.ImmutableMap;
54
55 public class MoxyLoader extends Loader {
56
57         private DynamicJAXBContext jaxbContext = null;
58         private EELFLogger LOGGER = EELFManager.getInstance().getLogger(MoxyLoader.class);
59         private Map<String, Introspector> allObjs = null;
60
61         /**
62          * Instantiates a new moxy loader.
63          *
64          * @param version the version
65          * @param llBuilder the ll builder
66          */
67         protected MoxyLoader(Version version) {
68                 super(version, ModelType.MOXY);
69                 process(version);
70         }
71
72         /**
73          * {@inheritDoc}
74          * @throws AAIUnknownObjectException 
75          */
76         @Override
77         public Introspector introspectorFromName(String name) throws AAIUnknownObjectException {
78
79                 return IntrospectorFactory.newInstance(ModelType.MOXY, objectFromName(name));
80         }
81         
82         /**
83          * {@inheritDoc}
84          */
85         @Override
86         public Object objectFromName(String name) throws AAIUnknownObjectException {
87
88                 final String sanitizedName = NamingExceptions.getInstance().getObjectName(name);
89                 final String upperCamel;
90
91                 //Contains any uppercase, then assume it's upper camel
92                 if (name.matches(".*[A-Z].*")) {
93                         upperCamel = sanitizedName;
94                 } else {
95                         upperCamel = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, sanitizedName);
96                 }
97                 
98                 try {
99                         final DynamicEntity result = jaxbContext.newDynamicEntity(upperCamel);
100
101                         if (result == null) throw new AAIUnknownObjectException("Unrecognized AAI object " + name);
102
103                         return result;
104                 } catch (IllegalArgumentException e) {
105                         //entity does not exist
106                         throw new AAIUnknownObjectException("Unrecognized AAI object " + name, e);
107                 }
108         }
109
110         /**
111          * {@inheritDoc}
112          */
113         @Override
114         protected void process(Version version) {
115                 ModelInjestor injestor = ModelInjestor.getInstance();
116                 jaxbContext = injestor.getContextForVersion(version);
117                 
118         }
119
120         /**
121          * {@inheritDoc}
122          */
123         @Override
124         public Introspector unmarshal(String type, String json, MediaType mediaType) throws AAIUnmarshallingException {         
125                 try {
126                         final Object clazz = objectFromName(type);
127                         final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
128
129                         if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
130                                 unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
131                                 unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
132                                 unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
133                         }
134
135                         final DynamicEntity entity = (DynamicEntity) unmarshaller.unmarshal(new StreamSource(new StringReader(json)), clazz.getClass()).getValue();
136                         return IntrospectorFactory.newInstance(ModelType.MOXY, entity);
137                 } catch (JAXBException e) {
138                         AAIException ex = new AAIException("AAI_4007", e);
139                         ErrorLogHelper.logException(ex);
140                         throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), ex);
141                 } catch (AAIUnknownObjectException e) {
142                         throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), e);
143                 }
144         }
145         
146         @Override
147         public Map<String, Introspector> getAllObjects() {
148                 if (this.allObjs != null) {
149                         return allObjs;
150                 } else {
151                         ImmutableMap.Builder<String, Introspector> map = new ImmutableMap.Builder<String, Introspector>();
152                         Set<String> objs = objectsInVersion();
153                         for (String objName : objs) {
154                                 try {
155                                         Introspector introspector = this.introspectorFromName(objName);
156                                         map.put(introspector.getDbName(), introspector);
157                                 } catch (AAIUnknownObjectException e) {
158                                         LOGGER.warn("Unexpected AAIUnknownObjectException while running getAllObjects()", e);
159                                 }
160                         }
161                         allObjs = map.build();
162                         return allObjs;
163                 }
164         }
165         
166         private Set<String> objectsInVersion() {
167                 final Set<String> result = new HashSet<>();
168
169                 try {
170                         final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
171                         final String fileName = ModelInjestor.getInstance().getOXMFileName(getVersion());
172
173                         docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
174
175                         final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
176                         final Document doc = docBuilder.parse(fileName);
177                         final NodeList list = doc.getElementsByTagName("java-type");
178
179                         for (int i = 0; i < list.getLength(); i++) {
180                                 result.add(list.item(i).getAttributes().getNamedItem("name").getNodeValue());
181                         }
182                 } catch (ParserConfigurationException | SAXException | IOException e) {
183                         LOGGER.warn("Exception while enumerating objects for API version " + getVersion() + " (returning partial results)", e);
184                 }
185
186                 result.remove("EdgePropNames");
187                 return result;
188         }
189
190 }