218f0dd817b0c3ba558ebb8e53d35072d3795d16
[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         ByteArrayOutputStream baos = new ByteArrayOutputStream();
133
134         mapper.writeValue(baos, clazz);
135
136         return baos.toString();
137     }
138
139     /**
140      * Gets the json from dynamic object.
141      *
142      * @param ent the ent
143      * @param jaxbContext the jaxb context
144      * @param includeRoot the include root
145      * @return the json from dynamic object
146      * @throws JsonGenerationException the json generation exception
147      * @throws JsonMappingException the json mapping exception
148      * @throws IOException Signals that an I/O exception has occurred.
149      * @throws JAXBException the JAXB exception
150      */
151     public String getJsonFromDynamicObject(DynamicEntity ent, org.eclipse.persistence.jaxb.JAXBContext jaxbContext,
152             boolean includeRoot) throws JsonGenerationException, JsonMappingException, IOException, JAXBException {
153         JAXBMarshaller marshaller = jaxbContext.createMarshaller();
154
155         marshaller.setProperty(JAXBMarshaller.JAXB_FORMATTED_OUTPUT, false);
156         marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE);
157         marshaller.setProperty("eclipselink.json.include-root", includeRoot);
158         marshaller.setProperty("eclipselink.media-type", "application/json");
159         StringWriter writer = new StringWriter();
160         marshaller.marshal(ent, writer);
161
162         return writer.toString();
163     }
164
165     /**
166      * Gets the xml from object.
167      *
168      * @param <T> the generic type
169      * @param clazz the clazz
170      * @return the xml from object
171      * @throws JAXBException the JAXB exception
172      * @throws IOException
173      */
174     public <T> String getXmlFromObject(T clazz) throws JAXBException, IOException {
175         try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
176             JAXBContext jc = JAXBContext.newInstance(clazz.getClass().getPackage().getName());
177
178             Marshaller marshaller = jc.createMarshaller();
179             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
180             marshaller.marshal(clazz, baos);
181             return baos.toString();
182         }
183     }
184
185     /**
186      * Gets the lookup key.
187      *
188      * @param baseKey the base key
189      * @param lookupHash the lookup hash
190      * @param keyProps the key props
191      * @return the lookup key
192      */
193     public String getLookupKey(String baseKey, HashMap<String, Object> lookupHash, Collection<String> keyProps) {
194         int baseKeyLen = baseKey.length();
195         StringBuffer newKey = new StringBuffer();
196         if (baseKeyLen > 0) {
197             newKey.append(baseKey);
198         }
199
200         Iterator<String> keyPropI = keyProps.iterator();
201         while (keyPropI.hasNext()) {
202             String keyProp = keyPropI.next();
203             if (baseKeyLen > 0) {
204                 newKey.append("&");
205             }
206             newKey.append(keyProp + "=" + lookupHash.get(keyProp));
207         }
208         return newKey.toString();
209     }
210
211     /**
212      * Gets the lookup keys.
213      *
214      * @param lookupHashes the lookup hashes
215      * @param _dbRulesNodeKeyProps the db rules node key props
216      * @return the lookup keys
217      */
218     public String getLookupKeys(LinkedHashMap<String, HashMap<String, Object>> lookupHashes,
219             Multimap<String, String> _dbRulesNodeKeyProps) {
220         Iterator<String> it = lookupHashes.keySet().iterator();
221         String lookupKeys = "";
222         while (it.hasNext()) {
223             String objectType = (String) it.next();
224             HashMap<String, Object> lookupHash = lookupHashes.get(objectType);
225
226             Collection<String> keyProps = _dbRulesNodeKeyProps.get(objectType);
227             Iterator<String> keyPropI = keyProps.iterator();
228             while (keyPropI.hasNext()) {
229                 lookupKeys += lookupHash.get(keyPropI.next());
230             }
231         }
232         return lookupKeys;
233     }
234
235     /**
236      * Gets the example object.
237      *
238      * @param <T> the generic type
239      * @param clazz the clazz
240      * @param singleton the singleton
241      * @return the example object
242      * @throws IllegalAccessException the illegal access exception
243      * @throws IllegalArgumentException the illegal argument exception
244      * @throws InvocationTargetException the invocation target exception
245      * @throws NoSuchMethodException the no such method exception
246      * @throws SecurityException the security exception
247      * @throws AAIException the AAI exception
248      */
249     public <T> void getExampleObject(T clazz, boolean singleton)
250             throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException,
251             SecurityException, AAIException {
252         Method[] methods = clazz.getClass().getDeclaredMethods();
253         String dnHypPropertyName = "";
254         String upCamPropertyName = "";
255         Random rand = new SecureRandom();
256         int randInt = rand.nextInt(10000000);
257
258         for (Method method : methods) {
259             boolean go = false;
260             if (method.getName().startsWith("get")) {
261                 dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, method.getName().substring(3));
262                 upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL, method.getName().substring(3));
263                 go = true;
264             } else if (method.getName().startsWith("is")) {
265                 dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, method.getName().substring(2));
266                 upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL, method.getName().substring(2));
267                 go = true;
268             }
269             // don't return resource-version on a singleton
270             if (singleton && dnHypPropertyName.equals("resource-version")) {
271                 go = false;
272             }
273             if (go) {
274                 String retType = method.getReturnType().getName();
275                 if (!retType.contains("aai") && !retType.contains("java.util.List")) {
276                     // get the setter
277                     Method meth = clazz.getClass().getMethod("set" + upCamPropertyName, method.getReturnType());
278
279                     if (retType.contains("String")) {
280                         String val = "example-" + dnHypPropertyName + "-val-" + randInt;
281                         if (val != null) {
282                             meth.invoke(clazz, val);
283                         }
284                     } else if (retType.toLowerCase().contains("long")) {
285                         Integer foo = rand.nextInt(100000);
286                         meth.invoke(clazz, foo.longValue());
287                     } else if (retType.toLowerCase().contains("int")) {
288                         meth.invoke(clazz, rand.nextInt(100000));
289                     } else if (retType.toLowerCase().contains("short")) {
290                         Integer randShort = rand.nextInt(10000);
291                         meth.invoke(clazz, randShort.shortValue());
292                     } else if (retType.toLowerCase().contains("boolean")) {
293                         meth.invoke(clazz, true);
294                     }
295                     // i think max has a list in license-management
296                 }
297             }
298         }
299     }
300
301     /**
302      * Gets the dynamic example object.
303      *
304      * @param childObject the child object
305      * @param aaiRes the aai res
306      * @param singleton the singleton
307      * @return the dynamic example object
308      */
309     public void getDynamicExampleObject(DynamicEntity childObject, AAIResource aaiRes, boolean singleton) {
310         // TODO Auto-generated method stub
311
312         Random rand = new SecureRandom();
313         Integer randInt = rand.nextInt(100000);
314         long range = 100000000L;
315         long randLong = (long) (rand.nextDouble() * range);
316         Integer randShrt = rand.nextInt(20000);
317         short randShort = randShrt.shortValue();
318
319         for (String dnHypAttrName : aaiRes.getStringFields()) {
320
321             if (singleton && ("resource-version").equals(dnHypAttrName)) {
322                 continue;
323             }
324
325             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
326             childObject.set(dnCamAttrName, "example-" + dnHypAttrName + "-val-" + randInt);
327
328         }
329
330         for (String dnHypAttrName : aaiRes.getStringListFields()) {
331             ArrayList<String> exampleList = new ArrayList<String>();
332             exampleList.add("example-" + dnHypAttrName + "-val-" + randInt + "-" + 1);
333             exampleList.add("example-" + dnHypAttrName + "-val-" + randInt + "-" + 2);
334             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
335             childObject.set(dnCamAttrName, exampleList);
336         }
337
338         // the attrName might need to be converted to camel case!!!
339         for (String dnHypAttrName : aaiRes.getLongFields()) {
340             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
341             childObject.set(dnCamAttrName, randLong);
342         }
343
344         for (String dnHypAttrName : aaiRes.getIntFields()) {
345             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
346             childObject.set(dnCamAttrName, randInt);
347         }
348
349         for (String dnHypAttrName : aaiRes.getShortFields()) {
350             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
351             childObject.set(dnCamAttrName, randShort);
352         }
353
354         for (String dnHypAttrName : aaiRes.getBooleanFields()) {
355             String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
356             childObject.set(dnCamAttrName, Boolean.TRUE);
357         }
358     }
359 }