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