├── .gitignore ├── jackson-nestedpropfilter ├── src │ ├── test │ │ └── java │ │ │ └── rk │ │ │ └── prod │ │ │ └── jackson │ │ │ ├── datatype │ │ │ ├── Pojo3.java │ │ │ ├── Pojo.java │ │ │ └── Pojo2.java │ │ │ └── NestedBeanPropertyFilterTest.java │ └── main │ │ └── java │ │ └── rk │ │ └── prod │ │ └── jackson │ │ ├── NestedPropertyFilterProvider.java │ │ ├── JacksonClassAttribute.java │ │ ├── JacksonAttributeBuilder.java │ │ ├── NestedBeanPropertyFilter.java │ │ └── JacksonClassAttributeCache.java ├── pom.xml └── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | */*.iml 2 | */target 3 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/src/test/java/rk/prod/jackson/datatype/Pojo3.java: -------------------------------------------------------------------------------- 1 | package rk.prod.jackson.datatype; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFilter; 4 | 5 | /** 6 | * Created by igreenfi on 11/13/2016. 7 | */ 8 | @JsonFilter("nestedPropertyFilter") 9 | public class Pojo3 { 10 | private String a; 11 | private Integer b; 12 | 13 | public Pojo3(String a, Integer b) { 14 | this.a = a; 15 | this.b = b; 16 | } 17 | 18 | public String getA() { 19 | return a; 20 | } 21 | 22 | public void setA(String a) { 23 | this.a = a; 24 | } 25 | 26 | public Integer getB() { 27 | return b; 28 | } 29 | 30 | public void setB(Integer b) { 31 | this.b = b; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/src/test/java/rk/prod/jackson/datatype/Pojo.java: -------------------------------------------------------------------------------- 1 | package rk.prod.jackson.datatype; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFilter; 4 | 5 | /** 6 | * Created by igreenfi on 11/13/2016. 7 | */ 8 | @JsonFilter("nestedPropertyFilter") 9 | public class Pojo { 10 | private String a; 11 | private Integer b; 12 | private Pojo2 c; 13 | 14 | public Pojo(String a, Integer b, Pojo2 c) { 15 | this.a = a; 16 | this.b = b; 17 | this.c = c; 18 | } 19 | 20 | public String getA() { 21 | return a; 22 | } 23 | 24 | public void setA(String a) { 25 | this.a = a; 26 | } 27 | 28 | public Integer getB() { 29 | return b; 30 | } 31 | 32 | public void setB(Integer b) { 33 | this.b = b; 34 | } 35 | 36 | public Pojo2 getC() { 37 | return c; 38 | } 39 | 40 | public void setC(Pojo2 c) { 41 | this.c = c; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/src/test/java/rk/prod/jackson/datatype/Pojo2.java: -------------------------------------------------------------------------------- 1 | package rk.prod.jackson.datatype; 2 | 3 | import com.fasterxml.jackson.annotation.JsonFilter; 4 | 5 | /** 6 | * Created by igreenfi on 11/13/2016. 7 | */ 8 | @JsonFilter("nestedPropertyFilter") 9 | public class Pojo2 { 10 | private String a; 11 | private Integer b; 12 | private Pojo3 c; 13 | 14 | public Pojo2(String a, Integer b, Pojo3 c) { 15 | this.a = a; 16 | this.b = b; 17 | this.c = c; 18 | } 19 | 20 | public String getA() { 21 | return a; 22 | } 23 | 24 | public void setA(String a) { 25 | this.a = a; 26 | } 27 | 28 | public Integer getB() { 29 | return b; 30 | } 31 | 32 | public void setB(Integer b) { 33 | this.b = b; 34 | } 35 | 36 | public Pojo3 getC() { 37 | return c; 38 | } 39 | 40 | public void setC(Pojo3 c) { 41 | this.c = c; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jackson-nested-prop-filter 2 | jackson-nested-prop-filter 3 | 4 | Let's you filter Jackson nested class properties without any (hardly noticeable) performance overhead. Your typical Spring 4.2+ controller can be modified as follows: 5 | 6 | 7 | 8 | ``` 9 | FilterProvider customJsonFilterProvider; 10 | 11 | @PostConstruct 12 | public void setup(){ 13 | customJsonFilterProvider = new NestedPropertyFilterProvider() 14 | .addFilter("nestedPropertyFilter", 15 | NestedBeanPropertyFilter.filterOutAllExcept(YourVO.class, "prop1", "prop1.prop2", "prop1.prop2.prop3")); 16 | ... 17 | 18 | 19 | @RequestMapping(method = RequestMethod.POST, value = "/springjsonfilter") 20 | public @ResponseBody MappingJacksonValue jsonFilter() { 21 | YourVO responseVO = helper.yourVOs(); 22 | MappingJacksonValue jacksonValue = new MappingJacksonValue(responseVO); 23 | jacksonValue.setFilters(customJsonFilterProvider); 24 | return jacksonValue; 25 | } 26 | ``` 27 | 28 | of course, all entities that are being filtered should have the @JsonFilter("nestedPropertyFilter") with the correct filter name so object mapper correctly picks the right filter with the name: "nestedPropertyFilter" 29 | 30 | ``` 31 | public class CustomObjectMapper extends ObjectMapper{ 32 | 33 | private static final long serialVersionUID = 1L; 34 | 35 | public CustomObjectMapper() { 36 | super(); 37 | this.registerModule(new AfterburnerModule()); 38 | this.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false)); 39 | this.addMixIn(Object.class, NestedBeanPropertyFilter.class); 40 | } 41 | 42 | } 43 | ``` 44 | 45 | 46 | you can use * as part of the path it mean all the attributes of the field. 47 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/src/main/java/rk/prod/jackson/NestedPropertyFilterProvider.java: -------------------------------------------------------------------------------- 1 | package rk.prod.jackson; 2 | 3 | import com.fasterxml.jackson.databind.ser.PropertyFilter; 4 | import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; 5 | import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; 6 | 7 | /** 8 | * NestedPropertyFilterProvider provides a SimpleBeanPropertyFilter based on 9 | * the class type using NestedBeanPropertyFilter 10 | * A NestedPropertyFilterProvider should be added with a specific filter ID 11 | * that is also defined for all classes annotated with JsonFilter 12 | */ 13 | public class NestedPropertyFilterProvider extends SimpleFilterProvider { 14 | 15 | private static final long serialVersionUID = 1L; 16 | 17 | public PropertyFilter findPropertyFilter(Object filterId, Object valueToFilter) { 18 | PropertyFilter filter = _filtersById.get(filterId); 19 | 20 | if (filter instanceof NestedBeanPropertyFilter) { 21 | 22 | // get filter for class 23 | filter = ((NestedBeanPropertyFilter) filter).findPropertyFilter(valueToFilter.getClass()); 24 | 25 | if (filter == null) { 26 | filter = _defaultFilter; 27 | if (filter == null && _cfgFailOnUnknownId) { 28 | throw new IllegalArgumentException("No filter configured with id '" + filterId + "' (type " 29 | + filterId.getClass().getName() + ")"); 30 | } 31 | } 32 | return filter; 33 | } else { 34 | return super.findPropertyFilter(filterId, valueToFilter); 35 | } 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/src/main/java/rk/prod/jackson/JacksonClassAttribute.java: -------------------------------------------------------------------------------- 1 | package rk.prod.jackson; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | /** 8 | * JacksonClassAttribute represents a Jackson entity class with getters and setters 9 | * containing all properties that need to be serialized, in the case of 10 | * nested class attributes, the property itself can be another JacksonClassAttribute 11 | */ 12 | public class JacksonClassAttribute { 13 | 14 | /* current class type 15 | */ 16 | private final Class clazz; 17 | 18 | /* 19 | * -> all primitive/wrapper type properties will have a value of null in map 20 | * as they don't have getters and setters are are not nested 21 | * -> all object instances which have their own properties with 22 | * getters and setters are nested properties for this entity 23 | * that Jackson needs to serialize and hence will have a value JacksonClassAttribute in map 24 | * 25 | * Root entity properties a, b.c, b.c.d, e will be stored in map as 26 | * , , 27 | * where bClassAttribute will be stored as and so on 28 | * 29 | * This could have been a tree 30 | */ 31 | private final Map attributes = new HashMap<>(); 32 | 33 | /* attributes containing same class 34 | * required for filter to return JacksonClassAttribute based on object class 35 | * being filtered, if the result has more than 1, then we use the jgen context 36 | * 37 | * final Map, Set> reverseAttributes = new HashMap<>(); 38 | */ 39 | 40 | public JacksonClassAttribute(Class clazz) { 41 | this.clazz = clazz; 42 | } 43 | 44 | public Class getClazz() { 45 | return clazz; 46 | } 47 | 48 | public Map getAttributes() { 49 | return attributes; 50 | } 51 | 52 | @Override 53 | public String toString() { 54 | return "JacksonClassAttribute [class=" + clazz 55 | + ", attributes=" + Arrays.toString(attributes.entrySet().toArray()) + "]"; 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/src/main/java/rk/prod/jackson/JacksonAttributeBuilder.java: -------------------------------------------------------------------------------- 1 | package rk.prod.jackson; 2 | 3 | import org.springframework.beans.BeanUtils; 4 | 5 | import java.beans.PropertyDescriptor; 6 | import java.lang.reflect.Field; 7 | import java.lang.reflect.ParameterizedType; 8 | import java.util.Map; 9 | import java.util.Set; 10 | 11 | public class JacksonAttributeBuilder { 12 | 13 | private static final String JAVA_LANG_CLASS = "java.lang.Class"; 14 | 15 | public static JacksonClassAttribute getBeanUtilsNestedJsonAttribute(Class clazz, 16 | Map, JacksonClassAttribute> nonNestedAttributeMap, 17 | Set> classes) throws Exception { 18 | JacksonClassAttribute jsonAttribute = new JacksonClassAttribute(clazz); 19 | PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(clazz); 20 | for (PropertyDescriptor descr : descriptors) { 21 | // if you want values, use: descr.getValue(attributeName) 22 | if (descr.getPropertyType().getName().equals(JAVA_LANG_CLASS)) { 23 | continue; 24 | } 25 | // a primitive, a CharSequence(String), Number, Date, URI, URL, Locale, Class, or corresponding array 26 | // or add more like UUID or other types 27 | if (!BeanUtils.isSimpleProperty(descr.getPropertyType())) { 28 | Field collectionField = clazz.getDeclaredField(descr.getName()); 29 | if (collectionField.getGenericType() instanceof ParameterizedType) { 30 | ParameterizedType listType = (ParameterizedType) collectionField.getGenericType(); 31 | Class actualClazz = (Class) listType.getActualTypeArguments()[0]; 32 | 33 | JacksonClassAttribute attribute = getBeanUtilsNestedJsonAttribute(actualClazz, nonNestedAttributeMap, classes); 34 | jsonAttribute.getAttributes().put(descr.getName(), attribute); 35 | classes.add(actualClazz); 36 | } else { // or a complex custom type to get nested fields 37 | JacksonClassAttribute attribute = getBeanUtilsNestedJsonAttribute(descr.getPropertyType(), nonNestedAttributeMap, classes); 38 | jsonAttribute.getAttributes().put(descr.getName(), attribute); 39 | classes.add(descr.getPropertyType()); 40 | } 41 | } else { 42 | jsonAttribute.getAttributes().put(descr.getDisplayName(), null); 43 | } 44 | } 45 | 46 | nonNestedAttributeMap.put(clazz, jsonAttribute); 47 | return jsonAttribute; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/src/main/java/rk/prod/jackson/NestedBeanPropertyFilter.java: -------------------------------------------------------------------------------- 1 | package rk.prod.jackson; 2 | 3 | import com.fasterxml.jackson.core.JsonGenerator; 4 | import com.fasterxml.jackson.databind.SerializerProvider; 5 | import com.fasterxml.jackson.databind.ser.PropertyWriter; 6 | import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Map.Entry; 11 | 12 | /** 13 | * NestedBeanPropertyFilter contains all property filters per class 14 | * contained in a json root entity class 15 | *

16 | * FYI: A class has a different meaning in the context of Jackson i.e., 17 | * a class that has getters and setters and can generate nested attributes 18 | * for Jackson 19 | */ 20 | public class NestedBeanPropertyFilter extends SimpleBeanPropertyFilter { 21 | 22 | public static SimpleBeanPropertyFilter filterOutAllExcept(Class clazz, String... propertyArray) { 23 | return new NestedBeanPropertyFilter(clazz, propertyArray); 24 | } 25 | 26 | private Map, SimpleBeanPropertyFilter> classLevelBeanPropertyFilter = new HashMap<>(); 27 | 28 | /** 29 | * Construct filter based on many nested properties as follows 30 | * prop1, classAObj.class1Obj.prop2, classAObj.class2Obj, prop3 31 | * 32 | * @param properties 33 | */ 34 | private NestedBeanPropertyFilter(Class clazz, final String... properties) { 35 | 36 | Map, JacksonClassAttribute> classLevelJsonAttribute = JacksonClassAttributeCache.generateClassLevelJsonAttribute( 37 | clazz, properties); 38 | 39 | for (Entry, JacksonClassAttribute> entry : classLevelJsonAttribute.entrySet()) { 40 | classLevelBeanPropertyFilter.put(entry.getKey(), SimpleBeanPropertyFilter.filterOutAllExcept(entry.getValue().getAttributes().keySet())); 41 | } 42 | } 43 | 44 | public SimpleBeanPropertyFilter findPropertyFilter(Class clazz) { 45 | return classLevelBeanPropertyFilter.get(clazz); 46 | } 47 | 48 | // TODO: eventually check what is the jgen.context immediate parent 49 | // for this class, a class can only have unique property names 50 | // so there is no chance of collision 51 | // i.e., two properties one ClassA obj1, ClassA obj2, here obj1, obj2 52 | // are different names, this can be delayed based on the whether 53 | // there are multiple propertyFilters for the same class to then filter 54 | // by the size() of the map > 1 55 | @Override 56 | public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) 57 | throws Exception { 58 | SimpleBeanPropertyFilter propertyFilter = classLevelBeanPropertyFilter.get(pojo.getClass()); 59 | propertyFilter.serializeAsField(pojo, jgen, provider, writer); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/src/test/java/rk/prod/jackson/NestedBeanPropertyFilterTest.java: -------------------------------------------------------------------------------- 1 | package rk.prod.jackson; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; 6 | import org.junit.Assert; 7 | import org.junit.Before; 8 | import org.junit.Rule; 9 | import org.junit.Test; 10 | import org.junit.rules.TestName; 11 | import rk.prod.jackson.datatype.Pojo; 12 | import rk.prod.jackson.datatype.Pojo2; 13 | import rk.prod.jackson.datatype.Pojo3; 14 | 15 | /** 16 | * Created by igreenfi on 11/13/2016. 17 | */ 18 | public class NestedBeanPropertyFilterTest { 19 | 20 | @Rule 21 | public TestName name = new TestName(); 22 | 23 | @Before 24 | public void before() { 25 | System.out.println(name.getMethodName()); 26 | } 27 | 28 | Pojo pojo = new Pojo("a", 2, new Pojo2("c.a", 4, new Pojo3("c.c.a", 7))); 29 | 30 | private SimpleFilterProvider p = new NestedPropertyFilterProvider().addFilter("nestedPropertyFilter", NestedBeanPropertyFilter.filterOutAllExcept(Pojo.class, "a", "c.c", "c.a")); 31 | 32 | private SimpleFilterProvider p1 = new NestedPropertyFilterProvider().addFilter("nestedPropertyFilter", NestedBeanPropertyFilter.filterOutAllExcept(Pojo.class, "a", "c.c.*", "c.a")); 33 | 34 | private SimpleFilterProvider p2 = new NestedPropertyFilterProvider().addFilter("nestedPropertyFilter", NestedBeanPropertyFilter.filterOutAllExcept(Pojo.class, "a", "c.*")); 35 | 36 | private SimpleFilterProvider p3 = new NestedPropertyFilterProvider().addFilter("nestedPropertyFilter", NestedBeanPropertyFilter.filterOutAllExcept(Pojo.class, "*")); 37 | 38 | @Test 39 | public void astrixOnPrimitiveValueTest() throws JsonProcessingException { 40 | new NestedPropertyFilterProvider().addFilter("nestedPropertyFilter", NestedBeanPropertyFilter.filterOutAllExcept(Pojo.class, "a.*")); 41 | } 42 | 43 | @Test 44 | public void nestAfterAstrixTest() throws JsonProcessingException { 45 | new NestedPropertyFilterProvider().addFilter("nestedPropertyFilter", NestedBeanPropertyFilter.filterOutAllExcept(Pojo.class, "c.*.a")); 46 | } 47 | 48 | @Test 49 | public void serializeTest() throws JsonProcessingException { 50 | 51 | ObjectMapper objectMapper = new ObjectMapper(); 52 | 53 | objectMapper.setFilterProvider(p); 54 | 55 | String valueAsString = objectMapper.writeValueAsString(pojo); 56 | 57 | System.out.println(valueAsString); 58 | 59 | Assert.assertEquals("{\"a\":\"a\",\"c\":{\"a\":\"c.a\",\"c\":{}}}", valueAsString); 60 | } 61 | 62 | @Test 63 | public void serializeWithAstrixTest() throws JsonProcessingException { 64 | ObjectMapper objectMapper = new ObjectMapper(); 65 | 66 | objectMapper.setFilterProvider(p1); 67 | 68 | String valueAsString = objectMapper.writeValueAsString(pojo); 69 | 70 | System.out.println(valueAsString); 71 | 72 | Assert.assertEquals("{\"a\":\"a\",\"c\":{\"a\":\"c.a\",\"c\":{\"a\":\"c.c.a\",\"b\":7}}}", valueAsString); 73 | } 74 | 75 | @Test 76 | public void serializeWithAstrix2Test() throws JsonProcessingException { 77 | ObjectMapper objectMapper = new ObjectMapper(); 78 | 79 | objectMapper.setFilterProvider(p2); 80 | 81 | String valueAsString = objectMapper.writeValueAsString(pojo); 82 | 83 | System.out.println(valueAsString); 84 | 85 | Assert.assertEquals("{\"a\":\"a\",\"c\":{\"a\":\"c.a\",\"b\":4,\"c\":{\"a\":\"c.c.a\",\"b\":7}}}", valueAsString); 86 | } 87 | 88 | @Test 89 | public void serializeWithAstrix3Test() throws JsonProcessingException { 90 | ObjectMapper objectMapper = new ObjectMapper(); 91 | 92 | objectMapper.setFilterProvider(p3); 93 | 94 | String valueAsString = objectMapper.writeValueAsString(pojo); 95 | 96 | System.out.println(valueAsString); 97 | 98 | Assert.assertEquals("{\"a\":\"a\",\"b\":2,\"c\":{\"a\":\"c.a\",\"b\":4,\"c\":{\"a\":\"c.c.a\",\"b\":7}}}", valueAsString); 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | rk.prod.jackson 5 | jackson-nestedpropfilter 6 | 0.0.4 7 | dynamic nested class property filter 8 | filter specific nested class properties dynamically - caches class property meta data to improve 9 | performance 10 | 11 | 12 | 13 | Apache License Version 2.0 14 | http://www.apache.org/licenses/LICENSE-2.0.txt 15 | 16 | 17 | 18 | UTF-8 19 | 4.2.5.RELEASE 20 | 2.6.5 21 | 1.7 22 | 20.0 23 | 3.4 24 | 1.8.3 25 | 26 | 27 | 28 | 29 | 30 | org.springframework 31 | spring-beans 32 | ${spring.version} 33 | 34 | 35 | commons-beanutils 36 | commons-beanutils 37 | ${commons-beanutils.version} 38 | 39 | 40 | 41 | 42 | com.fasterxml.jackson.core 43 | jackson-databind 44 | ${jackson.version} 45 | 46 | 47 | 48 | com.google.guava 49 | guava 50 | ${guava.version} 51 | 52 | 53 | org.apache.commons 54 | commons-lang3 55 | ${commons-lang3.version} 56 | 57 | 58 | 65 | 66 | 67 | junit 68 | junit 69 | 4.12 70 | test 71 | 72 | 73 | 74 | 75 | 76 | 77 | org.apache.maven.plugins 78 | maven-source-plugin 79 | 2.2.1 80 | 81 | 82 | attach-sources 83 | 84 | jar 85 | 86 | 87 | 88 | 89 | 90 | org.apache.maven.plugins 91 | maven-surefire-plugin 92 | 2.18.1 93 | 94 | false 95 | 96 | 97 | 98 | org.apache.maven.plugins 99 | maven-eclipse-plugin 100 | 2.9 101 | 102 | true 103 | false 104 | 2.0 105 | 106 | 107 | 108 | org.apache.maven.plugins 109 | maven-compiler-plugin 110 | 2.3.2 111 | 112 | ${jdk.version} 113 | ${jdk.version} 114 | 115 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/src/main/java/rk/prod/jackson/JacksonClassAttributeCache.java: -------------------------------------------------------------------------------- 1 | package rk.prod.jackson; 2 | 3 | import com.google.common.base.Splitter; 4 | import com.google.common.collect.Lists; 5 | import org.apache.commons.lang3.builder.EqualsBuilder; 6 | import org.apache.commons.lang3.builder.HashCodeBuilder; 7 | 8 | import java.util.*; 9 | import java.util.concurrent.ConcurrentHashMap; 10 | 11 | /** 12 | * Cache that stores JsonClassAttributes - i.e., all nested attributes 13 | * (java primitive/wrapper type properties and other class instances) 14 | * per "Json Root entity" class as well 15 | * as JacksonClassAttribute per individual class 16 | *

17 | * FYI: A class has a different meaning in the context of Jackson i.e., 18 | * a class that has getters and setters and can generate nested attributes 19 | * for Jackson 20 | */ 21 | public class JacksonClassAttributeCache { 22 | 23 | private static final Splitter dotSplitter = Splitter.on('.') 24 | .trimResults() 25 | .omitEmptyStrings(); 26 | 27 | private static final ArrayList PROP_ASTRIX = Lists.newArrayList("*"); 28 | 29 | private static final Map, JacksonClassAttribute>> cacheGlobal = new ConcurrentHashMap<>(); 30 | 31 | // TODO: pre populate json class attribute map for ONLY root entities 32 | private static final Map, JacksonClassAttribute> rootEntityNestedAttrMap = new ConcurrentHashMap<>(); 33 | 34 | // only has attributes for the current class but includes all classes that 35 | // NEED NOT BE root entities 36 | private static final Map, JacksonClassAttribute> nonNestedAttrMap = new ConcurrentHashMap<>(); 37 | 38 | // all classes (nested) contained within a root class 39 | private static final Map, Set>> nestedClassesMap = new ConcurrentHashMap<>(); 40 | 41 | private static JacksonClassAttribute generateJsonAttribute(Class clazz) { 42 | JacksonClassAttribute classAttribute = rootEntityNestedAttrMap.get(clazz); 43 | if (classAttribute == null) { 44 | try { 45 | Set> nestedClasses = new HashSet<>(); 46 | classAttribute = JacksonAttributeBuilder.getBeanUtilsNestedJsonAttribute( 47 | clazz, nonNestedAttrMap, nestedClasses); 48 | nestedClassesMap.put(clazz, nestedClasses); 49 | } catch (Exception e) { 50 | throw new RuntimeException(e); 51 | } 52 | rootEntityNestedAttrMap.put(clazz, classAttribute); 53 | } 54 | return classAttribute; 55 | } 56 | 57 | /* 58 | * returns a JacksonClassAttribute tree limited to the nested properties provided 59 | * a << root class 60 | * b c << first level attributes 61 | *e f g h << second level nested attributes 62 | *... 63 | */ 64 | public static JacksonClassAttribute generateRootEntityNestedJsonAttribute(Class clazz, String... properties) { 65 | JacksonClassAttribute srcAttribute = generateJsonAttribute(clazz); 66 | JacksonClassAttribute destAttribute = new JacksonClassAttribute(clazz); 67 | for (String prop : properties) { 68 | copyAttribute(srcAttribute, destAttribute, dotSplitter.splitToList(prop), null); 69 | } 70 | return destAttribute; 71 | } 72 | 73 | /* 74 | * returns a JacksonClassAttribute tree limited to the nested properties provided 75 | * a << root class 76 | * b c << first level attributes 77 | *e f g h << second level nested attributes 78 | *... 79 | */ 80 | public static Map, JacksonClassAttribute> generateClassLevelJsonAttribute(Class clazz, String... properties) { 81 | KeyHolder key = new KeyHolder(clazz, properties); 82 | Map, JacksonClassAttribute> result = cacheGlobal.get(key); 83 | if (result == null) { 84 | result = new HashMap<>(); 85 | JacksonClassAttribute srcAttribute = generateJsonAttribute(clazz); 86 | for (String prop : properties) { 87 | copyAttribute(srcAttribute, result, dotSplitter.splitToList(prop)); 88 | } 89 | cacheGlobal.put(key, result); 90 | } 91 | return result; 92 | } 93 | 94 | private static void copyAttribute(JacksonClassAttribute src, Map, JacksonClassAttribute> destClassMap, List splitProp) { 95 | JacksonClassAttribute dest = null; 96 | if ((dest = destClassMap.get(src.getClazz())) == null) { 97 | dest = new JacksonClassAttribute(src.getClazz()); 98 | destClassMap.put(src.getClazz(), dest); 99 | } 100 | 101 | copyAttribute(src, dest, splitProp, destClassMap); 102 | } 103 | 104 | // i starts at 0 105 | // use validate flag if required to check if it does exist 106 | private static void copyAttribute(JacksonClassAttribute src, JacksonClassAttribute dest, List splitProp, Map, JacksonClassAttribute> destClassMap) { 107 | // TODO: validate that current root entries: src/dest cannot be null 108 | for (String prop : splitProp) { 109 | 110 | if (prop.equals("*")) { 111 | //if someone configure on primitive value * skip it. 112 | if (src == null) { 113 | break; 114 | } 115 | 116 | Map srcAttributes = src.getAttributes(); 117 | for (Map.Entry attributeEntry : srcAttributes.entrySet()) { 118 | String key = attributeEntry.getKey(); 119 | JacksonClassAttribute destNestedAttribute = dest.getAttributes().get(key); 120 | if (destNestedAttribute == null) { 121 | JacksonClassAttribute srcJacksonClassAttribute = attributeEntry.getValue(); 122 | if (srcJacksonClassAttribute != null) { // save property with ClassAttribute value 123 | destNestedAttribute = new JacksonClassAttribute(srcJacksonClassAttribute.getClazz()); 124 | dest.getAttributes().put(key, destNestedAttribute); 125 | if (destClassMap != null) { 126 | destClassMap.put(attributeEntry.getValue().getClazz(), destNestedAttribute); 127 | } 128 | copyAttribute(srcJacksonClassAttribute, destNestedAttribute, PROP_ASTRIX, destClassMap); 129 | } else { // save property with null value 130 | dest.getAttributes().put(key, null); // null 131 | } 132 | } else { 133 | 134 | } 135 | } 136 | break; 137 | } else { 138 | boolean inSrc = src.getAttributes().containsKey(prop); 139 | if (!inSrc) { // validation error? 140 | return; 141 | } 142 | // else, this is a valid entry in src 143 | 144 | // copy the value from src attribute map to dest based on value type 145 | JacksonClassAttribute srcNestedAttribute = src.getAttributes().get(prop); 146 | JacksonClassAttribute destNestedAttribute = dest.getAttributes().get(prop); 147 | if (destNestedAttribute == null) { 148 | if (srcNestedAttribute != null) { // save property with ClassAttribute value 149 | destNestedAttribute = new JacksonClassAttribute(srcNestedAttribute.getClazz()); 150 | dest.getAttributes().put(prop, destNestedAttribute); 151 | if (destClassMap != null) { 152 | destClassMap.put(srcNestedAttribute.getClazz(), destNestedAttribute); 153 | } 154 | } else { // save property with null value 155 | dest.getAttributes().put(prop, null); // null 156 | } 157 | } else { 158 | // destination already has this field // validation error? 159 | // validate that they are the same type, but previously if it is a property type 160 | // above iteration takes care of overwriting 161 | } 162 | 163 | src = srcNestedAttribute; 164 | dest = destNestedAttribute; 165 | } 166 | } 167 | } 168 | 169 | 170 | static class KeyHolder { 171 | 172 | private final Class clazz; 173 | 174 | private final String[] properties; 175 | 176 | public KeyHolder(Class clazz, String[] properties) { 177 | this.clazz = clazz; 178 | this.properties = properties; 179 | } 180 | 181 | @Override 182 | public boolean equals(Object o) { 183 | if (this == o) return true; 184 | 185 | if (o == null || getClass() != o.getClass()) return false; 186 | 187 | KeyHolder keyHolder = (KeyHolder) o; 188 | 189 | return new EqualsBuilder() 190 | .append(clazz, keyHolder.clazz) 191 | .append(properties, keyHolder.properties) 192 | .isEquals(); 193 | } 194 | 195 | @Override 196 | public int hashCode() { 197 | return new HashCodeBuilder(17, 37) 198 | .append(clazz) 199 | .append(properties) 200 | .toHashCode(); 201 | } 202 | 203 | @Override 204 | public String toString() { 205 | final StringBuffer sb = new StringBuffer("KeyHolder{"); 206 | sb.append("clazz=").append(clazz); 207 | sb.append(", properties=").append(properties == null ? "null" : Arrays.asList(properties).toString()); 208 | sb.append('}'); 209 | return sb.toString(); 210 | } 211 | } 212 | 213 | } 214 | -------------------------------------------------------------------------------- /jackson-nestedpropfilter/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------