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