Last active
August 29, 2015 14:23
-
-
Save disc99/2d30f21f380f2b12d721 to your computer and use it in GitHub Desktop.
This file contains 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
package functionaljava.either; | |
import java.io.BufferedReader; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.net.URL; | |
import org.junit.Test; | |
import com.fasterxml.jackson.databind.JsonNode; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import fj.Effect; | |
import fj.F; | |
import fj.data.Either; | |
import fj.function.Effect1; | |
public class FunctionalJavaEitherTest { | |
@Test | |
public void 通信に成功するとSysout失敗するとStackTraceが表示される() { | |
final String url = "http://api.openweathermap.org/data/2.5/weather?q=Tokyo,jp"; | |
final Effect1<Exception> stackTrace = Exception::printStackTrace; | |
final Effect1<JsonNode> sysout = System.out::println; | |
get.f(url).right().bind(parse) | |
.either(Effect.f(stackTrace), Effect.f(sysout)); | |
} | |
// JsonデータをStringで取得 | |
F<String, Either<Exception, String>> get = urlString -> { | |
try { | |
final BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) new URL(urlString).getContent())); | |
String line; | |
final StringBuilder sb = new StringBuilder(); | |
while ((line = br.readLine()) != null) { | |
sb.append(line); | |
} | |
return Either.right(sb.toString()); | |
} catch (Exception e) { | |
return Either.left(e); | |
} | |
}; | |
// StringのJsonデータをJsonNodeに変換 | |
F<String, Either<Exception, JsonNode>> parse = jsonString -> { | |
try { | |
return Either.right(new ObjectMapper().readValue(jsonString, JsonNode.class)); | |
} catch (Exception e) { | |
return Either.left(e); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment