𝔖 Scriptorium
✦   LIBER   ✦

📁

Pro Kotlin Web Apps from Scratch: Building Production-Ready Web Apps Without a Framework

✍ Scribed by August Lilleaas


Publisher
Apress
Tongue
English
Leaves
330
Category
Library

⬇  Acquire This Volume

No coin nor oath required. For personal study only.

✦ Synopsis


Build production-grade web apps from scratch – without using frameworks – with Kotlin on the Java platform. You’ll learn how to use and compose libraries, how to choose between different libraries, and the benefits of explicit and straight-forward code, vs. the implicit magic, conventions, and inversion of control you often see in frameworks.
The book teaches the Kotlin language by building production-ready Kotlin code. You’ll gain a deep understanding of the idiomatic use of the Kotlin language along with knowledge of how to apply Kotlin in production-grade web apps. The book also bridges the gap between building from scratch and using existing frameworks. For example, you’ll learn how to integrate Spring Security-based authentication in web apps written from scratch, so you can leverage existing tooling in your organization without having to take on the entire Spring framework. 

The first section of the book sets up the base structure of your web app, such as routing, configuration files, and database migrations. The remaining chapters are broken into individual aspects of building production-ready web apps. Appendices at the end of the book explain how to use different libraries than the ones chosen in the main chapters, so you'll learn how to decouple your code from specific libraries, and choose between many different libraries to get the job done in your own web apps.

What You Will Learn

  • Compose libraries and manage boilerplate code using idiomatic and powerful Kotlin
  • Manage and query SQL databases without ORMs and mapping layers
  • Write resilient and change-proof tests in support of test-driven development practices
  • Create traditional, HTML-based web apps, APIs for JavaScript-based single-page web apps and native mobile apps
  • Manage parallelism and external service calls using Kotlin co-routines
  • Deploy to production using embedded servers, WAR files, and serverless approaches
  • Bridge the gap between custom-built apps and enterprise, using Spring Context and Spring Security


Who This Book Is For
The expert developer who is ready to take full control of the tech stack, and use the Kotlin language, type system, and standard library, to ship production-ready web apps. Readers should have prior programming experience. Experience with Java or another JVM language is helpful. 

✦ Table of Contents


Table of Contents
About the Author
About the Technical Reviewer
Acknowledgments
Introduction
Part I: Up and Running with a Web App
Chapter 1: Setting Up a Development Environment
Get Started with IntelliJ IDEA Community Edition
Download and Run IntelliJ IDEA
Create a New Kotlin Project with IntelliJ IDEA
Kotlin Hello, World!
Kotlin Naming Conventions
Write Some Code
Run Your Code with IntelliJ IDEA
Run Your Code with Gradle
IntelliJ IDEA Tips and Tricks
Look Out for the Progress Bar
Remember to Refresh the Gradle Project in IntelliJ IDEA
Embrace Auto-completion in IntelliJ IDEA
Chapter 2: Setting Up the Web App Skeleton
Web Server Hello, World!
Choosing Ktor
Add the Ktor Library
Start a Web Server
Extracting to a Separate Function
Using Lambdas
Named Arguments Instead of Magic Numbers and Booleans
Run Your Web App
Logging
Loggers on the Java Platform
Configure Logging in Your Web App
Write to the Log from Your Own Code
A Note on “Magic” XML Config Files
Useful Error Pages
Chapter 3: Configuration Files
Create a Configuration File
The Configuration File Anatomy
Reading Values from Your Configuration File
Make the Configuration Fail Early and Type-Safe
Store Configuration in a Data Class
Load Config into the Data Class
Kotlin Null Safety
Kotlin Platform Types
Use the Data Class in Your Web App
Use let Blocks to Avoid Intermediate Variables
Provide Different Default Values for Different Environments
Environment-Specific Config Files
Define the Web App Environment
Override Defaults with Environment-Specific Config
Secret Config Values
Don’t Store Secrets in Version Control
Logging Config on Web App Startup
Format the Output
Masking Secrets
Writing to the Log
Chapter 4: Decoupling Web Handlers from Specific Libraries
Your Own HTTP Response Abstraction
Representing HTTP Responses
Multiple Response Types
Convenience Functions for Headers
Case-Insensitive Headers
The fold Function
Destructuring Assignment
Connecting to Ktor
Ktor Route Mapping
Extension Functions
Functions Returning Functions
Map Headers
Map TextWebResponse and Status Code
Map JsonWebResponse
Using the New Mapping
A Note on Overengineering
Part II: Libraries and Solutions
Chapter 5: Connecting to and Migrating SQL Databases
Connecting to a SQL Database
The Connection Pool
Installing the Database Driver
Setting Up H2
Updating WebappConfig
Set Up the Connection Pool
Creating a Connection
The Initial Schema
Installing Flyway
Running Flyway During Startup
Creating the Initial Schema
Managing Schema Changes
Don’t Edit Migrations After Run
Adding More Schema
Adding Non-nullable Columns
Backward-Compatible Migrations
Insert Seed Data
Repeatable Migrations
Updating Repeatable Migrations
Handling Failed Migrations
Failed Migrations Locally
Failed Migrations in Production
Rerunning Failed Migration
Manually Performing Migration
Chapter 6: Querying a SQL Database
Setting Up Querying
Use SQL Directly
Installing Kotliquery
Mapping Query Results
Execute SQL Queries
Creating a Session
Querying for Single Rows
Querying for Multiple Rows
Inserting Rows
Updating and Deleting
Positional vs. Named Parameters
Additional Operations
Querying from Web Handlers
Creating a Helper Function
A Note on Architecture
Avoid Long-Running Connections
Maps vs. Data Classes
Passing Around Maps
Passing Individual Properties
Mapping to a Data Class
Database Transactions
Creating Transactions
Transactions in Web Handlers
Type-Safe Transactional Business Logic
Nested Transactions
Chapter 7: Automated Tests with jUnit 5
Setting Up Your Environment
Adding jUnit 5 and kotlin.test
Writing a Failing Test
Running a Failing Test
Making the Test Pass
Writing Web App Tests
Setting Up the Basics
Writing a Failing Test
Making the Test Pass
Avoiding Leaky Tests
Leaky Tests
Avoiding Leaks with Transactions
Avoiding Leaks with Relative Asserts
Test-Driven Development
Design and Verification
Writing a Failing Test
Making the Test Pass
Notes on Methodology
What About Front-End Tests?
Real Database Writes vs. Mocks
Unit vs. Integration Tests
Chapter 8: Parallelizing Service Calls with Coroutines
Preparing Your Web App
Implementing a Fake Service
Adding a Second Server
Understanding Coroutines
The delay Coroutine
The Problem with Threads
Suspending Instead of Locking
Coroutine Contexts
Coroutines in Ktor
Parallelizing Service Calls
Adding Dependencies
Performing Parallelized Calls
Handling Race Conditions
Adding to Ktor
Mixing Coroutines and Blocking Calls
Wrapping Blocking Calls
Coroutine Internals
Kotlin vs. KotlinX
Comparing with Arrow
Using Low-Level Continuations
Java Platform Implementation Details
Chapter 9: Building Traditional Web Apps with HTML and CSS
Patterns and Organization
Generating HTML
Using the kotlinx.html DSL
Using the Ktor HTML DSL
The Power of the DSL
Operator Overloading
Adding Custom Tags
CSS and Assets
Serving Static Files
Instant Reloading
Reusable Layouts
Adding a Layout
Using the Layout
Adding WebResponse for HTML
Implementing HtmlWebResponse
Extension Function Precedence
Responding with HtmlWebResponse
A Note on Abstractions
User Security
Password Hashing
Using Bcrypt for Hashing
Updating Your Migrations
Adding a Login Form
Wiring Up Your Web App
Different Types of Sessions
Adding a New Ktor Extension Function
Configuring Session Cookies
Logging In
Protecting Routes with Authentication
Logging Out
Chapter 10: Building API-Based Back Ends
Handling API Calls
Parsing Input
Validating and Extracting Input
Avoid Automatic Serialization
Internal vs. External APIs
Single-Page Apps
Hosting Alongside API
Hosting Separately with CORS
Authenticating Users
Native Apps
Using Cookies for Authentication
Using JWTs for Authentication
Performing Authentication
Chapter 11: Deploying to Traditional Server Based Environments
Packaging as Self-Contained JAR Files
What’s a JAR File
Self-Contained JAR Files
Packaging with Gradle
Building the JAR File
Executing the JAR File
Packaging for Production
Building Docker Images
Running Docker Images Locally
Deploying to Production
Chapter 12: Building and Deploying to Serverless Environments
Detaching Your Code
Separating Handlers from Ktor
Basic Structure
Detached Web Handlers
Run Web Handlers on AWS Lambda
Making AWS Lambda Web Handlers
Deploying to AWS Lambda
Calling Your Existing Handlers
Improving Performance
Performance and Cold Starts
Initialization Time vs. Execution Time
Lazy Loading
Initializing Correctly
Migrations and H2
Java Runtime Flags
GraalVM, Kotlin/JS, and Kotlin Native
Chapter 13: Setup, Teardown, and Dependency Injection with Spring Context
Why Spring and Dependency Injection?
Setting Up Spring Context
Adding Your Data Source
lateinit in Kotlin
Starting Your Web App
Extended Usage
Chapter 14: Enterprise Authentication Using Spring Security
Preparing Your Web App
Setting Up Embedded Jetty
Initializing the Servlet
Adding Ktor to Your Servlet
Using Spring Security
Setting Up the Servlet Filter
Configuring Spring Security
Authenticating Users
Filtering Requests
Accessing the Logged-In User
Part III: Tools of the Trade
Chapter 15: Choosing the Right Library
What’s a Library?
Popularity Is Largely Irrelevant
Documentation and Stability Are Important
Avoid Following the “X Way”
Don’t Shy Away from Platform Libraries
Boundaries and Layers
Chapter 16: An Assortment of Kotlin Tricks
Delegation (by lazy)
Inline Functions
Reified Generics
Contracts
And So Much More
Appendix A: Using Jooby Instead of Ktor
Starting a Server
Mapping WebResponse
Serving Assets
Responding to Requests
Authenticating with Forms
Authenticating with JWTs
Appendix B: Using Hoplite Instead of Typesafe Config
Loading Config Files
Handling JVM Target Version Errors
Handling Unknown Environment Variables
Masking Secrets
Appendix C: Using Spek Instead of jUnit 5
Writing Spek Tests
Structuring Spek Tests
Skipping Tests
Running Individual Tests
Index


📜 SIMILAR VOLUMES


Pro Kotlin Web Apps from Scratch: Buildi
✍ August Lilleaas 📂 Library 🏛 Apress 🌐 English

<span>Build production-grade web apps from scratch – without using frameworks – with Kotlin on the Java platform. You’ll learn how to use and compose libraries, how to choose between different libraries, and the benefits of explicit and straight-forward code, vs. the implicit magic, conventions, and

Build Your First Web App: Learn to Build
✍ Belton, Todd;Levinson, Deborah A 📂 Library 📅 2017 🏛 Sterling 🌐 English

User experience basics -- Application features and flow -- Visual design basics -- Preparing to code: installing and configuring -- Bootstrap -- Getting started with Angular -- Coding the app -- Putting it all together -- Deployment.

Mastering Flask Web and API Development:
✍ Sherwin John C. Tragura 📂 Library 📅 2024 🏛 Packt Publishing 🌐 English

<p><span>Discover how to construct API and web components, build enterprise-grade applications, design and implement unit and behavioral testing, and plan deployment strategies for scalable Flask 3 applications</span></p><h4><span>Key Features</span></h4><ul><li><span><span>Implement web and API app

iOS Apps with REST APIs: Building Web-Dr
✍ Christina Moulton 📂 Library 📅 2015 🌐 English

This book was written using Swift 2.0, Alamofire 3.1, Xcode 7, and iOS 9.<br><br>All code samples included.<br><br>This book is for:<br><br>- Software developers getting started with iOS but experienced in other languages<br><br>- Front-end devs looking to implement native UIs for iOS apps (no CSS,