Functional Programming in Java, Second Edition: p.91: Rewrite FinanceData HTTP request method

On page 91, we use a short method to request a stock ticker, class FinanceData
However, this method is based on java.net.URL
which has always been broken in several ways, one which being that it doesn’t encode the URL itself. That class is also deprecated in Java 20. The replacement is java.net.URI
(since Java 7).
The construction of the query string, while appropriate as an exercise, can also be done better while demonstrating stream use.
Anyway, let’s go. Here is a definitely longer but IMHO nicer replacement:
public class FinanceData {
public static BigDecimal getPrice(final String ticker) {
HttpResponse<String> response;
try {
final String scheme = "https";
final String authority = "eodhistoricaldata.com";
final String path = String.format("/api/eod/%s.US",ticker);
final String query =
List.of("fmt=json", "filter=last_close", "api_token=OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX")
.stream()
.collect(Collectors.joining("&"));
final String fragment = null;
final URI uri = new URI(scheme,authority,path,query,fragment);
System.out.println("Connecting to URI: " + uri);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(uri).build();
response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
} catch(Exception ex) {
throw new RuntimeException(ex);
}
System.out.println("Received status code: " + response.statusCode());
if (response.statusCode() == 200) {
System.out.println("Received body: " + response.body());
// parsing BigDecimal will throw on bad syntax
return new BigDecimal(response.body());
}
else {
throw new IllegalStateException("Status code was: " + response.statusCode());
}
}
}
Popular Pragprog topics

In Chapter 3, the source for index introduces Config on page 31, followed by more code including tests; Config isn’t introduced until pag...
New

As per the title, thanks.
New

page 37
ANTLRInputStream input = new ANTLRInputStream(is);
as of ANTLR 4 .8 should be:
CharStream stream = CharStreams.fromStream(i...
New

Python Testing With Pytest - Chapter 2, warnings for “unregistered custom marks”
While running the smoke tests in Chapter 2, I get these...
New

Hi everyone!
There is an error on the page 71 in the book “Programming machine learning from coding to depp learning” P. Perrotta. You c...
New

Hello! On page xix of the preface, it says there is a community forum "… for help if your’re stuck on one of the exercises in this b...
New

It seems the second code snippet is missing the code to set the current_user:
current_user: Accounts.get_user_by_session_token(session[&...
New

Book: Programming Phoenix LiveView, page 142 (157/378), file lib/pento_web/live/product_live/form_component.ex, in the function below:
d...
New

Docker-Machine became part of the Docker Toolbox, which was deprecated in 2020, long after Docker Desktop supported Docker Engine nativel...
New

Getting an error when installing the dependencies at the start of this chapter:
could not compile dependency :exla, "mix compile&qu...
New
Other popular topics

New
New

My first contact with Erlang was about 2 years ago when I used RabbitMQ, which is written in Erlang, for my job. This made me curious and...
New

Rust is an exciting new programming language combining the power of C with memory safety, fearless concurrency, and productivity boosters...
New

Here’s the story how one of the world’s first production deployments of LiveView came to be - and how trying to improve it almost caused ...
New

A few weeks ago I started using Warp a terminal written in rust. Though in it’s current state of development there are a few caveats (tab...
New

If you get Can't find emacs in your PATH when trying to install Doom Emacs on your Mac you… just… need to install Emacs first! :lol: ...
New

Author Spotlight: VM Brasseur (@vmbrasseur)
We have a treat for you today! We turn the spotlight onto Open Source as we sit down with...
New

zig/http.zig at 7cf2cbb33ef34c1d211135f56d30fe23b6cacd42 · ziglang/zig.
General-purpose programming language and toolchain for maintaini...
New

Author Spotlight: Bruce Tate (@redrapids)
Programming languages always emerge out of need, and if that’s not always true, they’re def...
New
Latest in Pragprog
Latest (all)
Categories:
My Saved Portals
-
None saved yet
Popular Portals
- /elixir
- /opensuse
- /rust
- /kotlin
- /ruby
- /erlang
- /python
- /clojure
- /react
- /quarkus
- /go
- /vapor
- /v
- /react-native
- /wasm
- /security
- /django
- /nodejs
- /centos
- /haskell
- /rails
- /fable
- /gleam
- /swift
- /js
- /deno
- /assemblyscript
- /tailwind
- /laravel
- /symfony
- /phoenix
- /crystal
- /typescript
- /debian
- /adonisjs
- /julia
- /arch-linux
- /svelte
- /spring
- /c-plus-plus
- /flutter
- /preact
- /actix
- /java
- /angular
- /ocaml
- /zig
- /kubuntu
- /scala
- /zotonic
- /vim
- /rocky
- /lisp
- /html
- /keyboards
- /vuejs
- /nim
- /emacs
- /nerves
- /elm