2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.util;
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;
36 import javax.xml.bind.JAXBContext;
37 import javax.xml.bind.JAXBException;
38 import javax.xml.bind.Marshaller;
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;
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;
57 public class PojoUtils {
60 * Gets the key value list.
62 * @param <T> the generic type
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
70 public <T> List<KeyValueList> getKeyValueList(Entity e, T clazz)
71 throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
72 List<KeyValueList> kvList = e.getKeyValueList();
74 Method[] methods = clazz.getClass().getDeclaredMethods();
75 String propertyName = "";
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);
86 kv.setValue(value.toString());
98 * Gets the json from object.
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.
107 public <T> String getJsonFromObject(T clazz) throws JsonGenerationException, JsonMappingException, IOException {
108 return getJsonFromObject(clazz, false, true);
112 * Gets the json from object.
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.
123 public <T> String getJsonFromObject(T clazz, boolean wrapRoot, boolean indent)
124 throws JsonGenerationException, JsonMappingException, IOException {
125 ObjectMapper mapper = new ObjectMapper();
127 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
129 mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
130 mapper.configure(SerializationFeature.INDENT_OUTPUT, indent);
131 mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapRoot);
133 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
134 mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapRoot);
136 mapper.registerModule(new JaxbAnnotationModule());
138 return mapper.writeValueAsString(clazz);
142 * Gets the json from dynamic object.
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
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();
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);
164 return writer.toString();
168 * Gets the xml from object.
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
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());
180 Marshaller marshaller = jc.createMarshaller();
181 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
182 marshaller.marshal(clazz, baos);
183 return baos.toString();
188 * Gets the lookup key.
190 * @param baseKey the base key
191 * @param lookupHash the lookup hash
192 * @param keyProps the key props
193 * @return the lookup key
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);
202 Iterator<String> keyPropI = keyProps.iterator();
203 while (keyPropI.hasNext()) {
204 String keyProp = keyPropI.next();
205 if (baseKeyLen > 0) {
208 newKey.append(keyProp + "=" + lookupHash.get(keyProp));
210 return newKey.toString();
214 * Gets the lookup keys.
216 * @param lookupHashes the lookup hashes
217 * @param _dbRulesNodeKeyProps the db rules node key props
218 * @return the lookup keys
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);
228 Collection<String> keyProps = _dbRulesNodeKeyProps.get(objectType);
229 Iterator<String> keyPropI = keyProps.iterator();
230 while (keyPropI.hasNext()) {
231 lookupKeys += lookupHash.get(keyPropI.next());
238 * Gets the example object.
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
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);
260 for (Method method : methods) {
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));
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));
271 // don't return resource-version on a singleton
272 if (singleton && dnHypPropertyName.equals("resource-version")) {
276 String retType = method.getReturnType().getName();
277 if (!retType.contains("aai") && !retType.contains("java.util.List")) {
279 Method meth = clazz.getClass().getMethod("set" + upCamPropertyName, method.getReturnType());
281 if (retType.contains("String")) {
282 String val = "example-" + dnHypPropertyName + "-val-" + randInt;
284 meth.invoke(clazz, val);
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);
297 // i think max has a list in license-management
304 * Gets the dynamic example object.
306 * @param childObject the child object
307 * @param aaiRes the aai res
308 * @param singleton the singleton
309 * @return the dynamic example object
311 public void getDynamicExampleObject(DynamicEntity childObject, AAIResource aaiRes, boolean singleton) {
312 // TODO Auto-generated method stub
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();
321 for (String dnHypAttrName : aaiRes.getStringFields()) {
323 if (singleton && ("resource-version").equals(dnHypAttrName)) {
327 String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
328 childObject.set(dnCamAttrName, "example-" + dnHypAttrName + "-val-" + randInt);
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);
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);
346 for (String dnHypAttrName : aaiRes.getIntFields()) {
347 String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
348 childObject.set(dnCamAttrName, randInt);
351 for (String dnHypAttrName : aaiRes.getShortFields()) {
352 String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
353 childObject.set(dnCamAttrName, randShort);
356 for (String dnHypAttrName : aaiRes.getBooleanFields()) {
357 String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, dnHypAttrName);
358 childObject.set(dnCamAttrName, Boolean.TRUE);