נבנה על ידי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.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-IntelliJ ולסמן פתרתי. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in IntelliJ and mark I solved it. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. למה "... WHERE author = '" + input + "'" מסוכן?Why is "... WHERE author = '" + input + "'" dangerous?

2. מה הסטטוס כשהמשאב לא קיים?What's the status when the resource doesn't exist?

3. מה היתרון של BookRepository כ-interface?What's the benefit of BookRepository as an interface?

תרגיליםExercises

תרגילExercise 1

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

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
[Book[title=Emma, author=Austen, year=1815], Book[title=Persuasion, author=Austen, year=1817]]
false
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: המתודות במימוש חייבות public (הן מממשות interface).The implementing methods must be public (they implement an interface).
לפתרוןSolution
תרגילExercise 2

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

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.

איך הפלט אמור להיראות?What should the output look like?
Query[sql=SELECT * FROM book WHERE author = ?, params=[Austen]]
Query[sql=SELECT * FROM book WHERE author = ?, params=[x' OR '1'='1]]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: זה בדיוק מה ש-PreparedStatement עושה: SQL קבוע, ערכים בנפרד.That's exactly what PreparedStatement does: fixed SQL, values separately.
לפתרוןSolution
תרגילExercise 3

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

תשובת 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 [].

איך הפלט אמור להיראות?What should the output look like?
200 {"title": "Dune"}
404 []
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: raw.split("\n\n", 2): עד השורה הריקה, ואחריה.raw.split("\n\n", 2): up to the empty line, and after it.
לפתרוןSolution
תרגילExercise 4

Optional מה-RepositoryOptional from the Repository

עם 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.

איך הפלט אמור להיראות?What should the output look like?
Dune (1965) | not found
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: .map(...).orElse("not found").map(...).orElse("not found")
לפתרוןSolution
תרגילExercise 5

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

פרויקט מלווהCompanion project

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.

איך הפלט אמור להיראות?What should the output look like?
saved Emma
rejected: duplicate
rejected: bad year
saved Persuasion
[Emma, Persuasion]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: הכללים (שנה, כפולים) ב-Service; השמירה ב-Repository.The rules (year, duplicates) go in the Service; storage in the Repository.
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

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

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]].

איך הפלט אמור להיראות?What should the output look like?
[Book[title=Dune, year=1965], Book[title=Emma, year=1815]]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: (String) r.get("title"), (Integer) r.get("year")(String) r.get("title"), (Integer) r.get("year")
לפתרוןSolution
אתגרChallenge 2

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

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().

איך הפלט אמור להיראות?What should the output look like?
[Dune, Emma]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: ב-commit העותק נהיה האמת.On commit the copy becomes the truth.
לפתרוןSolution

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