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