Last active
November 8, 2016 21:32
-
-
Save gicappa/02c4d12b8a5ca519d36e577ab1cfbce1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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