82504550b0e26387b89c82509c86267749fb7028
[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-2018 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 package org.onap.aai.introspection;
21
22 import com.att.eelf.configuration.EELFLogger;
23 import com.att.eelf.configuration.EELFManager;
24 import com.google.common.base.CaseFormat;
25 import com.google.common.collect.ImmutableMap;
26
27 import org.eclipse.persistence.dynamic.DynamicEntity;
28 import org.eclipse.persistence.jaxb.UnmarshallerProperties;
29 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
30 import org.onap.aai.exceptions.AAIException;
31 import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
32 import org.onap.aai.introspection.exceptions.AAIUnmarshallingException;
33 import org.onap.aai.logging.ErrorLogHelper;
34 import org.onap.aai.logging.LogFormatTools;
35 import org.onap.aai.nodes.NodeIngestor;
36 import org.onap.aai.restcore.MediaType;
37 import org.onap.aai.setup.SchemaVersion;
38 import org.onap.aai.workarounds.NamingExceptions;
39 import org.springframework.stereotype.Component;
40 import javax.xml.bind.JAXBException;
41 import javax.xml.bind.Unmarshaller;
42 import javax.xml.transform.stream.StreamSource;
43 import java.io.*;
44 import java.util.HashSet;
45 import java.util.Map;
46 import java.util.Set;
47
48 public class MoxyLoader extends Loader {
49
50         private DynamicJAXBContext jaxbContext = null;
51         private EELFLogger LOGGER = EELFManager.getInstance().getLogger(MoxyLoader.class);
52         private Map<String, Introspector> allObjs = null;
53
54         private Map<SchemaVersion, MoxyLoader> moxyLoaderFactory;
55         
56         private NodeIngestor nodeIngestor;
57
58         public MoxyLoader(SchemaVersion version, NodeIngestor nodeIngestor) {
59                 super(version, ModelType.MOXY);
60                 this.nodeIngestor = nodeIngestor;
61                 process(version);
62         }
63
64         public MoxyLoader getMoxyLoader(SchemaVersion v) {
65                 return moxyLoaderFactory.get(v);
66
67         }
68         /**
69          * {@inheritDoc}
70          * @throws AAIUnknownObjectException 
71          */
72         @Override
73         public Introspector introspectorFromName(String name) throws AAIUnknownObjectException {
74
75                 return IntrospectorFactory.newInstance(ModelType.MOXY, objectFromName(name));
76         }
77         
78         /**
79          * {@inheritDoc}
80          */
81         @Override
82         public Object objectFromName(String name) throws AAIUnknownObjectException {
83
84                 if (name == null) {
85                         throw new AAIUnknownObjectException("null name passed in");
86                 }
87                 final String sanitizedName = NamingExceptions.getInstance().getObjectName(name);
88                 final String upperCamel;
89
90                 //Contains any uppercase, then assume it's upper camel
91                 if (name.matches(".*[A-Z].*")) {
92                         upperCamel = sanitizedName;
93                 } else {
94                         upperCamel = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, sanitizedName);
95                 }
96                 
97                 try {
98                         final DynamicEntity result = jaxbContext.newDynamicEntity(upperCamel);
99
100                         if (result == null) throw new AAIUnknownObjectException("Unrecognized AAI object " + name);
101
102                         return result;
103                 } catch (IllegalArgumentException e) {
104                         //entity does not exist
105                         throw new AAIUnknownObjectException("Unrecognized AAI object " + name, e);
106                 }
107         }
108
109         /**
110          * {@inheritDoc}
111          */
112         @Override
113         protected void process(SchemaVersion version) {
114                 /*
115                  * We need to have just same JaxbContext for each version
116                  */
117                 jaxbContext = nodeIngestor.getContextForVersion(version);
118                 
119         }
120
121         /**
122          * {@inheritDoc}
123          */
124         @Override
125         public Introspector unmarshal(String type, String json, MediaType mediaType) throws AAIUnmarshallingException {         
126                 try {
127                         final Object clazz = objectFromName(type);
128                         final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
129
130                         if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
131                                 unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
132                                 unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
133                                 unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
134                         }
135
136                         final DynamicEntity entity = (DynamicEntity) unmarshaller.unmarshal(new StreamSource(new StringReader(json)), clazz.getClass()).getValue();
137                         return IntrospectorFactory.newInstance(ModelType.MOXY, entity);
138                 } catch (JAXBException e) {
139                         AAIException ex = new AAIException("AAI_4007", e);
140                         ErrorLogHelper.logException(ex);
141                         throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), ex);
142                 } catch (AAIUnknownObjectException e) {
143                         throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), e);
144                 }
145         }
146         
147         @Override
148         public Map<String, Introspector> getAllObjects() {
149                 if (this.allObjs != null) {
150                         return allObjs;
151                 } else {
152                         ImmutableMap.Builder<String, Introspector> map = new ImmutableMap.Builder<String, Introspector>();
153                         Set<String> objs = objectsInVersion();
154                         for (String objName : objs) {
155                                 try {
156                                         Introspector introspector = this.introspectorFromName(objName);
157                                         map.put(introspector.getDbName(), introspector);
158                                 } catch (AAIUnknownObjectException e) {
159                                         LOGGER.warn("Unexpected AAIUnknownObjectException while running getAllObjects() " + LogFormatTools.getStackTop(e));
160                                 }
161                         }
162                         allObjs = map.build();
163                         return allObjs;
164                 }
165         }
166         
167         private Set<String> objectsInVersion() {
168                  Set<String> result = new HashSet<>();
169
170                 try {
171                  result = nodeIngestor.getObjectsInVersion(getVersion());
172
173                 } catch (Exception e) {
174                         LOGGER.warn("Exception while enumerating objects for API version " + getVersion() + " (returning partial results) " + LogFormatTools.getStackTop(e));
175                 }
176
177                 //result.remove("EdgePropNames");
178                 return result;
179         }
180         
181         public DynamicJAXBContext getJAXBContext() {
182                 return this.jaxbContext;
183         }
184
185         /*
186          * Im keeping this for now - Just in case
187          */
188         /*private static class Helper {
189                 private static final Map<SchemaVersion, MoxyLoader> INSTANCEMAP = new ConcurrentHashMap<>();
190
191                 private Helper() {}
192
193                 private static MoxyLoader getLoaderBySchemaVersion(SchemaVersion v) {
194                         if (!INSTANCEMAP.containsKey(v)) {
195                                 INSTANCEMAP.put(v, new MoxyLoader(v, nodeIngestor));
196                         }
197                         return INSTANCEMAP.get(v);
198                 }
199         }*/
200 }