Skip to content

Commit

Permalink
Merge pull request #1110 from HubSpot/fix-npe-type-map
Browse files Browse the repository at this point in the history
More gracefully handle null keys/values in map resolver
  • Loading branch information
mattcoley authored Aug 23, 2023
2 parents ddcc97d + efbc908 commit b964022
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,18 @@ public Object getValue(ELContext context, Object base, Object property) {

if (base instanceof Map && !((Map) base).isEmpty()) {
Iterator<?> iterator = ((Map) base).keySet().iterator();
if (iterator.hasNext()) {
Class<?> keyClass = iterator.next().getClass();
Class<?> keyClass = null;
while (iterator.hasNext()) {
Object nextObject = iterator.next();
if (nextObject != null) {
keyClass = nextObject.getClass();
break;
}
}

if (keyClass == null) {
value = ((Map) base).get(property);
} else {
try {
value = ((Map) base).get(TYPE_CONVERTER.convert(property, keyClass));
if (value != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.hubspot.jinjava.el;

import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;

public class TypeConvertingMapELResolverTest {
private TypeConvertingMapELResolver typeConvertingMapELResolver;

@Before
public void setup() {
typeConvertingMapELResolver = new TypeConvertingMapELResolver(false);
}

@Test
public void itResolvesProperties() {
Map<String, String> values = ImmutableMap.of("1", "value1", "2", "value2");
assertThat(typeConvertingMapELResolver.getValue(new JinjavaELContext(), values, "2"))
.isEqualTo("value2");
}

@Test
public void itConvertsPropertyClassWhenResolvingProperty() {
Map<String, String> values = ImmutableMap.of("1", "value1", "2", "value2");
assertThat(typeConvertingMapELResolver.getValue(new JinjavaELContext(), values, 1))
.isEqualTo("value1");
}

@Test
public void itHandlesNullKeyValuesWhenResolvingProperty() {
Map<String, String> values = new HashMap<>();
values.put(null, "nullValue");
values.put("1", "value1");
values.put("2", "value2");
assertThat(typeConvertingMapELResolver.getValue(new JinjavaELContext(), values, 1))
.isEqualTo("value1");
}

@Test
public void itHandlesMapWithOnlyNullKey() {
Map<String, String> values = new HashMap<>();
values.put(null, "nullValue");
assertThat(typeConvertingMapELResolver.getValue(new JinjavaELContext(), values, 1))
.isEqualTo(null);
}

@Test
public void itResolvesNullPropertyValue() {
Map<String, String> values = new HashMap<>();
values.put(null, "nullValue");
values.put("1", "value1");
values.put("2", "value2");
assertThat(typeConvertingMapELResolver.getValue(new JinjavaELContext(), values, null))
.isEqualTo("nullValue");
}
}

0 comments on commit b964022

Please sign in to comment.