2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.onap.aai.introspection;
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.base.Joiner;
28 import org.eclipse.persistence.descriptors.ClassDescriptor;
29 import org.eclipse.persistence.dynamic.DynamicEntity;
30 import org.eclipse.persistence.dynamic.DynamicType;
31 import org.eclipse.persistence.exceptions.DynamicException;
32 import org.eclipse.persistence.jaxb.UnmarshallerProperties;
33 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
34 import org.eclipse.persistence.mappings.DatabaseMapping;
35 import org.eclipse.persistence.oxm.XMLField;
36 import org.eclipse.persistence.oxm.mappings.XMLCompositeCollectionMapping;
37 import org.eclipse.persistence.oxm.mappings.XMLCompositeDirectCollectionMapping;
38 import org.onap.aai.config.SpringContextAware;
39 import org.onap.aai.nodes.NodeIngestor;
40 import org.onap.aai.restcore.MediaType;
41 import org.onap.aai.schema.enums.ObjectMetadata;
42 import org.onap.aai.schema.enums.PropertyMetadata;
43 import org.onap.aai.setup.SchemaVersion;
44 import org.springframework.web.util.UriUtils;
45 import javax.xml.bind.JAXBException;
46 import javax.xml.bind.Marshaller;
47 import javax.xml.bind.Unmarshaller;
48 import javax.xml.transform.stream.StreamSource;
49 import java.io.StringReader;
50 import java.io.StringWriter;
51 import java.io.UnsupportedEncodingException;
53 import java.util.Map.Entry;
54 import java.util.stream.Collectors;
56 public class MoxyStrategy extends Introspector {
58 private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(MoxyStrategy.class);
59 private DynamicEntity internalObject = null;
60 private DynamicType internalType = null;
61 private DynamicJAXBContext jaxbContext = null;
62 private ClassDescriptor cd = null;
63 private Marshaller marshaller = null;
64 private Unmarshaller unmarshaller = null;
65 private SchemaVersion version = null;
66 private Set<String> properties = null;
67 private Set<String> keys = null;
68 private Set<String> requiredProperties = null;
70 private boolean isInitialized = false;
72 private NodeIngestor nodeIngestor;
74 protected MoxyStrategy(Object obj) {
76 /* must look up the correct jaxbcontext for this object */
77 className = MoxyStrategy.class.getSimpleName();
78 internalObject = (DynamicEntity)obj;
79 nodeIngestor = SpringContextAware.getBean(NodeIngestor.class);
80 version = nodeIngestor.getVersionFromClassName(internalObject.getClass().getName());
81 super.loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(getModelType(), version);
82 jaxbContext = nodeIngestor.getContextForVersion(version);
83 String simpleName = internalObject.getClass().getName();
84 internalType = jaxbContext.getDynamicType(simpleName);
86 cd = internalType.getDescriptor();
88 marshaller = jaxbContext.createMarshaller();
90 unmarshaller = jaxbContext.createUnmarshaller();
92 } catch (JAXBException e) {
101 Set<String> props = new LinkedHashSet<>();
102 for (String s : internalType.getPropertiesNames()) {
103 props.add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, s));
106 props = Collections.unmodifiableSet(props);
107 this.properties = props;
109 Set<String> requiredProps = new LinkedHashSet<>();
110 requiredProps = new LinkedHashSet<>();
111 for (DatabaseMapping dm : cd.getMappings()) {
112 if (dm.getField() instanceof XMLField) {
113 XMLField x = (XMLField)dm.getField();
115 if (x.isRequired()) {
116 requiredProps.add(this.removeXPathDescriptor(x.getName()));
121 requiredProps = Collections.unmodifiableSet(requiredProps);
122 this.requiredProperties = requiredProps;
124 Set<String> keys = new LinkedHashSet<>();
126 for (String name : internalType.getDescriptor().getPrimaryKeyFieldNames()) {
127 keys.add(this.removeXPathDescriptor(name));
129 keys = Collections.unmodifiableSet(keys);
136 public boolean hasProperty(String name) {
137 String convertedName = convertPropertyName(name);
139 return internalType.containsProperty(convertedName);
143 public Object get(String name) {
144 return internalObject.get(name);
148 public void set(String name, Object obj) throws IllegalArgumentException {
150 internalObject.set(name, obj);
154 public Set<String> getProperties() {
160 return this.properties;
165 public Set<String> getRequiredProperties() {
171 return this.requiredProperties;
175 public Set<String> getKeys() {
185 public Map<PropertyMetadata, String> getPropertyMetadata(String prop) {
186 String propName = this.convertPropertyName(prop);
187 DatabaseMapping mapping = cd.getMappingForAttributeName(propName);
188 Map<PropertyMetadata, String> result = new HashMap<>();
189 if (mapping != null) {
190 Set<Entry> entrySet = mapping.getProperties().entrySet();
191 for (Entry<?,?> entry : entrySet) {
193 PropertyMetadata.valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, (String)entry.getKey())), (String)entry.getValue());
201 public String getJavaClassName() {
202 return internalObject.getClass().getName();
208 public Class<?> getClass(String name) {
209 name = convertPropertyName(name);
210 Class<?> resultClass = null;
212 if (internalType.getPropertyType(name) == null) {
213 if (cd.getMappingForAttributeName(name) instanceof XMLCompositeDirectCollectionMapping) {
214 resultClass = cd.getMappingForAttributeName(name).getContainerPolicy().getContainerClass();
216 } else if (cd.getMappingForAttributeName(name) instanceof XMLCompositeCollectionMapping) {
217 resultClass = cd.getMappingForAttributeName(name).getContainerPolicy().getContainerClass();
219 ClassDescriptor referenceDiscriptor = cd.getMappingForAttributeName(name).getReferenceDescriptor();
220 if (referenceDiscriptor != null) {
221 resultClass = referenceDiscriptor.getJavaClass();
223 resultClass = Object.class;
227 resultClass = internalType.getPropertyType(name);
229 } catch (DynamicException e) {
230 //property doesn't exist
236 public Class<?> getGenericTypeClass(String name) {
237 name = convertPropertyName(name);
238 Class<?> resultClass = null;
239 if (internalType.getPropertyType(name) == null) {
240 if (cd.getMappingForAttributeName(name) instanceof XMLCompositeDirectCollectionMapping) {
241 resultClass = cd.getMappingForAttributeName(name).getFields().get(0).getType();
243 } else if (cd.getMappingForAttributeName(name) instanceof XMLCompositeCollectionMapping) {
244 resultClass = cd.getMappingForAttributeName(name).getReferenceDescriptor().getJavaClass();
252 public Object getUnderlyingObject() {
253 return this.internalObject;
257 public String getChildName() {
259 String className = internalObject.getClass().getSimpleName();
260 String lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className);
262 if (this.isContainer()) {
263 lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().iterator().next()).getSimpleName());
270 public String getName() {
271 String className = internalObject.getClass().getSimpleName();
272 String lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className);
274 if (this.isContainer()) {
275 lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().get(0)).getSimpleName());
283 public String getObjectId() throws UnsupportedEncodingException {
285 String container = this.getMetadata(ObjectMetadata.CONTAINER);
286 if (this.isContainer()) {
287 result += "/" + this.getName();
290 if (container != null) {
291 result += "/" + container;
293 result += "/" + this.getDbName() + "/" + this.findKey();
301 protected String findKey() throws UnsupportedEncodingException {
302 Set<String> keys = null;
303 keys = this.getKeys();
304 List<String> results = new ArrayList<>();
305 for (String key : keys) {
306 String value = UriUtils.encode(this.getValue(key).toString(), "UTF-8");
310 return Joiner.on("/").join(results);
314 public String preProcessKey (String key) {
316 //String trimmedRestURI = restURI.replaceAll("/[\\w\\-]+?/[\\w\\-]+?$", "");
317 String[] split = key.split("/");
319 for (i = split.length-1; i >= 0; i--) {
321 if (jaxbContext.getDynamicType(split[i]) != null) {
327 result = Joiner.on("/").join(Arrays.copyOfRange(split, 0, i));
334 public String marshal(MarshallerProperties properties) {
335 StringWriter result = new StringWriter();
337 if (properties.getMediaType().equals(MediaType.APPLICATION_JSON_TYPE)) {
338 marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json");
339 marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_INCLUDE_ROOT, properties.getIncludeRoot());
340 marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, properties.getWrapperAsArrayName());
341 marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, false);
344 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, properties.getFormatted());
345 marshaller.marshal(this.internalObject, result);
346 } catch (JAXBException e) {
347 //e.printStackTrace();
350 return result.toString();
354 public Object clone() {
355 Object result = null;
357 unmarshaller = jaxbContext.createUnmarshaller();
359 unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
360 unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
361 unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
363 result = unmarshaller.unmarshal(new StreamSource(new StringReader(this.marshal(true))), this.internalObject.getClass()).getValue();
364 } catch (JAXBException e) {
365 // TODO Auto-generated catch block
366 //e.printStackTrace();
368 result = IntrospectorFactory.newInstance(getModelType(), result);
372 public ModelType getModelType() {
373 return ModelType.MOXY;
376 private String removeXPathDescriptor(String name) {
378 return name.replaceAll("/text\\(\\)", "");
382 public String getMetadata(ObjectMetadata name) {
384 return (String)cd.getProperty(name.toString());
388 public SchemaVersion getVersion() {