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