05cbf97c4ac6b7baca416f29be84a5c1a264734d
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / util / PojoUtils.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
21 package org.onap.aai.util;
22
23 import com.fasterxml.jackson.annotation.JsonInclude;
24 import com.fasterxml.jackson.core.JsonGenerationException;
25 import com.fasterxml.jackson.databind.DeserializationFeature;
26 import com.fasterxml.jackson.databind.JsonMappingException;
27 import com.fasterxml.jackson.databind.ObjectMapper;
28 import com.fasterxml.jackson.databind.SerializationFeature;
29 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
30 import com.google.common.base.CaseFormat;
31 import com.google.common.collect.Multimap;
32
33 import java.io.IOException;
34 import java.io.StringWriter;
35 import java.lang.reflect.InvocationTargetException;
36 import java.lang.reflect.Method;
37 import java.security.SecureRandom;
38 import java.util.*;
39
40 import javax.xml.bind.JAXBContext;
41 import javax.xml.bind.JAXBException;
42 import javax.xml.bind.Marshaller;
43
44 import org.apache.commons.io.output.ByteArrayOutputStream;
45 import org.eclipse.persistence.dynamic.DynamicEntity;
46 import org.eclipse.persistence.jaxb.JAXBMarshaller;
47 import org.eclipse.persistence.jaxb.MarshallerProperties;
48 import org.onap.aai.domain.model.AAIResource;
49 import org.onap.aai.exceptions.AAIException;
50
51 public class PojoUtils {
52
53     /**
54      * Gets the key value list.
55      *
56      * @param <T> the generic type
57      * @param e the e
58      * @param clazz the clazz
59      * @return the key value list
60      * @throws IllegalAccessException the illegal access exception
61      * @throws IllegalArgumentException the illegal argument exception
62      * @throws InvocationTargetException the invocation target exception
63      */
64     public <T> List<KeyValueList> getKeyValueList(Entity e, T clazz)
65             throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
66         List<KeyValueList> kvList = e.getKeyValueList();
67         Object value = null;
68         Method[] methods = clazz.getClass().getDeclaredMethods();
69         String propertyName = "";
70
71         for (Method method : methods) {
72             if (method.getName().startsWith("get")) {
73                 propertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, method.getName().substring(3));
74                 if (!(method.getReturnType().getName().contains("aai"))
75                         || method.getReturnType().getName().contains("java.util.List")) {
76                     value = method.invoke(clazz);
77                     KeyValueList kv = new KeyValueList();
78                     kv.setKey(propertyName);
79                     if (value != null) {
80                         kv.setValue(value.toString());
81                     } else {
82                         kv.setValue("");
83                     }
84                     kvList.add(kv);
85                 }
86             }
87         }
88         return kvList;
89     }
90
91     /**
92      * Gets the json from object.
93      *
94      * @param <T> the generic type
95      * @param clazz the clazz
96      * @return the json from object
97      * @throws JsonGenerationException the json generation exception
98      * @throws JsonMappingException the json mapping exception
99      * @throws IOException Signals that an I/O exception has occurred.
100      */
101     public <T> String getJsonFromObject(T clazz) throws JsonGenerationException, JsonMappingException, IOException {
102         return getJsonFromObject(clazz, false, true);
103     }
104
105     /**
106      * Gets the json from object.
107      *
108      * @param <T> the generic type
109      * @param clazz the clazz
110      * @param wrapRoot the wrap root
111      * @param indent the indent
112      * @return the json from object
113      * @throws JsonGenerationException the json generation exception
114      * @throws JsonMappingException the json mapping exception
115      * @throws IOException Signals that an I/O exception has occurred.
116      */
117     public <T> String getJsonFromObject(T clazz, boolean wrapRoot, boolean indent)
118             throws JsonGenerationException, JsonMappingException, IOException {
119         ObjectMapper mapper = new ObjectMapper();
120
121         mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
122
123         mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
124         mapper.configure(SerializationFeature.INDENT_OUTPUT, indent);
125         mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapRoot);
126
127         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
128         mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapRoot);
129
130         mapper.registerModule(new JaxbAnnotationModule());
131
132         return mapper.writeValueAsString(clazz);
133     }
134
135     /**
136      * Gets the json from dynamic object.
137      *
138      * @param ent the ent
139      * @param jaxbContext the jaxb context
140      * @param includeRoot the include root
141      * @return the json from dynamic object
142      * @throws JsonGenerationException the json generation exception
143      * @throws JsonMappingException the json mapping exception
144      * @throws IOException Signals that an I/O exception has occurred.
145      * @throws JAXBException the JAXB exception
146      */
147     public String getJsonFromDynamicObject(DynamicEntity ent, org.eclipse.persistence.jaxb.JAXBContext jaxbContext,
148             boolean includeRoot) throws JsonGenerationException, JsonMappingException, IOException, JAXBException {
149         JAXBMarshaller marshaller = jaxbContext.createMarshaller();
150
151         marshaller.setProperty(JAXBMarshaller.JAXB_FORMATTED_OUTPUT, false);
152         marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE);
153         marshaller.setProperty("eclipselink.json.include-root", includeRoot);
154         marshaller.setProperty("eclipselink.media-type", "application/json");
155         StringWriter writer = new StringWriter();
156         marshaller.marshal(ent, writer);
157
158         return writer.toString();
159     }
160
161     /**
162      * Gets the xml from object.
163      *
164      * @param <T> the generic type
165      * @param clazz the clazz
166      * @return the xml from object
167      * @throws JAXBException the JAXB exception
168      * @throws IOException
169      */
170     public <T> String getXmlFromObject(T clazz) throws JAXBException, IOException {
171         try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
172             JAXBContext jc = JAXBContext.newInstance(clazz.getClass().getPackage().getName());
173
174             Marshaller marshaller = jc.createMarshaller();
175             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
176             marshaller.marshal(clazz, baos);
177             return baos.toString();
178         }
179     }
180
181     /**
182      * Gets the lookup key.
183      *
184      * @param baseKey the base key
185      * @param lookupHash the lookup hash
186      * @param keyProps the key props
187      * @return the lookup key
188      */
189     public String getLookupKey(String baseKey, HashMap<String, Object> lookupHash, Collection<String> keyProps) {
190         int baseKeyLen = baseKey.length();
191         StringBuffer newKey = new StringBuffer();
192         if (baseKeyLen > 0) {
193             newKey.append(baseKey);
194         }
195
196         Iterator<String> keyPropI = keyProps.iterator();
197         while (keyPropI.hasNext()) {
198             String keyProp = keyPropI.next();
199             if (baseKeyLen > 0) {
200                 newKey.append("&");
201             }
202             newKey.append(keyProp + "=" + lookupHash.get(keyProp));
203         }
204         return newKey.toString();
205     }
206
207     /**
208      * Gets the lookup keys.
209      *
210      * @param lookupHashes the lookup hashes
211      * @param _dbRulesNodeKeyProps the db rules node key props
212      * @return the lookup keys
213      */
214     public String getLookupKeys(LinkedHashMap<String, HashMap<String, Object>> lookupHashes,
215             Multimap<String, String> _dbRulesNodeKeyProps) {
216         Iterator<String> it = lookupHashes.keySet().iterator();
217         String lookupKeys = "";
218         while (it.hasNext()) {
219             String objectType = (String) it.next();
220             HashMap<String, Object> lookupHash = lookupHashes.get(objectType);
221
222             Collection<String> keyProps = _dbRulesNodeKeyProps.get(objectType);
223             Iterator<String> keyPropI = keyProps.iterator();
224             while (keyPropI.hasNext()) {
225                 lookupKeys += lookupHash.get(keyPropI.next());
226             }
227         }
228         return lookupKeys;
229     }
230
231     /**
232      * Gets the example object.
233      *
234      * @param <T> the generic type
235      * @param clazz the clazz
236      * @param singleton the singleton
237      * @return the example object
238      * @throws IllegalAccessException the illegal access exception
239      * @throws IllegalArgumentException the illegal argument exception
240      * @throws InvocationTargetException the invocation target exception
241      * @throws NoSuchMethodException the no such method exception
242      * @throws SecurityException the security exception
243      * @throws AAIException the AAI exception
244      */
245     public <T> void getExampleObject(T clazz, boolean singleton)
246             throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException,
247             SecurityException, AAIException {
248         Method[] methods = clazz.getClass().getDeclaredMethods();
249         String dnHypPropertyName = "";
250         String upCamPropertyName = "";
251         Random rand = new SecureRandom();
252         int randInt = rand.nextInt(10000000);
253
254         for (Method method : methods) {
255             boolean go = false;
256             if (method.getName().startsWith("get")) {
257                 dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, method.getName().substring(3));
258                 upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL, method.getName().substring(3));
259                 go = true;
260             } else if (method.getName().startsWith("is")) {
261                 dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, method.getName().substring(2));
262                 upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL, method.getName().substring(2));
263                 go = true;
264             }
265             // don't return resource-version on a singleton
266             if (singleton && dnHypPropertyName.equals("resource-version")) {
267                 go = false;
268             }
269             if (go) {
270                 String retType = method.getReturnType().getName();
271                 if (!retType.contains("aai") && !retType.contains("java.util.List")) {
272                     // get the setter
273                     Method meth = clazz.getClass().getMethod("set" + upCamPropertyName, method.getReturnType());
274
275                     if (retType.contains("String")) {
276                         String val = "example-" + dnHypPropertyName + "-val-" + randInt;
277                         if (val != null) {
278                             meth.invoke(clazz, val);
279                         }
280                     } else if (retType.toLowerCase().contains("long")) {
281                         Integer foo = rand.nextInt(100000);
282                         meth.invoke(clazz, foo.longValue());
283                     } else if (retType.toLowerCase().contains("int")) {
284                         meth.invoke(clazz, rand.nextInt(100000));
285                     } else if (retType.toLowerCase().contains("short")) {
286                         Integer randShort = rand.nextInt(10000);
287                         meth.invoke(clazz, randShort.shortValue());
288                     } else if (retType.toLowerCase().contains("boolean")) {
289                         meth.invoke(clazz, true);
290                     }
291                     // i think max has a list in license-management
292                 }
293             }
294         }
295     }
296
297     /**
298      * Gets the dynamic example object.
299      *
300      * @param childObject the child object
301      * @param aaiRes the aai res
302      * @param singleton the singleton
303      * @return the dynamic example object
304      */
305     public void getDynamicExampleObject(DynamicEntity childObject, AAIResource aaiRes, boolean singleton) {
306         // TODO Auto-generated method stub
307
308         Random rand = new SecureRandom();
309         Integer randInt = rand.nextInt(100000);
310         long range = 100000000L;
311         long randLong = (long) (rand.nextDouble() * range);
312         Integer randShrt = rand.nextInt(20000);
313         short randShort = randShrt.shortValue();
314
315         for (String dnHypAttrName : aaiRes.getStringFields()) {
316
317             if (singleton && ("resource-version").equals(dnHypAttrName)) {
318                 continue;
319             }
320
321             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
322             childObject.set(dnCamAttrName, "example-" + dnHypAttrName + "-val-" + randInt);
323
324         }
325
326         for (String dnHypAttrName : aaiRes.getStringListFields()) {
327             ArrayList<String> exampleList = new ArrayList<String>();
328             exampleList.add("example-" + dnHypAttrName + "-val-" + randInt + "-" + 1);
329             exampleList.add("example-" + dnHypAttrName + "-val-" + randInt + "-" + 2);
330             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
331             childObject.set(dnCamAttrName, exampleList);
332         }
333
334         // the attrName might need to be converted to camel case!!!
335         for (String dnHypAttrName : aaiRes.getLongFields()) {
336             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
337             childObject.set(dnCamAttrName, randLong);
338         }
339
340         for (String dnHypAttrName : aaiRes.getIntFields()) {
341             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
342             childObject.set(dnCamAttrName, randInt);
343         }
344
345         for (String dnHypAttrName : aaiRes.getShortFields()) {
346             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
347             childObject.set(dnCamAttrName, randShort);
348         }
349
350         for (String dnHypAttrName : aaiRes.getBooleanFields()) {
351             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
352             childObject.set(dnCamAttrName, Boolean.TRUE);
353         }
354     }
355 }