ExpressionUserMapper implements UserMapper { @Override public void mapUser(Object details, User user) { List<UserAttribute> attributes = new ArrayList<UserAttribute>(); details = preProcessDetails(details); for(String attributeName : attributeMappings.keySet()) { Expression exp = parser.parseExpression(attributeMappings.get(attributeName)); UserAttribute userAttribute = new UserAttribute(); userAttribute.setName(attributeName); Object value = exp.getValue(evaluationContext, details); userAttribute.setValue(value == null ? null : value.toString()); attributes.add(userAttribute); } user.setAttribute(attributes); } ExpressionUserMapper(Map<String, String> attributeMappings); @Override /** * If details is a UserDetailsWithAttributes object, its attributes are mapped to User * attributes. * Each mapping is an SpEL expression using the UserDetailsWithAttributes as a source. * */ void mapUser(Object details, User user); static SpelExpressionParser parser; }
@Test public void testUserDetailsMapping() { MockUserDetailsWithAttributes detailsWithAttributes = new MockUserDetailsWithAttributes(); mapper = new UserDetailsExpressionUserMapper(attributeMappings); User user = new User(); detailsWithAttributes.getAttributes().put("sample", "mock"); attributeMappings.put("transformed", "sample"); mapper.mapUser(detailsWithAttributes, user); assertEquals(1, user.getAttribute().size()); assertEquals("transformed", user.getAttribute().get(0).getName()); assertEquals("mock", user.getAttribute().get(0).getValue()); }
@Test public void testJsonsMapping() { mapper = new JSONExpressionUserMapper(attributeMappings); User user = new User(); attributeMappings.put("transformed", "email"); mapper.mapUser(SAMPLE_JSON, user); assertEquals(1, user.getAttribute().size()); assertEquals("transformed", user.getAttribute().get(0).getName()); assertEquals("myemail@email.com", user.getAttribute().get(0).getValue()); }
@Test public void testMapMapping() { mapper = new MapExpressionUserMapper(attributeMappings); User user = new User(); attributeMappings.put("transformed", "my_email"); Map<String, String> attributes = new HashMap<String, String>(); attributes.put("my_email", "myemail@email.com"); mapper.mapUser(attributes, user); assertEquals(1, user.getAttribute().size()); assertEquals("transformed", user.getAttribute().get(0).getName()); assertEquals("myemail@email.com", user.getAttribute().get(0).getValue()); }