Reduce the number of problems in aai-common by removing unused imports
[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.databind.json.JsonMapper;
30 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
31 import com.google.common.base.CaseFormat;
32 import com.google.common.collect.Multimap;
33
34 import java.io.IOException;
35 import java.io.StringWriter;
36 import java.lang.reflect.InvocationTargetException;
37 import java.lang.reflect.Method;
38 import java.nio.charset.Charset;
39 import java.security.SecureRandom;
40 import java.util.ArrayList;
41 import java.util.Collection;
42 import java.util.HashMap;
43 import java.util.Iterator;
44 import java.util.LinkedHashMap;
45 import java.util.List;
46 import java.util.Random;
47
48 import javax.xml.bind.JAXBContext;
49 import javax.xml.bind.JAXBException;
50 import javax.xml.bind.Marshaller;
51
52 import org.apache.commons.io.output.ByteArrayOutputStream;
53 import org.eclipse.persistence.dynamic.DynamicEntity;
54 import org.eclipse.persistence.jaxb.JAXBMarshaller;
55 import org.eclipse.persistence.jaxb.MarshallerProperties;
56 import org.onap.aai.domain.model.AAIResource;
57 import org.onap.aai.exceptions.AAIException;
58
59 public class PojoUtils {
60
61     /**
62      * Gets the key value list.
63      *
64      * @param <T> the generic type
65      * @param e the e
66      * @param clazz the clazz
67      * @return the key value list
68      * @throws IllegalAccessException the illegal access exception
69      * @throws IllegalArgumentException the illegal argument exception
70      * @throws InvocationTargetException the invocation target exception
71      */
72     public <T> List<KeyValueList> getKeyValueList(Entity e, T clazz)
73             throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
74         List<KeyValueList> kvList = e.getKeyValueList();
75         Object value = null;
76         Method[] methods = clazz.getClass().getDeclaredMethods();
77         String propertyName = "";
78
79         for (Method method : methods) {
80             if (method.getName().startsWith("get")) {
81                 propertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, method.getName().substring(3));
82                 if (!(method.getReturnType().getName().contains("aai"))
83                         || method.getReturnType().getName().contains("java.util.List")) {
84                     value = method.invoke(clazz);
85                     KeyValueList kv = new KeyValueList();
86                     kv.setKey(propertyName);
87                     if (value != null) {
88                         kv.setValue(value.toString());
89                     } else {
90                         kv.setValue("");
91                     }
92                     kvList.add(kv);
93                 }
94             }
95         }
96         return kvList;
97     }
98
99     /**
100      * Gets the json from object.
101      *
102      * @param <T> the generic type
103      * @param clazz the clazz
104      * @return the json from object
105      * @throws JsonGenerationException the json generation exception
106      * @throws JsonMappingException the json mapping exception
107      * @throws IOException Signals that an I/O exception has occurred.
108      */
109     public <T> String getJsonFromObject(T clazz) throws JsonGenerationException, JsonMappingException, IOException {
110         return getJsonFromObject(clazz, false, true);
111     }
112
113     /**
114      * Gets the json from object.
115      *
116      * @param <T> the generic type
117      * @param clazz the clazz
118      * @param wrapRoot the wrap root
119      * @param indent the indent
120      * @return the json from object
121      * @throws JsonGenerationException the json generation exception
122      * @throws JsonMappingException the json mapping exception
123      * @throws IOException Signals that an I/O exception has occurred.
124      */
125     public <T> String getJsonFromObject(T clazz, boolean wrapRoot, boolean indent)
126             throws JsonGenerationException, JsonMappingException, IOException {
127         ObjectMapper mapper = JsonMapper.builder().serializationInclusion(JsonInclude.Include.NON_NULL)
128                 .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
129                 .configure(SerializationFeature.INDENT_OUTPUT, indent)
130                 .configure(SerializationFeature.WRAP_ROOT_VALUE, wrapRoot)
131                 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
132                 .configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapRoot).addModule(new JaxbAnnotationModule())
133                 .build();
134
135         return mapper.writeValueAsString(clazz);
136     }
137
138     /**
139      * Gets the json from dynamic object.
140      *
141      * @param ent the ent
142      * @param jaxbContext the jaxb context
143      * @param includeRoot the include root
144      * @return the json from dynamic object
145      * @throws JsonGenerationException the json generation exception
146      * @throws JsonMappingException the json mapping exception
147      * @throws IOException Signals that an I/O exception has occurred.
148      * @throws JAXBException the JAXB exception
149      */
150     public String getJsonFromDynamicObject(DynamicEntity ent, org.eclipse.persistence.jaxb.JAXBContext jaxbContext,
151             boolean includeRoot) throws JsonGenerationException, JsonMappingException, IOException, JAXBException {
152         JAXBMarshaller marshaller = jaxbContext.createMarshaller();
153
154         marshaller.setProperty(JAXBMarshaller.JAXB_FORMATTED_OUTPUT, false);
155         marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE);
156         marshaller.setProperty("eclipselink.json.include-root", includeRoot);
157         marshaller.setProperty("eclipselink.media-type", "application/json");
158         StringWriter writer = new StringWriter();
159         marshaller.marshal(ent, writer);
160
161         return writer.toString();
162     }
163
164     /**
165      * Gets the xml from object.
166      *
167      * @param <T> the generic type
168      * @param clazz the clazz
169      * @return the xml from object
170      * @throws JAXBException the JAXB exception
171      * @throws IOException
172      */
173     public <T> String getXmlFromObject(T clazz) throws JAXBException, IOException {
174         try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
175             JAXBContext jc = JAXBContext.newInstance(clazz.getClass().getPackage().getName());
176
177             Marshaller marshaller = jc.createMarshaller();
178             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
179             marshaller.marshal(clazz, baos);
180
181             return baos.toString(Charset.defaultCharset());
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 }