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