xref: /OpenGrok/opengrok-web/src/main/java/org/opengrok/web/util/DTOUtil.java (revision 5d9f3aa0ca3da3a714233f987fa732f62c0965f6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * See LICENSE.txt included in this distribution for the specific
9  * language governing permissions and limitations under the License.
10  *
11  * When distributing Covered Code, include this CDDL HEADER in each
12  * file and include the License file at LICENSE.txt.
13  * If applicable, add the following below this CDDL HEADER, with the
14  * fields enclosed by brackets "[]" replaced with your own identifying
15  * information: Portions Copyright [yyyy] [name of copyright owner]
16  *
17  * CDDL HEADER END
18  */
19 
20 /*
21  * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
22  */
23 package org.opengrok.web.util;
24 
25 import net.sf.cglib.beans.BeanGenerator;
26 import org.modelmapper.ModelMapper;
27 import org.opengrok.indexer.util.DTOElement;
28 
29 import java.lang.reflect.Field;
30 
31 public class DTOUtil {
DTOUtil()32     private DTOUtil() {
33         // private to ensure static
34     }
35 
36     // ModelMapper is thread-safe and we only need to convert different object types for now
37     // so it should be safe to reuse its instance.
38     private static final ModelMapper modelMapper = new ModelMapper();
39 
40     /**
41      * Generate Data Transfer Object from an object. Any field in the input object
42      * that is annotated with <code>DTOElement</code> will be brought along.
43      * @param object object to use as input
44      * @return DTO with values and generated getters/setters from input object
45      */
createDTO(Object object)46     public static Object createDTO(Object object) {
47         // ModelMapper assumes getters/setters so use BeanGenerator to provide them.
48         BeanGenerator beanGenerator = new BeanGenerator();
49         for (Field field : object.getClass().getDeclaredFields()) {
50             if (field.isAnnotationPresent(DTOElement.class)) {
51                 beanGenerator.addProperty(field.getName(), field.getType());
52             }
53         }
54         Object bean = beanGenerator.create();
55 
56         return modelMapper.map(object, bean.getClass());
57     }
58 }
59