dtonhofer

dtonhofer

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());
            }
        }
    }

Marked As Solved

venkats

venkats

Author of Programming Kotlin, Rediscovering JavaScript (and 6 other titles)

Decided to keep the change minimum here and resolve the deprecation warning. Fixed. Thank you.

Also Liked

venkats

venkats

Author of Programming Kotlin, Rediscovering JavaScript (and 6 other titles)

Practically, given the context of this example code, there is little benefit to the reader to see more code than minimally necessary for this function.

Where Next?

Popular Pragmatic Bookshelf topics Top

GilWright
Working through the steps (checking that the Info,plist matches exactly), run the demo game and what appears is grey but does not fill th...
New
jesse050717
Title: Web Development with Clojure, Third Edition, pg 116 Hi - I just started chapter 5 and I am stuck on page 116 while trying to star...
New
AleksandrKudashkin
On the page xv there is an instruction to run bin/setup from the main folder. I downloaded the source code today (12/03/21) and can’t see...
New
gilesdotcodes
In case this helps anyone, I’ve had issues setting up the rails source code. Here were the solutions: In Gemfile, change gem 'rails' t...
New
brunogirin
When I run the coverage example to report on missing lines, I get: pytest --cov=cards --report=term-missing ch7 ERROR: usage: pytest [op...
New
dsmith42
Hey there, I’m enjoying this book and have learned a few things alredayd. However, in Chapter 4 I believe we are meant to see the “&gt;...
New
rainforest
Hi, I’ve got a question about the implementation of PubSub when using a Phoenix.Socket.Transport behaviour rather than channels. Before ...
New
tkhobbes
After some hassle, I was able to finally run bin/setup, now I have started the rails server but I get this error message right when I vis...
New
EdBorn
Title: Agile Web Development with Rails 7: (page 70) I am running windows 11 pro with rails 7.0.3 and ruby 3.1.2p20 (2022-04-12 revision...
New
bjnord
Hello @herbert ! Trying to get the very first “Hello, Bracket Terminal!" example to run (p. 53). I develop on an Amazon EC2 instance runn...
New

Other popular topics Top

Devtalk
Hello Devtalk World! Please let us know a little about who you are and where you’re from :nerd_face:
New
AstonJ
Just done a fresh install of macOS Big Sur and on installing Erlang I am getting: asdf install erlang 23.1.2 Configure failed. checking ...
New
AstonJ
Inspired by this post from @Carter, which languages, frameworks or other tech or tools do you think is killing it right now? :upside_down...
New
Margaret
Hello content creators! Happy new year. What tech topics do you think will be the focus of 2021? My vote for one topic is ethics in tech...
New
PragmaticBookshelf
Learn different ways of writing concurrent code in Elixir and increase your application's performance, without sacrificing scalability or...
New
rustkas
Intensively researching Erlang books and additional resources on it, I have found that the topic of using Regular Expressions is either c...
New
AstonJ
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: bre...
New
PragmaticBookshelf
Author Spotlight Jamis Buck @jamis This month, we have the pleasure of spotlighting author Jamis Buck, who has written Mazes for Prog...
New
CommunityNews
A Brief Review of the Minisforum V3 AMD Tablet. Update: I have created an awesome-minisforum-v3 GitHub repository to list information fo...
New
sir.laksmana_wenk
I’m able to do the “artistic” part of game-development; character designing/modeling, music, environment modeling, etc. However, I don’t...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: