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=========================================================
21 package org.onap.aai.introspection;
23 import com.att.eelf.configuration.EELFLogger;
24 import com.att.eelf.configuration.EELFManager;
25 import com.google.common.base.CaseFormat;
27 import java.io.UnsupportedEncodingException;
28 import java.lang.reflect.InvocationTargetException;
30 import java.util.stream.Collectors;
32 import org.apache.commons.lang.ClassUtils;
33 import org.eclipse.persistence.exceptions.DynamicException;
34 import org.onap.aai.config.SpringContextAware;
35 import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
36 import org.onap.aai.logging.ErrorLogHelper;
37 import org.onap.aai.logging.LogFormatTools;
38 import org.onap.aai.nodes.CaseFormatStore;
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.onap.aai.workarounds.NamingExceptions;
46 public abstract class Introspector implements Cloneable {
48 private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(Introspector.class);
50 protected String className;
51 protected String uriChain = "";
52 protected Loader loader;
53 protected final NamingExceptions namingException = NamingExceptions.getInstance();
54 private Set<String> uniqueProperties = null;
55 private Set<String> indexedProperties = null;
56 private Set<String> allKeys = null;
58 protected CaseFormatStore caseFormatStore = null;
59 protected NodeIngestor nodeIngestor;
61 protected Introspector(Object obj) {
62 this.nodeIngestor = SpringContextAware.getBean(NodeIngestor.class);
63 this.caseFormatStore = nodeIngestor.getCaseFormatStore();
66 public abstract boolean hasProperty(String name);
68 protected String convertPropertyName(String name) {
69 return caseFormatStore.fromLowerHyphenToLowerCamel(name).orElseGet(() -> {
70 LOGGER.debug("Unable to find {} in the store from lower hyphen to lower camel", name);
71 return CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name);
75 protected abstract Object get(String name);
77 protected abstract void set(String name, Object value);
81 * @param name the property name you'd like to retrieve the value for
82 * @return the value of the property
84 public <T> T getValue(String name) {
85 String convertedName = convertPropertyName(name);
88 if (this.hasProperty(name)) {
89 result = this.get(convertedName);
91 /* property not found - slightly ambiguous */
95 Class<?> clazz = this.getClass(name);
96 if (this.isListType(name) && result == null) {
98 this.set(convertedName, clazz.newInstance());
99 result = this.get(convertedName);
100 } catch (DynamicException | InstantiationException | IllegalAccessException e) {
101 LOGGER.warn(e.getMessage(), e);
108 public Introspector getWrappedValue(String name) {
109 String convertedName = convertPropertyName(name);
112 if (this.hasProperty(name)) {
113 value = this.get(convertedName);
115 /* property not found - slightly ambiguous */
119 Class<?> clazz = this.getClass(name);
120 if (this.isListType(name) && value == null) {
122 this.set(convertedName, clazz.newInstance());
123 value = this.get(convertedName);
124 } catch (DynamicException | InstantiationException | IllegalAccessException e) {
125 LOGGER.warn(e.getMessage(), e);
129 return IntrospectorFactory.newInstance(this.getModelType(), value);
137 public List<Introspector> getWrappedListValue(String name) {
138 String convertedName = convertPropertyName(name);
140 List<Introspector> resultList = new ArrayList<>();
141 if (this.hasProperty(name)) {
142 value = this.get(convertedName);
144 /* property not found - slightly ambiguous */
147 boolean isListType = this.isListType(name);
148 if (!this.isListType(name)) {
151 Class<?> clazz = this.getClass(name);
152 if (isListType && value == null) {
154 this.set(convertedName, clazz.newInstance());
155 value = this.get(convertedName);
156 } catch (DynamicException | InstantiationException | IllegalAccessException e) {
157 LOGGER.warn(e.getMessage(), e);
161 List<Object> valueList = (List<Object>) value;
163 for (Object item : valueList) {
164 resultList.add(IntrospectorFactory.newInstance(this.getModelType(), item));
171 public Object castValueAccordingToSchema(String name, Object obj) {
173 Class<?> nameClass = this.getClass(name);
174 if (nameClass == null) {
175 throw new IllegalArgumentException("property: " + name + " does not exist on " + this.getDbName());
180 if (!obj.getClass().getName().equals(nameClass.getName())) {
181 if (nameClass.isPrimitive()) {
182 nameClass = ClassUtils.primitiveToWrapper(nameClass);
183 result = nameClass.getConstructor(String.class).newInstance(obj.toString());
185 if (obj instanceof String) {
186 result = nameClass.getConstructor(String.class).newInstance(obj);
187 } else if (!this.isListType(name) && !this.isComplexType(name)) {
188 // box = obj.toString();
189 result = nameClass.getConstructor(String.class).newInstance(obj.toString());
192 } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
193 | InvocationTargetException | NoSuchMethodException | SecurityException e) {
194 ErrorLogHelper.logError("AAI_4017", e.getMessage());
200 public List<Object> castValueAccordingToSchema(String name, List<?> objs) {
201 List<Object> result = new ArrayList<>();
203 for (Object item : objs) {
204 result.add(this.castValueAccordingToSchema(name, item));
213 * @param name the property name you'd like to set the value of
214 * @param obj the value to be set
217 public void setValue(String name, Object obj) {
218 Object box = this.castValueAccordingToSchema(name, obj);
220 name = convertPropertyName(name);
226 * @return a list of all the properties available on the object
228 public abstract Set<String> getProperties();
230 public Set<String> getProperties(PropertyPredicate<Introspector, String> p) {
231 final Set<String> temp = new LinkedHashSet<>();
232 this.getProperties().stream().filter(item -> {
233 return p.test(this, item);
237 final Set<String> result = Collections.unmodifiableSet(temp);
243 public Set<String> getSimpleProperties(PropertyPredicate<Introspector, String> p) {
244 return this.getProperties().stream().filter(item -> p.test(this, item)).filter(this::isSimpleType)
245 .collect(Collectors.toSet());
250 * @return a list of the required properties on the object
252 public abstract Set<String> getRequiredProperties();
256 * @return a list of the properties that can be used to query the object in the db
258 public abstract Set<String> getKeys();
262 * @return a list of the all key properties for this object
264 public Set<String> getAllKeys() {
265 Set<String> result = null;
266 if (this.allKeys == null) {
267 Set<String> keys = this.getKeys();
268 result = new LinkedHashSet<>();
270 String altKeys = this.getMetadata(ObjectMetadata.ALTERNATE_KEYS_1);
271 if (altKeys != null) {
272 String[] altKeysArray = altKeys.split(",");
273 for (String altKey : altKeysArray) {
277 result = Collections.unmodifiableSet(result);
278 this.allKeys = result;
280 result = this.allKeys;
284 public Set<String> getIndexedProperties() {
285 Set<String> result = null;
287 if (this.indexedProperties == null) {
288 result = new LinkedHashSet<>();
289 Set<String> keys = this.getKeys();
291 String altKeys = this.getMetadata(ObjectMetadata.INDEXED_PROPS);
292 if (altKeys != null) {
293 String[] altKeysArray = altKeys.split(",");
294 for (String altKey : altKeysArray) {
298 this.indexedProperties = Collections.unmodifiableSet(result);
300 result = this.indexedProperties;
304 public Set<String> getUniqueProperties() {
305 Set<String> result = null;
306 if (this.uniqueProperties == null) {
307 String altKeys = this.getMetadata(ObjectMetadata.UNIQUE_PROPS);
308 result = new LinkedHashSet<>();
309 if (altKeys != null) {
310 String[] altKeysArray = altKeys.split(",");
311 for (String altKey : altKeysArray) {
315 this.uniqueProperties = Collections.unmodifiableSet(result);
318 result = this.uniqueProperties;
322 public Set<String> getDependentOn() {
323 String dependentOn = this.getMetadata(ObjectMetadata.DEPENDENT_ON);
324 if (dependentOn == null) {
325 return new LinkedHashSet<>();
327 return new LinkedHashSet<>(Arrays.asList(dependentOn.split(",")));
333 * @return the string name of the java class of the named property
335 public String getType(String name) {
336 Class<?> resultClass = this.getClass(name);
339 if (resultClass != null) {
340 result = resultClass.getName();
341 if (result.equals("java.util.ArrayList")) {
342 result = "java.util.List";
350 * This will returned the generic parameterized type of the underlying
351 * object if it exists
354 * @return the generic type of the java class of the underlying object
356 public String getGenericType(String name) {
357 Class<?> resultClass = this.getGenericTypeClass(name);
360 if (resultClass != null) {
361 result = resultClass.getName();
369 * @return the string name of the java class of the underlying object
371 public abstract String getJavaClassName();
375 * @param name the property name
376 * @return the Class object
378 public abstract Class<?> getClass(String name);
380 public abstract Class<?> getGenericTypeClass(String name);
384 * @param name the property name
385 * @return a new instance of the underlying type of this property
386 * @throws AAIUnknownObjectException
388 public Object newInstanceOfProperty(String name) throws AAIUnknownObjectException {
389 String type = this.getType(name);
390 return loader.objectFromName(type);
393 public Object newInstanceOfNestedProperty(String name) throws AAIUnknownObjectException {
394 String type = this.getGenericType(name);
395 return loader.objectFromName(type);
398 public Introspector newIntrospectorInstanceOfProperty(String name) throws AAIUnknownObjectException {
400 Introspector result = IntrospectorFactory.newInstance(this.getModelType(), this.newInstanceOfProperty(name));
406 public Introspector newIntrospectorInstanceOfNestedProperty(String name) throws AAIUnknownObjectException {
408 Introspector result =
409 IntrospectorFactory.newInstance(this.getModelType(), this.newInstanceOfNestedProperty(name));
416 * Is this type not a Java String or primitive
421 public boolean isComplexType(String name) {
422 String result = this.getType(name);
424 if (result.contains("aai") || result.equals("java.lang.Object")) {
431 public boolean isComplexGenericType(String name) {
432 String result = this.getGenericType(name);
434 if (result.contains("aai")) {
441 public boolean isSimpleType(String name) {
442 return !(this.isComplexType(name) || this.isListType(name));
445 public boolean isSimpleGenericType(String name) {
446 return !this.isComplexGenericType(name);
449 public boolean isListType(String name) {
450 String result = this.getType(name);
452 if (result.contains("java.util.List")) {
459 public boolean isContainer() {
460 Set<String> props = this.getProperties();
461 boolean result = false;
462 if (props.size() == 1 && this.isListType(props.iterator().next())) {
469 public abstract String getChildName();
471 public String getChildDBName() {
472 String result = this.getChildName();
474 result = namingException.getDBName(result);
478 public abstract String getName();
480 public String getDbName() {
481 String lowerHyphen = this.getName();
483 lowerHyphen = namingException.getDBName(lowerHyphen);
488 public abstract ModelType getModelType();
490 public boolean hasChild(Introspector child) {
491 boolean result = false;
492 // check all inheriting types for this child
493 if ("true".equals(this.getMetadata(ObjectMetadata.ABSTRACT))) {
494 String[] inheritors = this.getMetadata(ObjectMetadata.INHERITORS).split(",");
495 for (String inheritor : inheritors) {
497 Introspector temp = this.loader.introspectorFromName(inheritor);
498 result = temp.hasProperty(child.getName());
502 } catch (AAIUnknownObjectException e) {
504 "Skipping inheritor " + inheritor + " (Unknown Object) " + LogFormatTools.getStackTop(e));
508 result = this.hasProperty(child.getName());
513 public void setURIChain(String uri) {
517 public abstract String getObjectId() throws UnsupportedEncodingException;
519 public String getURI() throws UnsupportedEncodingException {
520 // String result = this.uriChain;
522 String namespace = this.getMetadata(ObjectMetadata.NAMESPACE);
523 String container = this.getMetadata(ObjectMetadata.CONTAINER);
524 if (this.isContainer()) {
525 result += "/" + this.getName();
528 if (container != null) {
529 result += "/" + container;
531 result += "/" + this.getDbName() + "/" + this.findKey();
533 if (namespace != null && !namespace.equals("")) {
534 result = "/" + namespace + result;
541 public String getGenericURI() {
543 if (this.isContainer()) {
544 result += "/" + this.getName();
546 result += "/" + this.getDbName();
547 for (String key : this.getKeys()) {
548 result += "/{" + this.getDbName() + "-" + key + "}";
555 public String getFullGenericURI() {
557 String namespace = this.getMetadata(ObjectMetadata.NAMESPACE);
558 String container = this.getMetadata(ObjectMetadata.CONTAINER);
559 if (this.isContainer()) {
560 result += "/" + this.getName();
563 if (container != null) {
564 result += "/" + container;
566 result += "/" + this.getDbName();
568 for (String key : this.getKeys()) {
569 result += "/{" + this.getDbName() + "-" + key + "}";
571 if (namespace != null && !namespace.equals("")) {
572 result = "/" + namespace + result;
580 public abstract String preProcessKey(String key);
582 protected abstract String findKey() throws UnsupportedEncodingException;
584 public abstract String marshal(MarshallerProperties properties);
586 public abstract Object getUnderlyingObject();
588 public String marshal(boolean formatted) {
589 MarshallerProperties properties =
590 new MarshallerProperties.Builder(MediaType.APPLICATION_JSON_TYPE).formatted(formatted).build();
592 return marshal(properties);
595 public String makeSingular(String word) {
597 String result = word;
598 result = result.replaceAll("(?:([ho])es|s)$", "");
600 if (result.equals("ClassesOfService")) {
601 result = "ClassOfService";
602 } else if (result.equals("CvlanTag")) {
603 result = "CvlanTagEntry";
604 } else if (result.equals("Metadata")) {
605 result = "Metadatum";
610 protected String makePlural(String word) {
611 String result = word;
613 if (result.equals("cvlan-tag-entry")) {
615 } else if (result.equals("class-of-service")) {
616 return "classes-of-service";
617 } else if (result.equals("metadatum")) {
620 result = result.replaceAll("([a-z])$", "$1s");
621 result = result.replaceAll("([hox])s$", "$1es");
623 * if (result.equals("classes-of-services")) {
624 * result = "classes-of-service";
631 public abstract String getMetadata(ObjectMetadata metadataName);
633 public abstract Map<PropertyMetadata, String> getPropertyMetadata(String propName);
635 public Optional<String> getPropertyMetadata(String propName, PropertyMetadata metadataName) {
636 final String resultValue = this.getPropertyMetadata(propName).getOrDefault(metadataName, "");
637 Optional<String> result = Optional.empty();
639 if (!resultValue.isEmpty()) {
640 result = Optional.of(resultValue);
646 public abstract SchemaVersion getVersion();
648 public Loader getLoader() {
652 public boolean isTopLevel() {
654 return this.getMetadata(ObjectMetadata.NAMESPACE) != null;