נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
39
חלקPart 7: Java בעולם האמיתיJava in the real world כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

JDBC ו-HttpClientJDBC & HttpClient

מסד נתונים עם JDBC ו-SQL, PreparedStatement, וקריאות HTTP עם HttpClient.

A database with JDBC and SQL, PreparedStatement, and HTTP calls with HttpClient.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

Repository בזיכרוןAn in-memory Repository

תזכורת: מה ביקשוReminder: the task

כתבו interface BookRepository (save, findByAuthor, findByTitle שמחזירה Optional) ומימוש InMemoryBookRepository. שמרו שלושה ספרים, והדפיסו את הספרים של Austen ואז false עבור Hamlet.

Write interface BookRepository (save, findByAuthor, findByTitle returning an Optional) and an InMemoryBookRepository. Save three books, then print Austen's books and false for Hamlet.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        BookRepository repo = new InMemoryBookRepository();
        repo.save(new Book("Emma", "Austen", 1815));
        repo.save(new Book("Dune", "Herbert", 1965));
        repo.save(new Book("Persuasion", "Austen", 1817));
        System.out.println(repo.findByAuthor("Austen"));
        System.out.println(repo.findByTitle("Hamlet").isPresent());
    }
}

interface BookRepository {
    void save(Book b);

    List<Book> findByAuthor(String author);

    Optional<Book> findByTitle(String title);
}

record Book(String title, String author, int year) {
}

class InMemoryBookRepository implements BookRepository {
    private final List<Book> rows = new ArrayList<>();

    public void save(Book b) {
        rows.add(b);
    }

    public List<Book> findByAuthor(String author) {
        List<Book> out = new ArrayList<>();
        for (Book b : rows) {
            if (b.author().equals(author)) {
                out.add(b);
            }
        }
        return out;
    }

    public Optional<Book> findByTitle(String title) {
        for (Book b : rows) {
            if (b.title().equals(title)) {
                return Optional.of(b);
            }
        }
        return Optional.empty();
    }
}
פלטOutput
[Book[title=Emma, author=Austen, year=1815], Book[title=Persuasion, author=Austen, year=1817]]
false

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

צייד באגים: SQL injectionBug hunter: SQL injection

תזכורת: מה ביקשוReminder: the task

findQuery מחברת את הקלט לתוך ה-SQL, והקלט השני הופך את השאילתה ל"כל הספרים". החזירו במקום זה record Query(String sql, List<Object> params) עם ? במקום הערך. הפלט: Query[sql=SELECT * FROM book WHERE author = ?, params=[Austen]] וכן לשני.

findQuery glues the input into the SQL, and the second input turns the query into "every book". Return instead record Query(String sql, List<Object> params) with ? in place of the value. The output: Query[sql=SELECT * FROM book WHERE author = ?, params=[Austen]] and the same for the second.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.List;

public class Main {
    record Query(String sql, List<Object> params) {
    }

    static Query findQuery(String author) {
        return new Query("SELECT * FROM book WHERE author = ?", List.of(author));
    }

    public static void main(String[] args) {
        System.out.println(findQuery("Austen"));
        System.out.println(findQuery("x' OR '1'='1"));
    }
}
פלטOutput
Query[sql=SELECT * FROM book WHERE author = ?, params=[Austen]]
Query[sql=SELECT * FROM book WHERE author = ?, params=[x' OR '1'='1]]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

לקרוא תשובת HTTPReading an HTTP response

תזכורת: מה ביקשוReminder: the task

תשובת HTTP היא טקסט: שורת סטטוס, כותרות, שורה ריקה וגוף. parse(raw) מחזירה Response(status, body). הדפיסו 200 {"title": "Dune"} ואז 404 [].

An HTTP response is text: a status line, headers, an empty line and a body. parse(raw) returns Response(status, body). Print 200 {"title": "Dune"} then 404 [].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    record Response(int status, String body) {
    }

    static Response parse(String raw) {
        String[] parts = raw.split("\n\n", 2);
        String statusLine = parts[0].split("\n")[0];
        int status = Integer.parseInt(statusLine.split(" ")[1]);
        return new Response(status, parts.length > 1 ? parts[1] : "");
    }

    public static void main(String[] args) {
        Response ok = parse("HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\"title\": \"Dune\"}");
        Response missing = parse("HTTP/1.1 404 Not Found\n\n");
        System.out.println(ok.status() + " " + ok.body());
        System.out.println(missing.status() + " [" + missing.body() + "]");
    }
}
פלטOutput
200 {"title": "Dune"}
404 []

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

Optional מה-RepositoryOptional from the Repository

תזכורת: מה ביקשוReminder: the task

עם findByTitle (מחזירה Optional<Book>) הדפיסו Dune (1965) | not found, בלי null ובלי if.

With findByTitle (returning an Optional<Book>) print Dune (1965) | not found, with no null and no if.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        BookRepository repo = new InMemoryBookRepository();
        repo.save(new Book("Dune", "Herbert", 1965));
        String a = repo.findByTitle("Dune").map(b -> b.title() + " (" + b.year() + ")").orElse("not found");
        String b = repo.findByTitle("Hamlet").map(x -> x.title() + " (" + x.year() + ")").orElse("not found");
        System.out.println(a + " | " + b);
    }
}

interface BookRepository {
    void save(Book b);

    List<Book> findByAuthor(String author);

    Optional<Book> findByTitle(String title);
}

record Book(String title, String author, int year) {
}

class InMemoryBookRepository implements BookRepository {
    private final List<Book> rows = new ArrayList<>();

    public void save(Book b) {
        rows.add(b);
    }

    public List<Book> findByAuthor(String author) {
        List<Book> out = new ArrayList<>();
        for (Book b : rows) {
            if (b.author().equals(author)) {
                out.add(b);
            }
        }
        return out;
    }

    public Optional<Book> findByTitle(String title) {
        for (Book b : rows) {
            if (b.title().equals(title)) {
                return Optional.of(b);
            }
        }
        return Optional.empty();
    }
}
פלטOutput
Dune (1965) | not found

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 39: המדף מעל RepositoryShelf, step 39: the shelf over a Repository

תזכורת: מה ביקשוReminder: the task

ShelfService מקבל BookRepository בבנאי, דוחה שנה שלילית וכפולים, ושומר. הדפיסו saved Emma, rejected: duplicate, rejected: bad year, saved Persuasion, [Emma, Persuasion]. ב-JdbcBookRepository אמיתי הקוד של ShelfService לא ישתנה.

ShelfService takes a BookRepository in its constructor, rejects a negative year and duplicates, and saves. Print saved Emma, rejected: duplicate, rejected: bad year, saved Persuasion, [Emma, Persuasion]. With a real JdbcBookRepository, ShelfService's code won't change.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        ShelfService shelf = new ShelfService(new InMemoryBookRepository());
        System.out.println(shelf.add("Emma", "Austen", 1815));
        System.out.println(shelf.add("Emma", "Austen", 1815));
        System.out.println(shelf.add("Old", "Nobody", -5));
        System.out.println(shelf.add("Persuasion", "Austen", 1817));
        System.out.println(shelf.byAuthor("Austen"));
    }
}

class ShelfService {
    private final BookRepository repo;

    ShelfService(BookRepository repo) {
        this.repo = repo;
    }

    String add(String title, String author, int year) {
        if (year < 0) {
            return "rejected: bad year";
        }
        if (repo.findByTitle(title).isPresent()) {
            return "rejected: duplicate";
        }
        repo.save(new Book(title, author, year));
        return "saved " + title;
    }

    List<String> byAuthor(String author) {
        List<String> titles = new ArrayList<>();
        for (Book b : repo.findByAuthor(author)) {
            titles.add(b.title());
        }
        return titles;
    }
}

interface BookRepository {
    void save(Book b);

    List<Book> findByAuthor(String author);

    Optional<Book> findByTitle(String title);
}

record Book(String title, String author, int year) {
}

class InMemoryBookRepository implements BookRepository {
    private final List<Book> rows = new ArrayList<>();

    public void save(Book b) {
        rows.add(b);
    }

    public List<Book> findByAuthor(String author) {
        List<Book> out = new ArrayList<>();
        for (Book b : rows) {
            if (b.author().equals(author)) {
                out.add(b);
            }
        }
        return out;
    }

    public Optional<Book> findByTitle(String title) {
        for (Book b : rows) {
            if (b.title().equals(title)) {
                return Optional.of(b);
            }
        }
        return Optional.empty();
    }
}
פלטOutput
saved Emma
rejected: duplicate
rejected: bad year
saved Persuasion
[Emma, Persuasion]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

משורות לעצמיםFrom rows to objects

תזכורת: מה ביקשוReminder: the task

ResultSet הוא בעצם רשימת שורות. כאן כל שורה היא Map<String, Object>. map(rows) הופכת אותן ל-Bookים: [Book[title=Dune, year=1965], Book[title=Emma, year=1815]].

A ResultSet is really a list of rows. Here each row is a Map<String, Object>. map(rows) turns them into Books: [Book[title=Dune, year=1965], Book[title=Emma, year=1815]].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Main {
    record Book(String title, int year) {
    }

    static List<Book> map(List<Map<String, Object>> rows) {
        List<Book> out = new ArrayList<>();
        for (Map<String, Object> r : rows) {
            out.add(new Book((String) r.get("title"), (Integer) r.get("year")));
        }
        return out;
    }

    public static void main(String[] args) {
        List<Map<String, Object>> rows = List.of(Map.of("title", "Dune", "year", 1965), Map.of("title", "Emma", "year", 1815));
        System.out.println(map(rows));
    }
}
פלטOutput
[Book[title=Dune, year=1965], Book[title=Emma, year=1815]]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

טרנזקציה: הכול או כלוםA transaction: all or nothing

תזכורת: מה ביקשוReminder: the task

TxRepo מדמה טרנזקציה: begin מעתיק, save כותב לעותק, commit מאשר ו-rollback זורק. שתי שמירות עם commit ואחת עם rollback: [Dune, Emma]. ב-JDBC: db.setAutoCommit(false), db.commit(), db.rollback().

TxRepo imitates a transaction: begin copies, save writes to the copy, commit confirms and rollback throws away. Two saves with commit and one with rollback: [Dune, Emma]. In JDBC: db.setAutoCommit(false), db.commit(), db.rollback().

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        TxRepo repo = new TxRepo();
        repo.begin();
        repo.save("Dune");
        repo.save("Emma");
        repo.commit();
        repo.begin();
        repo.save("Broken");
        repo.rollback();
        System.out.println(repo.all());
    }
}

class TxRepo {
    private List<String> committed = new ArrayList<>();
    private List<String> working = null;

    void begin() {
        working = new ArrayList<>(committed);
    }

    void save(String title) {
        working.add(title);
    }

    void commit() {
        committed = working;
        working = null;
    }

    void rollback() {
        working = null;
    }

    List<String> all() {
        return List.copyOf(committed);
    }
}
פלטOutput
[Dune, Emma]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich