Skip to content

Instantly share code, notes, and snippets.

@gicappa
Last active November 8, 2016 21:32
Show Gist options
  • Save gicappa/02c4d12b8a5ca519d36e577ab1cfbce1 to your computer and use it in GitHub Desktop.
Save gicappa/02c4d12b8a5ca519d36e577ab1cfbce1 to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class SecureMessage {
private final String key;
private final ObjectMapper objectMapper;
public SecureMessage(String key, ObjectMapper objectMapper) {
this.key = key;
this.objectMapper = objectMapper;
}
public Optional<Map> decrypt(String value) {
return Optional.ofNullable(value)
.map(this::decryptJSON)
.map(this::jsonToMap);
}
private HashMap jsonToMap(String value) {
try {
return objectMapper.readValue(value, HashMap.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// Fake Method instead of Util.decryp
private String decryptJSON(String value) {
// should use key to decrypt
return value;
}
}
public class SecureMessageSpec {
private SecureMessage secureMessage;
@Before
public void before() {
secureMessage = new SecureMessage("fake-key", new ObjectMapper());
}
@Test
public void when_value_is_a_json_it_returns_an_optional_map() {
assertThat(secureMessage.decrypt("{\"foo\": \"bar\"}"),
is(Optional.of(ImmutableMap.of("foo", "bar"))));
}
@Test
public void when_value_is_null_it_returns_an_empty_optional() {
assertThat(secureMessage.decrypt(null), is(Optional.empty()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment