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.nio.charset.Charset;
28 import java.security.SecureRandom;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.LinkedHashMap;
34 import java.util.List;
35 import java.util.Random;
37 import javax.xml.bind.JAXBContext;
38 import javax.xml.bind.JAXBException;
39 import javax.xml.bind.Marshaller;
41 import org.apache.commons.io.output.ByteArrayOutputStream;
42 import org.eclipse.persistence.dynamic.DynamicEntity;
43 import org.eclipse.persistence.jaxb.JAXBMarshaller;
44 import org.eclipse.persistence.jaxb.MarshallerProperties;
45 import org.onap.aai.domain.model.AAIResource;
46 import org.onap.aai.exceptions.AAIException;
48 import com.fasterxml.jackson.annotation.JsonInclude;
49 import com.fasterxml.jackson.core.JsonGenerationException;
50 import com.fasterxml.jackson.databind.DeserializationFeature;
51 import com.fasterxml.jackson.databind.JsonMappingException;
52 import com.fasterxml.jackson.databind.ObjectMapper;
53 import com.fasterxml.jackson.databind.SerializationFeature;
54 import com.fasterxml.jackson.databind.json.JsonMapper;
55 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
56 import com.google.common.base.CaseFormat;
57 import com.google.common.collect.Multimap;
59 public class PojoUtils {
62 * Gets the key value list.
64 * @param <T> the generic type
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
72 public <T> List<KeyValueList> getKeyValueList(Entity e, T clazz)
73 throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
74 List<KeyValueList> kvList = e.getKeyValueList();
76 Method[] methods = clazz.getClass().getDeclaredMethods();
77 String propertyName = "";
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);
88 kv.setValue(value.toString());
100 * Gets the json from object.
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.
109 public <T> String getJsonFromObject(T clazz) throws JsonGenerationException, JsonMappingException, IOException {
110 return getJsonFromObject(clazz, false, true);
114 * Gets the json from object.
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.
125 public <T> String getJsonFromObject(T clazz, boolean wrapRoot, boolean indent)
126 throws JsonGenerationException, JsonMappingException, IOException {
127 ObjectMapper mapper = JsonMapper.builder()
128 .serializationInclusion(JsonInclude.Include.NON_NULL)
129 .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
130 .configure(SerializationFeature.INDENT_OUTPUT, indent)
131 .configure(SerializationFeature.WRAP_ROOT_VALUE, wrapRoot)
132 .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
133 .configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapRoot)
134 .addModule(new JaxbAnnotationModule())
137 return mapper.writeValueAsString(clazz);
141 * Gets the json from dynamic object.
144 * @param jaxbContext the jaxb context
145 * @param includeRoot the include root
146 * @return the json from dynamic object
147 * @throws JsonGenerationException the json generation exception
148 * @throws JsonMappingException the json mapping exception
149 * @throws IOException Signals that an I/O exception has occurred.
150 * @throws JAXBException the JAXB exception
152 public String getJsonFromDynamicObject(DynamicEntity ent, org.eclipse.persistence.jaxb.JAXBContext jaxbContext,
153 boolean includeRoot) throws JsonGenerationException, JsonMappingException, IOException, JAXBException {
154 JAXBMarshaller marshaller = jaxbContext.createMarshaller();
156 marshaller.setProperty(JAXBMarshaller.JAXB_FORMATTED_OUTPUT, false);
157 marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE);
158 marshaller.setProperty("eclipselink.json.include-root", includeRoot);
159 marshaller.setProperty("eclipselink.media-type", "application/json");
160 StringWriter writer = new StringWriter();
161 marshaller.marshal(ent, writer);
163 return writer.toString();
167 * Gets the xml from object.
169 * @param <T> the generic type
170 * @param clazz the clazz
171 * @return the xml from object
172 * @throws JAXBException the JAXB exception
173 * @throws IOException
175 public <T> String getXmlFromObject(T clazz) throws JAXBException, IOException {
176 try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
177 JAXBContext jc = JAXBContext.newInstance(clazz.getClass().getPackage().getName());
179 Marshaller marshaller = jc.createMarshaller();
180 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
181 marshaller.marshal(clazz, baos);
183 return baos.toString(Charset.defaultCharset());
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);