diff --git a/!!! TemplateName(YYYY-MM-DD) !!!.md.bak b/!!! TemplateName(YYYY-MM-DD) !!!.md.bak new file mode 100644 index 0000000..ca77e76 --- /dev/null +++ b/!!! TemplateName(YYYY-MM-DD) !!!.md.bak @@ -0,0 +1,46 @@ +--- +title: "Template Name" + +description: "Template Description" +summary: 'Template Summary with "quotation" mark + +And it can be multi-liner. + +All of the content shown in summary will be used as blog digest shown in index' + +category: "misc" +series: "Series-Name" # Caution!!! Series Name canNOT be wrapped up with Square brackets !!! +tags: ["Tag Name 1", "Tag Name 2"] + + +date: 2023-07-19T00:00:00+08:00 +lastmod: 2023-08-23T00:00:00+08:00 + +plantuml: false +katex: false +mathjax: false +mermaid: false +utterances: true + +draft: true +--- + +This is Template Summary. + +# 1. LEVEL-1 TITLE + +## 1.1 Level 2 Title + +### 1.1.1 Level 3 Title + +### 1.1.2 Level 3 Title + +## 1.2 Level 2 Title + +# 2. LEVEL-1 TITLE + +## 2.1 Level 2 Title + +### 2.1.1 Level 3 Title + +# 3. CONCLUSION diff --git a/2022/05/binary-tree-nonrecursive-inorder/index.html b/2022/05/binary-tree-nonrecursive-inorder/index.html new file mode 100644 index 0000000..26440f5 --- /dev/null +++ b/2022/05/binary-tree-nonrecursive-inorder/index.html @@ -0,0 +1,482 @@ + + + + +Binary Tree NonRecursive InOrder | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

Binary Tree NonRecursive InOrder

+ + +

Hi there, let's talk about how to nonrecursively do a In-Order traversal for a Binary Tree.

+

A Binary Tree consists of 3 parts: the node itself, pointer to the left child, pointer to the right child.

+

An In-Order Traversal is to access the leftmost child firstly, then the node itself, and finally the right child.

+

1. Question

+

94. Binary Tree Inorder Traversal:

+

Given the root of a binary tree, return the inorder traversal of its nodes' values.

+

1.1 Examples

+
    +
  • Example 1:
  • +
+
1Input: root = [1,null,2,3]
+2Output: [1,3,2]
+
    +
  • Example 2:
  • +
+
1Input: root = []
+2Output: []
+
    +
  • Example 3:
  • +
+
1Input: root = [1]
+2Output: [1]
+

1.2 Constraints

+
    +
  • The number of nodes in the tree is in the range $ \left[ 0, 100 \right ] $.
  • +
  • $ -100 \leq \text{node.val} \leq 100 $
  • +
+

2. Solution

+

To solve this problem, we will use stack.

+

This approach is a nonrecursive method.

+

2.1 Code

+
 1class Solution {
+ 2public:
+ 3    vector<int> inorderTraversal(TreeNode* root) {
+ 4        if (root == nullptr) return {};  // corner case: empty tree
+ 5        
+ 6        TreeNode * p = root;
+ 7        stack<TreeNode *> stk;
+ 8
+ 9        vector<int>  ans;
+10        while (p != nullptr || stk.empty() == false) {
+11            while (p != nullptr) {  // To Left Child, until end
+12                stk.push(p);
+13                p = p->left;
+14            }
+15            p = stk.top();  stk.pop();
+16            ans.push_back(p->val);  // Node->val
+17            p = p->right;           // Right Child
+18        }
+19
+20        return ans;
+21    }
+22};
+

2.2 Complexity Analysis

+

Assume the number of nodes in the tree is $ n $, and thus:

+
    +
  • +

    Time complexity: $ T(n) = O(n) $

    +
  • +
  • +

    Space complexity: $ S(n) = O(n) $

    +
  • +
+
+ + +
+
+
* This blog was last updated on 2022-05-17 21:42
+
+ + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/index.html b/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/index.html new file mode 100644 index 0000000..826a5d2 --- /dev/null +++ b/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/index.html @@ -0,0 +1,562 @@ + + + + +DDIA Ch01: Reliable, Scalable, and Maintainable Applications | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

DDIA Ch01: Reliable, Scalable, and Maintainable Applications

+ + +

Hi!

+

Let's read the Chapter 01: Reliable, Scalable, and Maintainable Applications of Designing Data-Intensive Applications.

+

It introduces the terminology and approach that we are going to use throughout the book, and it also explores some fundamental ways of thinking about data-intensive applications: general properties (nonfunctional requirements) such as reliability, scalability, and maintainability.

+

First of all, there are 2 types of applications:

+
    +
  • compute-intensive applications: raw CPU power is a limiting factor
  • +
  • data-intensive applications: the bigger problems are usually the amount of data, the complexity of data, and the speed at which it is changing.
  • +
+

And many applications today are data-intensive, which are typically built from standard building blocks (commonly needed functionalities):

+
    +
  • Databases
  • +
  • Caches
  • +
  • Search Indexes
  • +
  • Streaming Processing
  • +
  • Batch Processing
  • +
+

In reality, however, it can be hard to combine these tools when building an application.

+

1.1 Thinking About Data Systems

+

In this section, we talk about the background of the Data Systems.

+

Data Systems all can store data for some time, but with different access patterns, which means different performance characteristics, and thus very different implementations.

+

In recent years, with new tools for data processing and storage emerged, the boundaries between traditional categories are becoming blurred. And with different tools stitched together by application code, the work is broken down into tasks that can be performed efficiently on a single tool.

+

However, a lot of tricky questions arise when designing a data system or service. And in this book, we mainly focus on 3 concerns that are important in most software systems: Reliability, Scalabilility, and Maintainability.

+

1.2 Reliability

+

In this section, we deals with the kinds of faults that can be cured, such as hardware faults, software errors, and human errors.

+

First of all, the Reliability means that the system should continue to work correctly, even in the face of adversity.

+

However, if things did go wrong, it could only make sense to talk about tolerating certain types of faults, preventing faults from causing failures.

+

In practice, we generally prefer tolerating faults over preventing faults, and by deliberately inducing faults, we ensure that the fault-tolerant machinery is continually exercised and tested.

+

1.2.1 Hardware Faults

+

Hardware faults are faults that happen randomly, reported as having a Mean Time To Failure (MTTF).

+

Hardware Faults have weak correlation, and thus are independent from each other.

+

Solution for tolerating faults (rather than preventing faults):

+
    +
  • add hardware redundancy
  • +
  • use software fault-tolerance techniques
  • +
+

1.2.2 Software Errors

+

Software Errors are systematic errors within the system.

+

Software errors have strong correlation, which means they are correlated across nodes.

+

Solutions:

+
    +
  • carefully thinking about assumptions and interactions in the system.
  • +
  • thorough testing
  • +
  • process isolation
  • +
  • allowing process(es) to crash and restart
  • +
  • measuring, monitoring, and analyzing system behavior in production
  • +
+

1.2.3 Human Errors

+

Human errors are caused by human operations, and thus human are known to be unreliable.

+

Approaches:

+
    +
  • minimize opportunities for error when designing systems
  • +
  • use sandbox environments to decouple places where people make mistakes from places where mistakes causing outage
  • +
  • test thoroughly, from unit tests to whole-system integration tests and manual tests
  • +
  • quick and easy recovery from human errors
  • +
  • detailed and clear monitoring, e.g., telemetry
  • +
  • good management practices and training
  • +
+

1.3 Scalabilility

+

In this section, we focus on scalabilility - the ability that a system have to cope with the the increased load.

+

1.3.1 Describing 'Load'

+

Load can be described with a few numbers, called load parameters.

+

The best choice of parameters depends on the architecture of the system.

+

1.3.2 Describing 'Performance'

+

We use performance numbers to investigate what happens when load increases.

+

And we use percentile, one of the performance numbers, to denote response time, which is a distribution of values that can be measured (e.g., p999 meaning 99.9% of requests are handled faster than the particular threshold).

+

However, reducing response times at very high percentiles (known as tail latencies) may be too expensive, and may be difficult due to random events outside your control.

+

Queueing delays often account for a large part of the response time at high percentiles, for the following reasons:

+
    +
  • head-of-line blocking: a small number of slow requests in parallel hold up the processing of subsequent requests.
  • +
  • tail latency amplification: just one slow backend request can slow down the entire end-user requests.
  • +
+

1.3.3 Coping with Load

+

In this part, we talk about how to maintain good performance, even when load parameters increase.

+
    +
  • Rethink architecture on every order of magnitude of load increases.
  • +
  • Use a mixture of 2 scaling approaches +
      +
    • scaling up, or vertical scaling: moving to a more powerful machine
    • +
    • scaling down, or horizontal scaling: distributing the load across multiple machines, also known as shared-nothing architecture
    • +
    +
  • +
  • When choosing load parameters, figure out which operations will be common and which will be rare.
  • +
  • Use elastic systems to add computing resources automatically if load is highly unpredictable; but manually scaled systems are simpler and may have fewer operational surprises.
  • +
+

1.4 Maintainability

+

The majority of cost of software is in its ongoing maintenance, so software should be designed to minimize pain during maintenance, and thus to avoid creating legacy softwares.

+

And in this section, we pay attention to 3 designing principles for software systems: operability, simplicity, and evolvability.

+

1.4.1 Operability

+

Operability can make it easy for operations teams to keep the system running smoothly.

+

Data system should provide good operability, which means making routine tasks easy, allowing the operations team to focus their efforts on high-value activities.

+

1.4.2 Simplicity

+

Simplicity can make it easy for new engineers to understand the system.

+

We use abstraction to remove accidental complexity, which is not inherent in the problem that software solves (as seen by users) but arises only from the implementation.

+

And our goal is to use good abstraction to extract parts of the large systems into well-defined, reusable components.

+

1.4.3 Evolvability

+

Evolvability can make it easy for engineers to make changes to the system in the future, adapting it for unanticipated use cases as requirements change.

+

In terms of organizational processes, we use a framework from Agile working patterns to adapt to change. And the Agile community has also developed technical tools and patterns that are helpful when developing softwares in frequently changing environments, such as test-driven development (TDD) and refactoring.

+

And in this book, we will use evolvability to refer to agility on a data system level.

+
+ + +
+
+
* This blog was last updated on 2022-05-19 22:06
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2022/05/hello-world/index.html b/2022/05/hello-world/index.html new file mode 100644 index 0000000..22fed27 --- /dev/null +++ b/2022/05/hello-world/index.html @@ -0,0 +1,554 @@ + + + + +Hello World | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

Hello World

+ + +

Hello World!

+

This is my first blog post. Today, let's talk about writing a Markdown blog with Hugo, and eventually deploying it on GitHub Pages.

+

Hugo is a static HTML and CSS website generator, which allows us to concentrate on the contents rather than the layout tricks.

+

Environment:

+
    +
  • Windows 10 (64-bit)
  • +
  • Ubuntu 20.04 LTS, Windows Subsystem Linux 2
  • +
+

PREPARATIONS

+

In this section, we will prepare the tools.

+

NOTE: Please check out the official websites for detailed guidance. I may not cover full details.

+

Toolchain

+

In this section, we will use two powerful tools: git and golang

+
1$ sudo apt-get install git golang
+2
+3$ git config --global user.name "Your GitHub Username"
+4$ git config --global user.email "Your GitHub Email"
+

Install Hugo Compiler

+

Install from GitHub Release package, choose the latest package with the name 'extended', e.g., "hugo_extended_0.98.0_Linux-64bit.deb"

+

To install it, type:

+
1$ sudo dpkg -i ./hugo_extended_0.98.0_Linux-64bit.deb
+

NOTE: DO NOT use apt to install hugo, because its version of hugo installation package has already been outdated and can thus cause runtime errors.

+

Generate RSA keys

+
1$ ssh-keygen -t rsa -C "Your GitHub Email"
+

And then add the public key in ~/.ssh/id_rsa.pub to the GitHub Dashboard, and test connection:

+
1$ ssh -T git@github.com
+

CREATE BLOG

+

In this section, we will initialize the blog.

+

Generate an empty site

+
1$ hugo new site "NewSite"
+2$ cd NewSite
+

Initialize '.git'

+

This will prepare the submodule environment for Hugo themes.

+
1$ git init
+

Hugo Theme Pickup

+

In this section, we will pick up a beautiful theme for the new site.

+

Unlike Hexo, an alternative blog generating tool, the Hugo does not consist of a default theme, so let's pick theme(s) for Hugo.

+

And I prefer the hugo-Clarity, so I type these commands:

+
1# 1. Getting started with Clarity theme
+2$ git submodule add https://github.com/chipzoller/hugo-clarity themes/hugo-clarity
+3
+4# 2. copy the essential files to start
+5$ cp -a themes/hugo-clarity/exampleSite/* . && rm -f config.toml
+

NOTE: We use git submodule here, rather than git clone. Because we already have a .git configuration.

+

Preview

+
1$ hugo server --buildDrafts=true
+

Well done, now we can preview our blog (including drafts) with the URL shown in the Terminal.

+

In this case, my URL to preview is http://localhost:1313/

+

POST NOW

+

In this section, we will talk about how to upload a new post and do some tweaks.

+

Create a new post

+
1$ hugo new post/post-1.md
+

NOTE: the folder is 'post', not 'posts'

+

Fill in the contents

+

Open the newly generated file in ./content/post/post-1.md, and change its header

+
 1---
+ 2title: "Hello World"
+ 3
+ 4description: "The first blog, and how to 'Hugo' a blog"
+ 5summary: "How to use Hugo to build a personal blog, and publish it onto GitHub Pages."
+ 6tags: ["Misc"]
+ 7
+ 8date:    2022-05-15T19:28:07+08:00
+ 9
+10katex: false
+11mermaid: false
+12utterances: true
+13
+14draft: false
+15---
+16
+17Hello World!
+18
+19This is my first blog post.
+

NOTE:

+
    +
  1. the header part begins with 3 dashes
  2. +
  3. the draft: true meaning this file is a draft and will not be rendered into webpage (requires hugo command line $ hugo --buildDrafts=false); however if you do want to display (debug) this draft article, you can use command line $ hugo server --buildDrafts=true.
  4. +
  5. Now that the Hugo server is started, your contents will be synchronized into webpage instantly once you saved your changes.
  6. +
+

Upload

+
 1# 1) generate the output files in ./public
+ 2$ hugo --buildDrafts=false
+ 3$ cd public
+ 4
+ 5# 2) First Time: version control of the file to be published
+ 6$ git init
+ 7$ git remote add origin git@github.com:Mighten/Mighten.github.io.git
+ 8
+ 9# 3) Process the changes and commit
+10$ git add .
+11$ git commit -m 'First Post: Hello World From Hugo!'
+12$ git branch -m master main
+13$ git push -f --set-upstream origin main
+

NOTE:

+
    +
  1. in step 2) the origin is different from person to person, please check your GitHub Settings and set it accordingly
  2. +
  3. in step 3) the upstream origin is usually named main, please go to the GitHub Pages Setting to check it.
  4. +
+

Well Done, Now the first blog is published!

+
+ + +
+
+
* This blog was last updated on 2022-05-15 19:28
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2022/05/how-to-sign-our-git-commits-with-gpg/index.html b/2022/05/how-to-sign-our-git-commits-with-gpg/index.html new file mode 100644 index 0000000..b113883 --- /dev/null +++ b/2022/05/how-to-sign-our-git-commits-with-gpg/index.html @@ -0,0 +1,583 @@ + + + + +How to Sign Our Git Commits with GPG | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

How to Sign Our Git Commits with GPG

+ + +

Hello!

+

Today, let's talk about signing a git commit with GPG, an encryption engine for signing and signature verification.

+

When it comes to work across the Internet, it's recommended that we add a cryptographic signature to our commit, which provides some sort of assurance that a commit is originated from us, rather than from an impersonator.

+

This blog is based on the following environments:

+
    +
  • Windows 10 x64-based
  • +
  • Ubuntu 20.04 LTS, Windows Subsystem Linux (WSL) version 2
  • +
+

1. Preparations

+

In this section, we will install GPG, and config it.

+

Installation

+
1$ sudo apt-get install gnupg
+

And it's done. Next, we have to configure it.

+

Firstly, we will append these two lines to the profile file. In this case, I am using bash. So I will open ~/.bashrc, and append:

+
1export GPG_TTY=$(tty)
+2gpgconf --launch gpg-agent
+

After saving these contents, we will go to the terminal, and type this command to validate settings:

+
1$ source ~/.bashrc
+

And the GPG is ready to go.

+

2. Configurations

+

2.1 Generate a GPG Key Pair

+

Just type this command:

+
1$ gpg --full-gen-key
+

Note:

+
    +
  1. What kind of key you want: RSA and RSA (default)
  2. +
  3. What keysize do you want: 4096
  4. +
  5. How long the key should be valid: 0 (key does not expire)
  6. +
  7. Is this correct: Y
  8. +
  9. Real Name: (Your GitHub Name)
  10. +
  11. E-mail: (Your GitHub Email), and it MUST MATCH your GitHub account !!!
  12. +
  13. Comment: (Leave your note for that key)
  14. +
+

2.2 Add Public Key to GitHub Settings

+

Now that the keys are generated, we need to add the Public Key to GitHub Setting pages.

+

To fill in the contents, we go back to the Terminal, and type these commands to get GPG Public Key:

+
 1# (1) List all the keys
+ 2$ gpg --list-secret-keys --keyid-format=long
+ 3
+ 4# And it shows the following contents: (* hidden for privacy)
+ 5#    sec   rsa4096/********** 2022-05-20 [SC]
+ 6#          ED0BEFAC1E5C4681F0A0FEF0E97461039812B753
+ 7#    uid                 [ultimate] Mighten Dai <mighten@outlook.com>
+ 8#    ssb   rsa4096/********** 2022-05-20 [E]
+ 9
+10# (2) Display the associate Public Key
+11$ gpg --armor --export ED0BEFAC1E5C4681F0A0FEF0E97461039812B753 # copy from above
+

and this command will shows the required Public Key like that:

+
1-----BEGIN PGP PUBLIC KEY BLOCK-----
+2
+3.........
+4-----END PGP PUBLIC KEY BLOCK-----
+

In SSH and GPG Keys of your GitHub Settings, click New GPG Key, and it prompts Begins with '-----BEGIN PGP PUBLIC KEY BLOCK-----', which exactly is the contents above.

+

2.3 Associate with Git

+

In Section 2.2, my Private Key shown as 'ED0BEFAC1E5C4681F0A0FEF0E97461039812B753', so I just open the configuration file ~/.gitconfig and change the following properties:

+
1[user]
+2    name = Mighten Dai
+3    email = mighten@outlook.com
+4    signingKey = ED0BEFAC1E5C4681F0A0FEF0E97461039812B753
+5[commit]
+6    gpgsign = true
+7[gpg]
+8    program = /usr/bin/gpg
+

And it's done.

+

3. Git Commit with GPG

+
1$ git add .
+2$ git commit -S -m "This is a commit with PGP Signature"
+

4. (Optional)

+

In this section, we talk about other usage of GPG

+

4.1 Sign & Verify Plaintext

+

If you just want to sign a plaintext, you just type with a Pipe command | like this:

+
1echo "Signing a plaintext" | gpg --clearsign
+

and it immediately shows:

+
 1-----BEGIN PGP SIGNED MESSAGE-----
+ 2Hash: SHA512
+ 3
+ 4Signing a plaintext
+ 5-----BEGIN PGP SIGNATURE-----
+ 6
+ 7iQIzBAEBCgAdFiEE7QvvrB5cRoHwoP7w6XRhA5gSt1MFAmRxbSoACgkQ6XRhA5gS
+ 8t1OfvA/+IGNwwCfJmwkb2LjhUQgACcUedCS6/VGb7uek7PQwQJr6Aid4hp7cguVz
+ 9lfGpadKTi6chokwcRgwjjuaCd/DFabaHs5e03Q2nn8qqE5Gx+chNcG/+9/cuDRxa
+10JnyEiqTUY62UIGY6+WVYgKE/+T3CpRX3wdLYC3n0InyctdJZNIIycX/IragUhXAh
+11VSZc66QxA60zgNFXzypMyl8NfxmDQKdE8IkCOgiPgHhat0dDQxQQd6zqSmTdQM8P
+12OXpLpT0ryXI9ZnqkOk/gN9mUrncpilelE2J6NgMKbe0lOGNP45F9GQMxqVUQqw/1
+13i6rCTV4gLR+Xmfaydo9fFj5p5mB7VK8IPZGh5Q7RM722D4NxJfaIekhlD1Sy32cP
+14wp0581fHLk778ngz6jomNt/srND5xf13cStdHSxSMwHS8PXxyh5rUs5KtTDH7srg
+15U19l8rdgr9TBl6/ydBlL0aepGQW95KA0loxW2mwrpsEG8Ii1fZ2kMWqR17dPxwoe
+167O3BbeGW0k9Ur3MSm8m5jP2OKvDm62cMiLnUYP3LKakKGL4PBeer26NWK+4dXhi6
+170/ohXd7GGa1zuhChFwj0/pqzjYU2PQLUUOb1/UXKXmpGvu/GvGvZ1Slu0VOKUVil
+18dXv1cxUHgINY6CvoCdH6gxuKmz1K4B8TXqZ4wzMj4FLx/10PtPk=
+19=tIWQ
+20-----END PGP SIGNATURE-----
+

And if some guy send you these thing, you can verify by:

+
1$ gpg --verify signedMsg.txt
+2gpg: Signature made Fri May 20 15:51:09 2022 CST
+3gpg:                using RSA key ED0BEFAC1E5C4681F0A0FEF0E97461039812B753
+4gpg: Good signature from "Mighten Dai <mighten@outlook.com>" [ultimate]
+

It seems that this message is good. What if we want to tamper with this message

+
1$ gpg --verify signedMsg-tampered.txt
+2gpg: Signature made Fri May 20 15:51:09 2022 CST
+3gpg:                using RSA key ED0BEFAC1E5C4681F0A0FEF0E97461039812B753
+4gpg: BAD signature from "Mighten Dai <mighten@outlook.com>" [ultimate]
+

So, now we can see the bad message detected.

+

4.2 Verify Online Files

+

In this section, I will verify the integrity of online files.

+

I have downloaded the file gnupg-2.4.2.tar.bz2.sig and its signature file gnupg-2.4.2.tar.bz2, I can verify by:

+
 1# 1. acquire Public Key of the publisher, 
+ 2#      e.g., https://gnupg.org/signature_key.html
+ 3$ gpg --import  public_key.asc
+ 4...
+ 5gpg: Total number processed: 4
+ 6gpg:               imported: 4
+ 7gpg: marginals needed: 3  completes needed: 1  trust model: pgp
+ 8gpg: depth: 0  valid:   1  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 1u
+ 9
+10# 2. verify the file
+11$ gpg --verify gnupg-2.4.2.tar.bz2.sig  gnupg-2.4.2.tar.bz2
+12gpg: Signature made 5/30/2023 8:27:44 PM China Standard Time
+13gpg:                using EDDSA key 6DAA6E64A76D2840571B4902528897B826403ADA
+14gpg: Good signature from "Werner Koch (dist signing 2020)" [unknown]
+15...
+16
+17# 3. List all the keys
+18$ gpg --list-keys
+19
+20# 4. Delete keys that are temporarily imported
+21$ gpg --delete-key  < The keyID you want to delete >
+
+
+ + +
+
+
* This blog was last updated on 2022-05-20 13:54
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2023/03/servlet/index.html b/2023/03/servlet/index.html new file mode 100644 index 0000000..ec4eeb9 --- /dev/null +++ b/2023/03/servlet/index.html @@ -0,0 +1,1151 @@ + + + + +Servlet | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

Servlet

+ + +

Hi there, todaly let's talk about Servlet in a nutshell.

+

A Servlet is a Java programming language class, which is executed in Web Server and responsible for dynamic content generation in a portable way.

+

Servlet extends the capabilities of servers that host applications accessed by means of a request-response programming model.

+

This blog talks about several topics, shown below:

+
mindmap
+    root(Servlet)
+        Life Cycle
+        Configuration
+        Request and Response
+        Cookies and Sessions
+        Event Listener and Filter
+

But first, let's talk about the hierarchy of Servlet:

+

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets.

+

javax.servlet is a generic interface, and the javax.servlet.http.HttpServlet is an extension of that interface – adding HTTP specific support – such as doGet and doPost.

+

When it comes to writing a Servlet, we usually choose to extend HttpServlet and override doGet and doPost.

+

Life Cycle

+

The web container maintains the life cycle of a servlet instance

+
    +
  1. +

    Load

    +

    when the first request is received, Web Container loads the servlet class and initialize an instance

    +
  2. +
  3. +

    Initialize

    +

    The web container then creates one single servlet instance, to handle all incoming requests on that servlet, even there are concurrent requests.

    +
  4. +
  5. +

    init()

    +

    The web container calls the init() method only once after creating the servlet instance, to initialize the servlet.

    +
  6. +
  7. +

    service()

    +

    For every request, servlet creates a separate thread to execute service()

    +
  8. +
  9. +

    destoy()

    +

    The web container asks servlet to release all the resources associated with it, before removing the servlet instance from the service.

    +
  10. +
+

A typical Servlet demo:

+

snippet of web.xml:

+
 1<?xml version="1.0" encoding="UTF-8"?>
+ 2<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ 3    xmlns="http://java.sun.com/xml/ns/javaee"
+ 4    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+ 5    id="WebApp_ID" version="3.0">
+ 6     
+ 7    <servlet>
+ 8      <servlet-name>ServletLifecycle</servlet-name>
+ 9      <servlet-class>ServletLifecycleExample</servlet-class>
+10    </servlet>
+11 
+12    <servlet-mapping>
+13      <servlet-name>ServletLifecycle</servlet-name>
+14      <url-pattern>/</url-pattern>
+15    </servlet-mapping>
+16</web-app>
+

snippet of index.jsp:

+
 1<%@ page language="java" 
+ 2    contentType="text/html; charset=ISO-8859-1"
+ 3    pageEncoding="ISO-8859-1"%>
+ 4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+ 5<html>
+ 6<head>
+ 7    <title>Servlet Lifecycle Example</title>
+ 8</head>
+ 9<body>
+10  <form action="ServletLifecycle" method="post">
+11      <input type="submit" value="Make request" />
+12  </form>
+13</body>
+14</html>
+

snippet of ServletLifecycleExample.java:

+
 1import java.io.IOException;
+ 2import java.io.PrintWriter;
+ 3 
+ 4import javax.servlet.GenericServlet;
+ 5import javax.servlet.ServletException;
+ 6import javax.servlet.ServletRequest;
+ 7import javax.servlet.ServletResponse;
+ 8 
+ 9public class ServletLifecycleExample extends GenericServlet {
+10     
+11    @Override
+12    public void init() {
+13        System.out.println("Servlet Initialized!");
+14    }
+15 
+16    @Override
+17    public void service(ServletRequest request, ServletResponse response)
+18            throws ServletException, IOException {
+19        response.setContentType("text/html");
+20        PrintWriter out = response.getWriter();
+21        out.println("Servlet called from jsp page!");
+22    }
+23     
+24    @Override
+25    public void destroy() {
+26    }
+27}
+

Servlet life time shown in the sequence chart below:

+
sequenceDiagram
+    participant Browser
+    participant Server
+    participant Servlet
+    autonumber
+    Browser->>Server: Connect to the server
+    Browser->>Server: HTTP GET
+    Server->>Server:  Resolve
+    Server->>Servlet: Load Servlet and create obj for first access
+    Server->>Servlet: invoke `init()`
+    Server->>Servlet: invoke `service()`
+    Servlet->>Servlet: Execute `service()` and generate Response
+    Servlet-->>Server: Response
+    Server-->>Browser: Response
+

Configuration

+

Tomcat

+

Tomcat is a servlet container, which is a runtime shell that manages and invokes servlets on behalf of users.

+

Tomcat has the following directory structure:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DirectoryDescription
binstartup/shutdown... scripts
confconfiguration files including server.xml (Tomcat's global configuration file) and web.xml(sets the default values for web applications deployed in Tomcat)
docdocuments regarding Tomcat
libvarious jar files that are used by Tomcat
logslog files
srcservlet APIs source files, and these are only the empty interfaces and abstract classes that should be implemented by any servlet container
webappssample web applications
workintermediate files, automatically generated by Tomcat
classesto add additional classes to Tomcat's classpath
+

Note:

+
    +
  1. +

    The single most important directory is webapps, where we can manually add our Servlet into it, e.g., if we want to create a servlet named HelloServlet, the first thing we do is to create the directory /webapps/HelloServlet.

    +
  2. +
  3. +

    The default port for Tomcat is 8080, and if we want to switch the port to 80, we just need to modify /conf/server.xml:

    +
    1 <Connector port="80" protocol="HTTP/1.1"
    +2         connectionTimeout="20000"
    +3         redirectPort="8443" />
    +
  4. +
+

web.xml

+

To deploy servlets and map URLs to the servlets, we have to modify the web.xml file, a deployment descriptor, like this:

+
 1<web-app>
+ 2	<servlet>
+ 3		<servlet-name>servletName</servlet-name>
+ 4		<servlet-class>servletClass</servlet-class>
+ 5	</servlet>
+ 6	<servlet-mapping>
+ 7		<servlet-name>servletName</servlet-name>
+ 8		<url-pattern>*.*</url-pattern>
+ 9	</servlet-mapping> 
+10</web-app>  
+

When a request comes, it is matched with URL pattern in servlet mapping attribute.

+

When URL matched with URL pattern, Web Server try to find the servlet name in servlet attributes, same as in servlet mapping attribute.

+

When match found, control goes to the associated servlet class.

+

ServletConfig

+

ServletConfig, a servlet configuration object used by a servlet container to pass information to a servlet during initialization.

+

<init-param> attribute is used to define a init parameter, which refers to the initialization parameters of a servlet or filter. <init-param> attribute has 2 main sub attributes: <param-name> and <param-value>. The <param-name> contains the name of the parameter and <param-value> contains the value of the parameter.

+

Example:

+

snippet of web.xml:

+
1<init-param>
+2    <param-name>appUser</param-name>
+3    <param-value>jai</param-value>
+4</init-param>
+

snippet of InitParamExample.java:

+
1ServletConfig config = getServletConfig();
+2String appUser = config.getInitParameter("appUser");
+

This example shows how to read web.xml, and get init parameters "appUser": "jai" for initialization.

+

ServletContext

+

ServletContext defines a set of methods that a servlet will use to communicate with its servlet container, to share initial parameters or configuration information to the whole application.

+

<context-param> attribute is used to define a context parameter, which refers to the initialization parameters for all servlets of an application. <context-param> attribute also has 2 main sub attributes: <param-name> and <param-value>. And also, the <param-name> contains the name of the parameter, the <param-value> contains the value of the parameter.

+

Example:

+

snippet of web.xml:

+
1<context-param>
+2    <param-name>appUser</param-name>  
+3    <param-value>jai</param-value>  
+4</context-param>
+

snippet of ContextParamExample.java:

+
1ServletContext context = this.getServletContext();
+2String value = (String) context.getAttribute("appUser");
+

This example shows how to read web.xml, and get context parameters "appUser": "jai" for communication.

+

load-on-startup

+

The load-on-startup is the sub attribute of servlet attribute in web.xml. It is used to control when the web server loads the servlet.

+

As we discussed that servlet is loaded at the time of first request. In this case, response time is increased for first request.

+

If load-on-startup is specified for a servlet in web.xml, then this servlet will be loaded when the server starts. So the response time will NOT increase for fist request.

+

Example:

+
 1<servlet>  
+ 2    <servlet-name>servlet1</servlet-name>  
+ 3    <servlet-class>com.w3spoint.business.Servlet1 </servlet-class>
+ 4    <load-on-startup>0</load-on-startup>  
+ 5</servlet>  
+ 6
+ 7<servlet>  
+ 8    <servlet-name>servlet2</servlet-name>  
+ 9    <servlet-class> com.w3spoint.business.Servlet2</servlet-class>
+10    <load-on-startup>1</load-on-startup>  
+11</servlet>    
+12
+13<servlet>  
+14    <servlet-name>servlet3</servlet-name>  
+15    <servlet-class> com.w3spoint.business.Servlet3</servlet-class>
+16    <load-on-startup>-1</load-on-startup>  
+17</servlet>  
+

In the example above, Servlet1 and Servlet2 will be loaded when server starts because non-negative value is passed in there load-on-startup. While Servlet3 will be loaded at the time of first request because negative value is passed in there load-on-startup.

+

Request and Response

+

There is a method named service() in package javax.servlet, as is mentioned in the 'Life Cycle' section, it has a prototype like this:

+
1void service(ServletRequest request,
+2             ServletResponse response)
+3      throws ServletException,
+4             IOException
+

where request is the ServletRequest object that contains the client's request, and response is the ServletResponse object that contains the servlet's response

+

ServletRequest

+

ServletRequest defines an object to provide client request information to a servlet.

+

The servlet container creates a ServletRequest object and passes it as an argument to the servlet's service() method. A ServletRequest object provides data including parameter name and values, attributes, and an input stream.

+

To transfer data to other component, we can use getAttribute(), setAttribute() of ServletRequest, example code:

+
 1@WebServlet(name = "LoginServlet", urlPatterns = {"/login.do"})
+ 2public class LoginServlet extends HttpServlet {
+ 3    public void doPost(HttpServletRequest  request, 
+ 4                       HttpServletResponse response)
+ 5                throws ServletException, IOException {
+ 6        String  username = request.getParameter("username");
+ 7        String  password = request.getParameter("password");
+ 8        if (username.equals("admin") && 
+ 9            password.equals("5F4DCC3B5AA765D61D8327DEB882CF99")) {
+10            // Logged in
+11            RequestDispatcher  rd = 
+12                    request.getRequestDispatcher("/welcome.jsp");
+13            //   to store `username` in request object
+14            request.setAttribute("user", username);
+15            rd.forward(request, response);
+16        } else {
+17            // Failed to log in
+18            RequestDispatcher  rd = 
+19                    request.getRequestDispatcher("/login.jsp");
+20            rd.forward(request, response);
+21        }
+22
+23    }
+24}
+

HttpServletRequest

+

HttpServletRequest interface adds the methods that relates to the HTTP protocol.

+
classDiagram
+    class ServletRequest {
+        +getAttribute()
+        +getParameter()
+    }
+    class HttpServletRequest {
+        +getMethod()
+        +getSession()
+    }
+    ServletRequest <|-- HttpServletRequest: extends
+

(Note: could not display <<interface>> for both classes, due to error of Mermaid version 9.4.3 , maybe the Mermaid-js team will fix this issue later)

+

The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service() methods (doGet(), doPost(), etc).

+

Demo of HttpServletRequest:

+

snippet of index.html:

+
1<form method="post" action="check">
+2    Name <input type="text" name="user" >
+3    <input type="submit" value="submit">
+4</form>
+

snippet of web.xml:

+
1<servlet>
+2    <servlet-name>check</servlet-name>
+3    <servlet-class>MyHttpServletRequestServlet</servlet-class>
+4</servlet>
+5<servlet-mapping>
+6    <servlet-name>check</servlet-name>
+7    <url-pattern>/check</url-pattern>
+8</servlet-mapping>
+

snippet of MyHttpServletRequestServlet.java:

+
 1import java.io.*;
+ 2import javax.servlet.*;
+ 3import javax.servlet.http.*;
+ 4
+ 5public class MyHttpServletRequestServlet extends HttpServlet {
+ 6
+ 7  protected void doPost(HttpServletRequest request, 
+ 8                        HttpServletResponse response)
+ 9                throws ServletException, IOException {
+10       response.setContentType("text/html;charset=UTF-8");
+11        PrintWriter out = response.getWriter();
+12        try {
+13            String user = request.getParameter("user");
+14            out.println("<h2> Welcome "+user+"</h2>");
+15        } finally {            
+16            out.close();
+17        }
+18    }
+19}
+

RequestDispatcher

+

RequestDispatcher defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.

+

The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.

+

Methods of RequestDispacher interface:

+
1public void forward(ServletRequest request,
+2                    ServletResponse response)
+3            throws ServletException, IOException
+4
+5public void include(ServletRequest request,
+6                    ServletResponse response)
+7            throws ServletException, IOException
+

To get an object of RequestDispacher:

+

RequestDispacher object can be gets from HttpServletRequest object.

+

ServletRequest’s getRequestDispatcher() method is used to get RequestDispatcher object.

+

Example:

+
 1protected void doPost(HttpServletRequest request, 
+ 2                      HttpServletResponse response) 
+ 3                throws ServletException, IOException {
+ 4    response.setContentType("text/html"); 
+ 5    PrintWriter out = response.getWriter();
+ 6
+ 7    //get parameters from request object.
+ 8    String userName = 
+ 9        request.getParameter("userName").trim();
+10    String password = 
+11        request.getParameter("password").trim();
+12
+13    //check for null and empty values.
+14    if(userName == null || userName.equals("") 
+15            || password == null || password.equals("")){
+16        out.print("Please enter both username" +
+17                " and password. <br/><br/>");
+18        RequestDispatcher requestDispatcher = 
+19            request.getRequestDispatcher("/login.html");
+20        requestDispatcher.include(request, response);
+21    }//Check for valid username and password.
+22    else if(userName.equals("jai") && 
+23            password.equals("1234")){
+24        RequestDispatcher requestDispatcher = 
+25            request.getRequestDispatcher("WelcomeServlet");
+26        requestDispatcher.forward(request, response);
+27    }else{
+28        out.print("Wrong username or password. <br/><br/>");
+29        RequestDispatcher requestDispatcher = 
+30            request.getRequestDispatcher("/login.html");
+31        requestDispatcher.include(request, response);
+32    }
+33}
+

In brief:

+
 1// 1. use `requestDispatcher.include()`:
+ 2//      if invalid `userName` or `password` inputed,
+ 3//          return to 'login.html' and retry
+ 4RequestDispatcher requestDispatcher = 
+ 5    			request.getRequestDispatcher("/login.html");
+ 6requestDispatcher.include(request, response);
+ 7
+ 8// 2. use `requestDispatcher.forward()`:
+ 9//      if correct `userName` and `password` inputed,
+10//          return to 'Welcome Servlet'
+11RequestDispatcher requestDispatcher = 
+12    			request.getRequestDispatcher("WelcomeServlet");
+13requestDispatcher.forward(request, response);
+

ServletResponse

+

ServletResponse defines an object to assist a servlet in sending a response to the client.

+

The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service() method. To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.

+

HttpServletResponse

+

HttpServletResponse extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.

+

The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's service() methods (doGet(), doPost(), etc).

+

Cookies and Sessions

+

There are 2 mechanisms which allow us to store user data between subsequent requests to the server – the cookie and the session

+ +

A cookie is a small piece of information as a text file stored on client’s machine by a web application.

+

The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

+

The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies() method. Several cookies might have the same name but different path attributes.

+

There are 2 types of cookies:

+
    +
  1. +

    Session cookies (Non-persistent cookies) +They are accessible as long as session is open, and they are lost when session is closed by exiting from the web application.

    +
  2. +
  3. +

    Permanent cookies(Persistent cookies) +They are still alive when session is closed by exiting from the web application, and they are lost when they expire.

    +
  4. +
+

Example:

+
 1//create cookie object  
+ 2Cookie cookie=new Cookie(cookieName,cookieValue);
+ 3response.addCookie(cookie);
+ 4
+ 5//get all cookie objects.
+ 6Cookie[] cookies = request.getCookies();
+ 7for(Cookie cookie : cookies){
+ 8    out.println(Cookie Name:  + cookie.getName());
+ 9    out.println(Cookie Value:  + cookie.getValue());
+10}
+11
+12//Remove value from cookie
+13Cookie cookie = new Cookie(cookieName, “”);
+14cookie.setMaxAge(0);
+15response.addCookie(cookie);
+

HttpSession

+

HttpSession is an interface that provides a way to identify a user in multiple page requests. A unique session id is given to the user when first request comes. This id is stored in a request parameter or in a cookie.

+

Example:

+
1HttpSession session = request.getSession();
+2session.setAttribute("attName", "attValue");
+3String value = (String) session.getAttribute("attName"); 
+

Filter and Event Listener

+

In web applications, we use filters to preprocess and postprocess the parameters. And during runtime of web apps, we use event listeners to do callback stuff.

+

Filter

+

A filter is an object that is invoked at the preprocessing and postprocessing of a request on the server.

+

Servlet filters are mainly used for following tasks:

+
    +
  1. +

    Preprocessing

    +

    Preprocessing of request before it accesses any resource at server side.

    +
  2. +
  3. +

    Postprocessing

    +

    Postprocessing of response before it sent back to client.

    +
  4. +
+
flowchart TD
+    Client <--> Listener[Web<br/>Listener]
+    Listener <--> Container[Servlet Container]
+    Container --> |Request| Filter1 --> Filter2 --> FilterN --> Servlet
+    Servlet --> |Response| FilterN --> Filter2 --> Filter1 --> Container
+
+

The order in which filters are invoked depends on the order in which they are configured in the web.xml file. The first filter in web.xml is the first one invoked during the request, and the last filter in web.xml is the first one invoked during the response. Note the reverse order during the response.

+

Filter API (or interface) includes some methods which help us in filtering requests:

+
1public void init(FilterConfig config)
+2public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain)
+3public void destroy()
+

To create a filter, implement javax.servlet.Filter interface

+

<filter> attribute is used to define a filter in web.xml:

+
1<filter>
+2    <filter-name>filterName </filter-name>
+3    <filter-class>filterClass</filter-class>
+4</filter>
+5<filter-mapping>
+6    <filter-name>filterName</filter-name>
+7    <url-pattern>urlPattern</url-pattern>
+8</filter-mapping>
+

FilterChain object is used to call the next filter or a resource, if it is the last filter in filter chaining.

+

Example:

+

snippet of MyFilter.java:

+
 1public class MyFilter implements Filter {
+ 2
+ 3	public void init(FilterConfig filterConfig) throws ServletException { }
+ 4
+ 5	@Override
+ 6	public void doFilter(ServletRequest request,
+ 7						ServletResponse response,
+ 8						FilterChain chain)
+ 9		        throws IOException, ServletException
+10	{
+11
+12		PrintWriter out = response.getWriter();
+13		System.out.println("preprocessing before servlet");
+14        // pass to next filter for more check
+15		chain.doFilter(request, response);
+16		System.out.println("postProcessing after servlet");
+17	}
+18
+19	public void destroy() {}
+20}
+21
+

snippet of index.html:

+
1<form action="MyFilterServlet">
+2    <button type="submit">Click here to go to the Servlet</button>
+3</form>
+
 1<?xml version="1.0" encoding="UTF-8"?>
+ 2<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ 3		xmlns="http://xmlns.jcp.org/xml/ns/javaee"
+ 4		xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
+ 5							http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
+ 6		id="WebApp_ID" version="4.0">
+ 7<display-name>MyFilterServlet</display-name>
+ 8<welcome-file-list>
+ 9	<welcome-file>index.html</welcome-file>
+10</welcome-file-list>
+11	
+12<filter>
+13	<filter-name>filter1</filter-name>
+14	<filter-class>com.app.MyFilterServlet</filter-class>
+15</filter>
+16	
+17<filter-mapping>
+18	<filter-name>filter1</filter-name>
+19	<url-pattern>/MyFilterServlet</url-pattern>
+20</filter-mapping>
+21	
+22</web-app>
+23
+

snippet of MyFilterServlet.java:

+
 1@WebServlet("/MyFilterServlet")
+ 2public class MyFilterServlet extends HttpServlet {
+ 3
+ 4	protected void doGet(HttpServletRequest request,
+ 5						HttpServletResponse response)
+ 6		            throws ServletException, IOException
+ 7	{
+ 8		PrintWriter out = response.getWriter();
+ 9		out.println("<h1>Welcome to the Servlet.");
+10		System.out.println("MyFilterServlet is running");
+11	}
+12
+13	protected void doPost(HttpServletRequest request,
+14						HttpServletResponse response)
+15		            throws ServletException, IOException 
+16    {
+17		doGet(request, response);
+18	}
+19}
+

Event Listener

+

Event Listener allows Servlet to track key events in your Web applications through event listeners.

+

This functionality allows more efficient resource management and automated processing based on event status.

+
flowchart TD
+    Client <--> Listener[Web<br/>Listener]
+    Listener <--> Container[Servlet Container]
+    Container --> |Request| Servlet
+    Servlet --> |Response| Container
+

There are 2 levels of servlet events:

+
    +
  1. +

    Servlet context-level (application-level) event

    +

    This event involves resources or state held at the level of the application servlet context object.

    +
  2. +
  3. +

    Session-level event

    +

    This event involves resources or state associated with the series of requests from a single user session; that is, associated with the HTTP session object.

    +
  4. +
+

Listeners handling Servlet Lifecycle Events:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Object: EventListener InterfaceEvent Class
Web context: Initialization and destructionServletContextListenerServletContextEvent
Web context: Attribute added, removed, or replacedServletContextAttributeListenerServletContextAttributeEvent
Session: Creation, invalidation, activation, passivation, and timeoutHttpSessionListener, HttpSessionActivationListenerHttpSessionEvent
Session: Attribute added, removed, or replacedHttpSessionAttributeListenerHttpSessionBindingEvent
Request: A servlet request has started being processed by web componentsServletRequestListenerServletRequestEvent
Request: Attribute added, removed, or replacedServletRequestAttributeListenerServletRequestAttributeEvent
+

Event classes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Event ClassMethods
ServletRequestEventgetServletContext(), getServletRequest()
ServletContextEventgetServletContext()
ServletRequestAttributeEventgetName(), getValue()
ServletContextAttributeEventgetName(), getValue()
HttpSessionEventsessionCreated(), sessionDestroyed(), sessionWillPassivate(), sessionDidActivate()
HttpSessionBindingEventgetName(), getSession(), getValue()
+

Configure the Listener class in the web.xml files:

+
1<web-app>
+2    <listener>
+3        <listener-class>myListenerName</listener-class>
+4    </listener>
+5</web-app>
+

Note: Except for HttpSessionBindingListener and HttpSessionActivationListener, all Listeners require the aforementioned listener configuration.

+

Example Code of AppContextAttributeListener:

+

snippet of web.xml:

+
1<listener>
+2    <listener-class>AppContextAttributeListener</listener-class>
+3</listener>
+

snippet of AppContextAttributeListener.java:

+
 1@WebListener
+ 2public class AppContextAttributeListener implements ServletContextAttributeListener {
+ 3	public void attributeAdded(ServletContextAttributeEvent	event) {
+ 4		System.out.println( "ServletContext attribute added::{" event.getName() + ","+ event.getValue() + "}");
+ 5	}
+ 6
+ 7	public void	attributeReplaced(ServletContextAttributeEvent event) {
+ 8        System.out.println( "ServletContext attribute replaced::{" event.getName() + ","+ event.getValue() + "}");
+ 9	}
+10	public void	attributeRemoved(ServletContextAttributeEvent event) {
+11
+12        System.out.println( "ServletContext attribute removed::{" event.getName() + ","+ event.getValue() + "}");
+13	}
+14}
+
+
+ + +
+
+
* This blog was last updated on 2023-03-30 18:05
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2023/04/linked-list/index.html b/2023/04/linked-list/index.html new file mode 100644 index 0000000..13e8507 --- /dev/null +++ b/2023/04/linked-list/index.html @@ -0,0 +1,652 @@ + + + + +Linked List | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

Linked List

+ + +

Today, let's talk about Linked List algorithms that are frequently used.

+

A Linked List is a data structure that stores data into a series of connected nodes, and thus it can be dynamically allocated. For each node, it contains 2 fields: the val that stores data, and the next that points to the next node.

+

In LeetCode, the Linked List is often defined below, using C++:

+
1struct ListNode {
+2    int val;
+3    ListNode *next;
+4};
+

The content of this blog is shown below:

+
mindmap
+root)Linked List(
+        A1(Node Removal)
+        A2(Inplace Reversal)
+        A3(Merge)
+        A4(Insertion Sort)
+        A5(Two Pointer)
+

Node Removal

+

LeetCode 203: Remove Linked List Elements

+

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

+
 1ListNode* removeElements(ListNode* head, int val){
+ 2    ListNode newHead;
+ 3    ListNode  *pre = &newHead;
+ 4    newHead.next = head;
+ 5
+ 6    while (pre->next != nullptr ) {
+ 7        ListNode *cur = pre->next;
+ 8        if (cur->val == val ) {
+ 9            pre->next = cur->next;
+10            delete cur;
+11        }else
+12            pre = pre->next;
+13    }
+14    return newHead.next;
+15}
+

In-place Reversal

+

LeetCode 206. Reverse Linked List

+

Given the head of a singly linked list, reverse the list, and return the reversed list.

+
1ListNode* reverseList(ListNode* head) {
+2    ListNode *pre = nullptr, *cur = head;
+3    while (cur != nullptr ) {
+4        ListNode *next = cur->next;
+5        cur->next = pre;
+6        pre = cur, cur = next;
+7    }
+8    return pre;
+9}
+

Merge

+

LeetCode 21. Merge Two Sorted Lists

+

You are given the heads of two sorted linked lists list1 and list2.

+

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

+

Return the head of the merged linked list.

+
 1ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
+ 2    ListNode head;
+ 3    ListNode *pre = &head;
+ 4
+ 5    while (list1 != nullptr && list2 != nullptr ) {
+ 6        if (list1->val < list2->val ) {
+ 7            pre->next = list1;
+ 8            list1 = list1->next;
+ 9        } else {
+10            pre->next = list2;
+11            list2 = list2->next;
+12        }
+13        pre = pre->next;
+14    }
+15
+16    while (list1 != nullptr ) {
+17        pre->next = list1;
+18        pre = pre->next;
+19        list1 = list1->next;
+20    }
+21
+22    while (list2 != nullptr ) {
+23        pre->next = list2;
+24        pre = pre->next;
+25        list2 = list2->next;
+26    }
+27    pre->next = nullptr;
+28    return head.next;
+29}
+

Insertion Sort

+

LeetCode 147. Insertion Sort List

+

Given the head of a linked list, return the list after sorting it in ascending order.

+

Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.

+

The steps of the insertion sort algorithm:

+
    +
  1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
  2. +
  3. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
  4. +
  5. It repeats until no input elements remain.
  6. +
+
 1ListNode* insertionSortList(ListNode* head) {
+ 2    if (head == nullptr) return head;
+ 3    ListNode tmpHead;
+ 4    ListNode *cur = head, *pre = &tmpHead;
+ 5
+ 6    while (cur != nullptr) {
+ 7        while (pre->next != nullptr && pre->next->val < cur->val)
+ 8            pre = pre->next;
+ 9
+10        ListNode* next = cur->next;
+11        cur->next = pre->next;
+12        pre->next = cur;
+13        pre = &tmpHead;
+14        cur = next;
+15    }
+16    return tmpHead.next;
+17}
+

Two Pointer

+

We often use fast and slow to solve Linked List problems in $O(n)$-time complexity.

+

Middle Node

+

LeetCode 876. Middle of the Linked List

+

Given the head of a singly linked list, return the middle node of the linked list.

+

If there are two middle nodes, return the second middle node.

+
1ListNode* middleNode(ListNode* head) {
+2    ListNode *fast = head, *slow = head;
+3    while (fast != nullptr && fast->next != nullptr) {
+4        fast = fast->next->next;
+5        slow = slow->next;
+6    }
+7    return slow;
+8}
+

Cycle Detection

+

LeetCode 142. Linked List Cycle II

+

Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

+

Do not modify the linked list.

+
 1ListNode *detectCycle(ListNode *head) {
+ 2    ListNode *fast = head, *slow = head;
+ 3
+ 4    // Judge if cycle exists
+ 5    while ( true ) {
+ 6        if (fast == nullptr || fast->next == nullptr )
+ 7            return nullptr;
+ 8        fast = fast->next->next;
+ 9        slow = slow->next;
+10        if (fast == slow) break;  // Cycle detect
+11    }
+12
+13    // yes there is a cycle, and find the entry of cycle
+14    ListNode *ptr = head;
+15    while (ptr != slow ) {
+16        ptr = ptr->next;
+17        slow = slow->next;
+18    }
+19    return ptr; 
+20}
+
+
+ + +
+
+
* This blog was last updated on 2023-04-05 22:22
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2023/04/mit-6.033-cse-operating-system/index.html b/2023/04/mit-6.033-cse-operating-system/index.html new file mode 100644 index 0000000..55cd601 --- /dev/null +++ b/2023/04/mit-6.033-cse-operating-system/index.html @@ -0,0 +1,839 @@ + + + + +MIT 6.033 CSE Operating System | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

MIT 6.033 CSE Operating System

+ + +

MIT 6.033 (Computer System Engineering) covers 4 parts: Operating Systems, Networking, Distributed Systems, and Security.

+

This is the course note for Part I: Operating Systems. And in this section, we mainly focus on:

+
    +
  • How common design patterns in computer system — such as abstraction and modularity — are used to limit complexity.
  • +
  • How operating systems use virtualization and abstraction to enforce modularity.
  • +
+

Complexity

+

In this section, we talk about what is complexity in computer systems, and how to mitigate it.

+

A system is a set of interconnected components that has an expected behavior observed at the interface with its environment.

+

So we say that a system has complexity, which limits what we can build. However, complexity can be mitigated with design patterns, such as modularity and abstration.

+

Nowadays, we usually enforce modularity by Client/Server Model, or C/S Model, where two modules reside on different machines and communicate with RPCs.

+

Naming Schemes

+

In this section, we talk about naming, which allows modules to communicate.

+

Naming is that a name can be resolved to the entity it refers to. Therefore, it allows modules to interact, and can help to achieve goals such as indirection, user-friendliness, etc.

+

The design of a naming scheme has 3 parts: name, value, and look-up algorithm.

+

One great case of naming scheme is Domain Name System (DNS), which illustrates principles such as hierarchy, scalability, delegation and decentralization. Especially, the hierarchical design of DNS let us scale up to the Internet.

+

Virtual Memory

+

Virtual Memory is a primary technique that uses Memory Management Unit (MMU) to translate virtual address into physical address by using page tables.

+

To enforce modularity, the operating system(OS) kernel checks the following 3 bits:

+ + + + + + + + + + + + + + + + + + + + + +
NameDescription
User/Supervisor (U/S) bitif the program allowed to access the address
Present (P) bitif the page currently in memory
User/Kernel (U/K) bitwhether the operation is in user mode or kernel mode
+

These 3 bits let the OS know when to trigger page faults, and if the access triggers an exception, the OS kernel will first switch to kernel mode and then execute the corresponding exception handler before switching back to user mode.

+

To deal with performance issues, the Operating Systems introduce two mechanisms: hierarchical page table and cache. The hierarchical(multilevel) page table reduces the memory overhead associated with the page table, at the expense of more table look-ups. And cache, also known as Translation Lookaside Buffer (TLB), stores recent translations of virtual memory to physical addresses to enable faster retrieval.

+

OS enforces modularity by virtualization and abstraction. +On resources that can be virtualized, such as memory, OS uses virtualization. And for those components that are difficult to virtualize such as disk and network, OS presents abstration.

+

Bounded Buffer with Lock

+

Let's virtualize communication links - the bouded buffers.

+

But first, we need Lock, which is a protecting mechanism that allows only one CPU to execute a piece of code at a time to implement atomic actions. If two CPUs try to acquire the same lock at the same time, only one of them will succeed and the other will block until the first CPU releases the lock.

+

Implementing locks is possible by the support of a special hardware called controller that manages access to memory.

+
1acquire(lock):
+2    do:
+3        r = 1
+4        XCHG r, lock
+5    while r == 1
+6
+7release(lock):
+8    lock = 0
+

A bounded buffer is a buffer that has (up to) N slots and allows concurrent programs to send/receive messages.

+

A bounded buffer with lock may deal with race condition, therefore, we need to decide where to put locks:

+
    +
  • coarse-grained locking is easy to maintain correctness, but it will lead to bad performance;
  • +
  • fine-grained locking improves performance, but it may cause inconsistent state;
  • +
  • multiple locking requires that locks are acquired in the same order, otherwise the dead lock may happen.
  • +
+

In addition, bounded buffer with lock is yet another example of virtualization, which means any of senders/receivers think it has full access to the whole buffer.

+

Concurrent Threads

+

Let's virtualize processors - the threads.

+

Thread

+

Thread is a virtual processor and has 3 states:

+
    +
  • RUNNING (actively running)
  • +
  • RUNNABLE (ready to go, but not running)
  • +
  • WAITING (waiting for a particular event)
  • +
+

To change the states of a thread, we often use 2 APIs:

+
    +
  • suspend(): save state of current thread to memory.
  • +
  • resume(): restore state from memory.
  • +
+

In reality, most threads spend most of the time waiting for events to occur. So we use yield() to let the current thread voluntarily suspend itself, and then let the kernel choose a new thread to resume execution.

+

In particular, we maintain a processor table and a thread table.

+
    +
  • The processor table (cpus) keeps track of which processor is currently running which thread;
  • +
  • The thread table (threads) keeps track of thread states.
  • +
+
 1yield_():
+ 2    acquire(t_lock)
+ 3    # 1. Suspend the running thread
+ 4    id = cpus[CPU].thread # thread #id is on #CPU
+ 5    threads[id].state = RUNNABLE
+ 6    threads[id].sp = SP   # stack pointer
+ 7    threads[id].ptr = PTR # page table register
+ 8
+ 9    # 2. Choose the new thread to run
+10    do:
+11        id = (id + 1) mod N
+12    while threads[id].state != RUNNABLE
+13
+14    # 3. Resume the new thread
+15    SP = threads[id].sp
+16    PTR = threads[id].ptr
+17    threads[id].state = RUNNING
+18    cpus[CPU].thread = id
+19
+20    release(t_lock)
+21
+22# send a `message` into `bb`(N-slot buffer)
+23send(bb, message ):
+24    acquire(bb.lock)
+25    # when the buffer is full
+26    while bb.in_num - bb.out_num >= N:
+27        release(bb.lock)
+28        yield_()
+29        acquire(bb.lock)
+30    bb.buf[bb.in_num % N] <- message
+31    bb.in_num += 1
+32    release(bb.lock)
+33
+34# reveive a message from bb
+35receive(bb):
+36    acquire(bb.lock)
+37    # while the buffer is empty
+38    while bb.out_num >= bb.in_num:
+39        release(bb.lock)
+40        yield_()
+41        acquire(bb.lock)
+42    message <- bb.buf[bb.out_num % N]
+43    bb.out_num += 1
+44    release(bb.lock)
+45    return message
+

However, the sender may get resumed in the meantime, even if there is no room in buffer. One solution to fix that is to use condition variables

+

Condition Variable

+

Condition variable is simply a synchronization primitive that allow kernel to notify threads instead of having threads constantly make checks. And it has 2 APIs:

+
    +
  • wait(cv): yield processor and wait to be notified of cv, a condition variable.
  • +
  • notify(cv): notify threads that are waiting for cv.
  • +
+

However, condition variables without lock may cause "Lost notify" problem:

+
 1# send a `message` into `bb`(N-slot buffer)
+ 2send(bb, message ):
+ 3    acquire(bb.lock)
+ 4    # while the buffer is full
+ 5    while bb.in_num - bb.out_num >= N:
+ 6        release(bb.lock)
+ 7        wait(bb.has_space)  ### !
+ 8        acquire(bb.lock)
+ 9    bb.buf[bb.in_num % N] <- message
+10    bb.in_num += 1
+11    release(bb.lock)
+12    notify(bb.has_message)
+13    return
+14
+15# reveive a message from bb
+16receive(bb):
+17    acquire(bb.lock)
+18    # while the buffer is empty
+19    while bb.out_num >= bb.in_num:
+20        release(bb.lock)
+21        wait(bb.has_message)
+22        acquire(bb.lock)
+23    message <- bb.buf[bb.out_num % N]
+24    bb.out_num += 1
+25    release(bb.lock)
+26    notify(bb.has_space) ### !
+27    return message
+

Considering there are two threads: T1(sender), and T2(receiver).

+
    +
  • T1 acquires bb.lock on buffer, finding it full, so T1 releases bb.lock
  • +
  • Prior to T1 calling wait(bb.has_space), T2 just acquires bb.lock to read messages, notifying the T1 that the buffer now has space(s).
  • +
  • but T1 is actually not yet waiting for bb.has_space (Bacause T1 was interrupted by OS before it could call wait(bb.has_space)).
  • +
+

So, as you can see, it cause the "lost notify" problem. And the solution to fix that is use a lock.

+
    +
  • wait(cv, lock): yield processor, release +lock, wait to be notified of cv
  • +
  • notify(cv): notify waiting threads of cv
  • +
+
 1yield_wait():
+ 2    id = cpus[CPU].thread
+ 3    threads[id].sp = SP
+ 4    threads[id].ptr = PTR
+ 5    SP = cpus[CPU].stack # avoid stack corruption
+ 6
+ 7    do:
+ 8        id = (id + 1) mod N
+ 9        release(t_lock) # !
+10        acquire(t_lock) # !
+11    while threads[id].state != RUNNABLE
+12
+13    SP = threads[id].sp 
+14    PTR = threads[id].ptr
+15    threads[id].state = RUNNING
+16    cpus[CPU].thread = id
+17
+18
+19wait(cv, lock):
+20    acquire(t_lock)
+21    release(lock) # let others access what `lock` protects
+22    # mark the current thread: wait for `cv`
+23    id = cpus[CPU].thread
+24    threads[id].cv = cv
+25    threads[id].state = WAITING
+26
+27    # different from `yield_()` mentioned above!
+28    yield_wait()
+29    
+30    release(t_lock)
+31    acquire(lock) # disallow others to access what `lock` protects
+32
+33
+34notify(cv):
+35    acquire(t_lock)
+36    # Find all threads waiting for `cv`,
+37    #  and change states: WAITING -> RUNNABLE
+38    for id = 0 to N-1:
+39        if threads[id].cv == cv &&
+40         threads[id].state == WAITING:
+41            threads[id].state = RUNNABLE
+42    release(t_lock)
+43
+44# send `message` into N-slot buffer `bb`
+45send(bb, message):
+46    acquire(bb.lock)
+47    while bb.in_num - bb.out_num >= N:
+48        wait(bb.has_space, bb.lock)
+49    bb.buf[bb.in_num % N] <- message
+50    bb.in_num += 1
+51    release(bb.lock)
+52    notify(bb.has_message)
+53    return
+54
+55# reveive a message from bb
+56receive(bb):
+57    acquire(bb.lock)
+58    # while the buffer is empty
+59    while bb.out_num >= bb.in_num:
+60        wait(bb.has_message, bb.lock)
+61    message <- bb.buf[bb.out_num % N]
+62    bb.out_num += 1
+63    release(bb.lock)
+64    notify(bb.has_space)
+65    return message
+

Note:

+
    +
  • Why yield_wait(), rather than yield_()? Because yield_() will cause Deadlock. At the beginning of wait(cv, lock), we acquire and hold t_lock. So if we invoke yield_(), it will try to acquire t_lock again, causing deadlock problem.
  • +
  • Why yield_wait() releases and then immediately acquires t_lock? Because it guarantee other threads can access the buffer. Considering there are 5 senders writing into buffer and only 1 receiver reading the buffer. If all 5 senders find the buffer full, it is important to release t_lock to let the only 1 receiver acquire the t_lock and read the buffer.
  • +
  • Why do we need to SP = cpus[CPU].stack? To avoid stack corruption when this thread is scheduled to a different CPU.
  • +
+

And the new problem arises, what if the thread never yield CPU? Use preemption.

+

Preemption

+

Preemption forcibly interrupts a thread so that we don’t have to rely on programmers correctly using yield(). In this case, if a thread never calls yield() or wait(), it’s okay; special hardware will periodically generate an interrupt and forcibly call yield().

+

But what if this interrupt occurs while running yield() or yield_wait(): Deadlock. And the solution is to require hardware mechanism to disable interrupts.

+

Kernel

+

The kernel is a non-interruptible, trusted program that runs system code.

+

Kernel errors are fatal, so we try to limit the size of kernel code. There are two models for kernels.

+
    +
  • The monolithic kernel implements most of the OS in the kernel, and everything sharing
  • +
  • The microkernel implements different features as client-servers. They enforce modularity by putting subsystems in user programs.
  • +
+

Virtual Machine

+

Virtual Machine (VM) allows us to run multiple isolated operating systems on a single physical machine. VMs must handle the challenges of virtualizing the hardware.

+

+ + + + + + + + + + +
+ Figure 1. Virtual Machine Environment + +
+
+
+

+

The Virtual Machine Monitor (VMM) deals with privileged instructions, allocates resources, and dispatches events.

+

The guest OS runs in user mode. Privileged instructions throw exceptions, and VMM will trap and emulate. In modern hardware, the physical hardware +knows of both page tables, and it directly translates from guest virtual address to host physical address.

+

However, there are still some cases in which we cannot trap exceptions. There are several solutions:

+
    +
  • Para-virtualization is where the guest OS changes a bit, which defeats the purpose of a VM
  • +
  • Binary translation is also a method (VMWare used to use this), +but it is slightly messy
  • +
  • Hardware support for virtualization means that hardware has VMM capabilities built-in. The guest OS can directly manipulate page tables, etc. Most VMMs today have hardware support.
  • +
+

Performance

+

There are 3 metrics to measure performance:

+
    +
  • latency: how long does it take to complete a single task?
  • +
+

+ + + + + + + + + + +
+ Figure 2. Latency vs. number of users + +
+
+
+

+
    +
  • Throughput: the rate of useful work, or how many requests per unit of time.
  • +
+

+ + + + + + + + + + +
+ Figure 3. Throughput vs. number of users + +
+
+
+

+
    +
  • Utilization: what fraction of resources are being utilized
  • +
+
+ + +
+
+
* This blog was last updated on 2023-04-06 15:06
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2023/05/mit-6.033-cse-networking/index.html b/2023/05/mit-6.033-cse-networking/index.html new file mode 100644 index 0000000..9066811 --- /dev/null +++ b/2023/05/mit-6.033-cse-networking/index.html @@ -0,0 +1,768 @@ + + + + +MIT 6.033 CSE Networking | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

MIT 6.033 CSE Networking

+ + +

MIT 6.033 (Computer System Engineering) covers 4 parts: Operating Systems, Networking, Distributed Systems, and Security.

+

This is the course note for Part II: Networking. And in this section, we mainly focus on: how the Internet is designed to scale and its various applications.

+

Network Topology

+

A network is a graph of many nodes: endpoints and switches. Endpoints are physical devices that connect to and exchange information with network. Switches deal with many incoming and outgoing connections on links, and help forward data to destinations that are far away.

+

+ + + + + + + + + + +
+ Figure 1. Endpoints, Switches, and Links + +
+
+
+

+

On the network, we have to solve various difficult problems, such as addressing, routing, and transport. For each node, it has a name and thus is addressable by the routing protocol. And between any two reachable nodes, they exchange packets, each of which is some data with a header (information for packet delivery, especially the source and destination). +Switches have queues in case more packets arrive than it can handle. If the queue is full when a new packet arrives, the packet is to be dropped.

+

To mitigate complexity, A layered model called TCP/IP Model was presented, with 4 layers:

+

+ + + + + + + + + + +
+ Figure 2. Four Layers of TCP/IP Model + +
+
+
+

+
    +
  • Application Layer: acutal traffic generation
  • +
  • Transport Layer: sharing the network, efficiency, reliability
  • +
  • Network Layer: naming, addressing, routing
  • +
  • Link Layer: communicates between two directly-connected nodes.
  • +
+

Not every node in the network has the whole four layers. Some nodes in the network, such as our laptops, have full 4 layers; while others like routers, only have Link Layer and Network Layer.

+

Routing

+

Firstly, we need to distinguish two concepts: path and route.

+
    +
  • Path: the full path the packets will travel
  • +
  • Route: only the first hop of that path
  • +
+

So, routing means that, in the Network Layer, for every node, its routing table should contain a minimum-cost route to every other reachable node after running routing protocol.

+
    +
  • Differentiate between route and path:
  • +
  • Once a routing table is set up, when a switch gets a packet, it can check the packet header for the destination address, and add the packet to the queue for that outgoing link.
  • +
+

Routing protocols can be divided into two categories: distributed routing protocols and the centralized routing protocols. And distributed routing protocols scale better than the centralized ones. There are two types of distributed routing protocols for an IP network:

+
    +
  • Link-State (LS) Routing, like OSPF, forwards link costs to neighbors via advertisement, and uses Dijkstra algorithm to calculate the full shortest path. (Fast convergence, but high overhead due to flooding. Good for middle-sized network, but not scale up to the Internet)
  • +
  • Distance-Vector (DV) Routing, like RIP, it only advertises to the nodes that each node knows about. (Low overhead, but convergence time is proportional to longest path. Good for small networks, but not scale up to the Internet.)
  • +
+

Scale and Policy

+

In this section, we talk about a routing protocol that can scale up to the Internet with policy routing: Border Gateway Protocol (BGP) .

+

First thing we need to do is scale. The whole Internet is divided into several autonomous systems (AS), e.g., a university, an ISP, etc. To route across the Internet, the scalable routing is introduced, with 3 types:

+
    +
  • hierarchy of routing: first between ASes, then within AS.
  • +
  • path-vector routing: like BGP, advertise the path to better detect loop.
  • +
  • topological addressing: CIDR, to make advertisement smaller.
  • +
+

Next thing we need to do is policy. We use export policies and import policies to reflect two common autonomous-system relationships:

+
    +
  • Transit: customer pays provider
  • +
  • Peer: two ASes agree to share routing tables at no cost.
  • +
+

The export policies decide which routes to advertise, and to whom:

+
    +
  • A provider wants its customers to send and receive as much traffic through the provider as possible
  • +
  • Peers only tell each other about their customers (A peer does not tell each other about its own providers; because it will lose money providing that transit)
  • +
+

+ + + + + + + + + + +
+ Figure 3. Autonomous Systems + +
+
+
+

+

Note: there is a path from AS7 to AS1, but this policy just does not present it to us. To fix this issue in the real world, we make all top-tier(tier-1) ISPs peer, to provide global connectivity:

+

+ + + + + + + + + + +
+ Figure 4. Internet of ASes + +
+
+
+

+

The import policies decide which route to use. If the AS hears about multiple routes to a destination, it will prefer to use: first its customers, then peers, then providers.

+

And finally, let's talk about BGP. BGP works at the Application Layer, and it runs on top of a reliable transport protocol called TCP (Transport Layer). BGP doesn’t have to do periodic advertisements to handle failure, instead, it pushs advertisements to neighbors when routes change.

+

Failures: Routes can be explicitly withdrawn in BGP when they fail. Routing loops avoided because BGP is path-vector.

+

Does the BGP scale? Yes, but the following 4 factors will cause scaling issues: the size of routing table, route instability, multihoming, iBGP(internal BGP).

+

Is BGP secure? No, BGP basically relies on the honor system. And also, BGP relies on human, meaning network outages may happen due to human errors.

+

Reliable Transport

+

In this section, we talk about how to do reliable transport while keeping things efficient and fair.

+

First, the reliable transport protocol is a protocol that delivers each byte of data exactly once, in-order, to the receiving application. And we use the sliding-window protocol to guarantee reliability.

+
    +
  1. Sender uses sequence numbers to order and send the packets. There are main two steps on how it works.
  2. +
  3. Receiver replies acknowledgment(ACK) to sender if a packet is received successfully. Otherwise, a timeout is to be detected, the sender then retransmits the corresponding packet.
  4. +
+

Now that a packet will be delivered reliably, next we need to do congestion control.

+

+ + + + + + + + + + +
+ Figure 5. Congested Network + +
+
+
+

+

Our goal for network is efficiency and fairness. Considering both A and B are sending data to R1, and R1 is forwarding to R2, so the bottleneck link is the link between R1 and R2. When the bottleneck link is "full", we call the network is fully utilized (efficient). When A and B are sending at the same rate, we call the network is fair.

+

+ + + + + + + + + + +
+ Figure 6. AIMD Algorithm + +
+
+
+

+

The red line(A + B = bandwidth) is the efficiency line, and the blue line(A = B) is the fairness line. Initially, the dot is below the red line, meaning network is underutilized. And eventually, A and B will come to oscillate around the fixed point, shown as purple point, which means the network is both efficient and fair.

+

We use slow-start, AIMD (Additive Increase Multiplicative Decrease), and fast retransmit/fast recovery algorithms to dynamically adjust the window size to deal with congestion. At the start of the connection, slow-start algorithm will double the windows size on every RTT. Upon reaching the threshold, the AIDM algorithm will increase the congestion window (cwnd) by one segment per RTT, and decrease cwnd by half upon detecting timeout. However, if a single packet is lost, fast retransmit/fast recovery algorithm will send three duplicate ACKs to the receiver before RTO expires.

+

In-network Resource Management

+

In this section, we talk about how to react to congestion before it happens.

+

Queues are transient (not persistent) buffers and are used to absorb packet bursts. If the queues were to be full, the network delay would have been very long. So, TCP senders need to drop packets before the queues are full.

+

+ + + + + + + + + + +
+ Figure 7. Form of In-network Resource Management + +
+
+
+

+

Application Layer

+

In this section, we talk about how to deliver content on the Internet.

+

There are three models on how we sharing a file (deliver content) on the Internet: Client-Server, CDN(Content Distribution Network), and P2P(Peer to Peer).

+

+ + + + + + + + + + +
+ Figure 8. Client-Server, CDN and P2P + +
+
+
+

+
    +
  • Client-Server: if client request a file, the server will just respond with the file content. (simple, but, single-node failure and not scalable)
  • +
  • CDN: to prevent single-node failure, we add more servers that are linked with persistent TCP, and thus every time a client requests, the DNS dynamically choose the nearest CDN server to respond. (requires coordination among the edge servers)
  • +
  • P2P: to improve scalability, a client will discover peers and exchange blocks of data. (scalability is limited by end-users' upload constraints)
  • +
+
+ + +
+
+
* This blog was last updated on 2023-05-30 18:10
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2023/06/docker/index.html b/2023/06/docker/index.html new file mode 100644 index 0000000..95f9a99 --- /dev/null +++ b/2023/06/docker/index.html @@ -0,0 +1,878 @@ + + + + +Docker | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

Docker

+ + +

Docker is a platform for developing, shipping, and deploying applications quickly in portable, self-sufficient containers, and is used in the Continuous Deployment (CD) stage of the DevOps ecosystem.

+

INSTALLATION

+

Environment: CentOS 7 Minimal on VMware Player 17

+
1$ yun update
+2$ yum install -y \
+3    yum-utils \
+4    device-mapper-persistent-data \
+5    lvm2
+6$ yum-config-manager \
+7    --add-repo https://download.docker.com/linux/centos/docker-ce.repo
+8$ yum install -y docker-ce
+9$ docker -v
+

DOCKER COMMANDS

+

DAEMON

+

Daemon is a special process of Docker, +To start/stop/restart Docker, or to get the status of Docker:

+
1$ systemctl start    docker
+2$ systemctl stop     docker
+3$ systemctl restart  docker
+4$ systemctl status   docker 
+

To enable autostart:

+
1$ systemctl enable   docker
+

IMAGE

+

List Images

+

To list local images, type:

+
1$ docker images
+

and it will return a table like:

+ + + + + + + + + + + + + + + + + + + +
REPOSITORYTAGIMAGE IDCREATEDSIZE
+

Note:

+
    +
  • REPOSITORY: the software or service name
  • +
  • TAG: version number
  • +
+

If we just need Docker Image ID, we can add a parameter -q

+
1$ docker images -q
+

Search Images

+
1$ docker search redis
+

and it will return a table like:

+ + + + + + + + + + + + + + + + + + + +
NAMEDESCRIPTIONSTARSOFFICIALAUTOMATED
redisRedis is an open source key-value store that…12156[OK]
+

Note: OFFICIAL is [OK] meaning that this image is maintained by Redis team.

+

Pull Images

+

If we want to pull Redis, we just type:

+
1$ docker pull redis
+

And the latest Redis (i.e., TAG "redis:latest") will be pulled into local machine. However, if we want to pull Redis 5.0, open Docker Hub to verify if it is available, and then:

+
1$ docker pull redis:5.0
+

Remove Images

+

to remove a Docker Image (called redis:5.0 or Image ID is c5da061a611a), we can type any one of them:

+
1$ docker rmi redis:5.0
+2$ docker rmi c5da061a611a
+

Trick: +If we want to remove all the images, we can use:

+
1$ docker rmi `docker images -q`
+

CONTAINER

+

A Container is built out of Docker Image.

+

Container Status and Inspection

+

The status for a container can be UP or Exited.

+
1$ docker ps       # List all the running container
+2$ docker ps --all # List all the history container(s)
+3$ docker ps -a    # Also List all the history container(s)
+

Or, we can inspect a container for more details:

+
1$ docker inspect CONTAINER_NAME
+

Create Container

+

To create a docker container out of an image, we will first pull image centos:7 from remote repository:

+
1$ docker pull centos:7
+
    +
  1. Interactive Container: create docker image container with centos:7, and then enter the container. These three docker run commands are equivalent:
  2. +
+
1$ docker run --interactive --tty --name=test_container centos:7 /bin/bash
+2$ docker run -i -t --name=test_container centos:7 /bin/bash
+3$ docker run -it --name=test_container centos:7 /bin/bash
+

Note:

+
    +
  • --interactive or -i: keeps STDIN open even if not attached
  • +
  • --tty or -t: allocates a pseudo-TTY
  • +
  • --name=test_container: assigns a name "test_container" to this container
  • +
  • centos:7: this container is built on the image called 'centos:7'
  • +
  • /bin/bash: docker will run /bin/bash of container.
  • +
  • the terminal identidy will switch from root@localhost to root@9b7d0441909b, meaning the container (9b7d0441909b) is now started.
  • +
+
    +
  1. Detached Container: Detached Container will not be executed once created, and will not be terminated after $ exit. These three commands are equivalent:
  2. +
+
1$ docker run --interactive --detach --name=test_container2 centos:7
+2$ docker run -i -d --name=test_container2 centos:7
+3$ docker run -id --name=test_container2 centos:7
+

Enter Container

+

In the last section, we created a container but not enter into it, and we can enter by these 3 equivalent docker exec commands:

+
1$ docker exec --interactive --tty test_container2 /bin/bash
+2$ docker exec -i -t test_container2 /bin/bash
+3$ docker exec -it test_container2 /bin/bash
+

Stop or Start Container

+
1$ docker stop CONTAINER_NAME
+2$ docker start CONTAINER_NAME
+

where CONTAINER_NAME is set accordingly by command $ docker ps --all.

+

Remove Container

+
1$ docker rm CONTAINER_NAME
+

Note:

+
    +
  • An UP-status docker container cannot be removed, we have to bring it to Exited before removal
  • +
  • Note the difference between the removal of image and container: to remove image, we type: docker rmi, and to remove container, we type: docker rm.
  • +
+

VOLUMES

+

Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.

+

Volume Mapping

+

To persist data, we can use volume to map the folders. These two commands are equivalent:

+
 1$ docker run -it \
+ 2    --name=testVol1 \
+ 3    --volume ~/data1:/root/container_data1 \
+ 4    --volume ~/data2:/root/container_data2 \
+ 5     centos:7 \
+ 6     /bin/bash
+ 7
+ 8$ docker run -it \
+ 9    --name=testVol1 \
+10    -v ~/data1:/root/container_data1 \
+11    -v ~/data2:/root/container_data2 \
+12     centos:7 \
+13     /bin/bash
+

Note:

+
    +
  • --volume or -v: map the folder to the container with synchronization. Outside container, we use folders ~/data1/ and ~/data2/; Inside container, we use /root/container_data1 and /root/container_data2
  • +
  • we can only explicitlly use the path /root/* (not ~/*) inside container
  • +
+

Volume Container

+

We first create a container called c3, and this will be our Volume Container: (Note the parameter -v /Volume)

+
1$ docker run -it \
+2    --name=c3 \
+3    -v /Volume \
+4    centos:7 \
+5    /bin/bash
+

Then, we will create two containers, and mount them onto c3 in two separate SSH sessions:

+
1$ docker run -it --name=c1 \
+2    --volumes-from c3 \
+3    centos:7 /bin/bash
+4$ docker run -it --name=c2 \
+5    --volumes-from c3 \
+6    centos:7 /bin/bash
+

you can use $ docker inspect c3 to find out where where c3 is mounted, and snippet of docker inspect response shown below:

+
 1......
+ 2"Mounts": [
+ 3            {
+ 4                "Type": "volume",
+ 5                "Name": "266**298fb7",
+ 6                "Source": "/var/lib/docker/volumes/266**298fb7/_data",
+ 7                ......
+ 8            }
+ 9            ......
+10]
+11......
+

so, we can see that /var/lib/docker/volumes/266**298fb7/_data outside of container c3 is mapped into /Volume folder in Docker containers c1, c2 and c3.

+

DEPLOYMENT

+

MySQL

+

Deploy MySQL 5.6 into container, and map its port from 3306 (inside container) to port 3307 (outside container).

+

First, we need to pull MySQL 5.6

+
1$ docker search  mysql
+2$ docker pull    mysql:5.6
+

Second, we need to create container:

+
1$ mkdir  ~/mysql
+2$ docker run -id \
+3    -p 3307:3306 \
+4    --name=c_mysql \
+5    -v ~/mysql/conf:/etc/mysql/conf.d \
+6    -v ~/mysql/logs:/logs \
+7    -v ~/mysql/data:/var/lib/mysql \
+8    -e MYSQL_ROOT_PASSWORD=toor \
+9    mysql:5.6
+

Note:

+
    +
  • -p 3307:3306 or --expose 3307:3306: map the port 3307 (outside container) to the container's port 3306.
  • +
  • -e or --env: set the environment variable MYSQL_ROOT_PASSWORD as toor, which is the root password set for MySQL.
  • +
+

Third, we start and enter the container and test it:

+
1$ docker exec -it c_mysql /bin/bash
+2$ mysql -uroot -p toor
+

Fourth, open MySQL with visual tool such as SQLyog Community

+

Tomcat

+

Map the port 8081 (outside container) to port 8080 (inside container):

+
1$ docker search tomcat
+2$ docker pull   tomcat
+3$ mkdir ~/tomcat
+4$ docker run -id \
+5    --name=c_tomcat \
+6    -p 8081:8080 \
+7    -v ~/tomcat:/usr/local/tomcat/webapps \
+8    tomcat
+

Now we can publish Servlet to folder ~/tomcat/ (outside container), and Tomcat inside container will find it in path /usr/local/tomcat/webapps. For demo, I just put a simple HTML ~/tomcat/test/index.html:

+
1$ mkdir ~/tomcat/test
+2$ echo "Hello Tomcat in Container" > ~/tomcat/test/index.html
+

Now that the IP address outside container is 192.168.109.128, I open http://192.168.109.128:8081/test/index.html, and it will display "Hello Tomcat in Container".

+

NGINX

+

First, search and pull NGINX image.

+
1$ docker search nginx
+2$ docker pull   nginx
+3$ mkdir ~/nginx
+4$ mkdir ~/nginx/conf
+

Second, Copy the nginx.conf at /etc/conf/nginx.conf (inside contanier), and paste into ~/nginx/conf/nginx.conf (inside container):

+
user  nginx;
+worker_processes  auto;
+
+error_log  /var/log/nginx/error.log notice;
+pid        /var/run/nginx.pid;
+
+
+events {
+    worker_connections  1024;
+}
+
+
+http {
+    include       /etc/nginx/mime.types;
+    default_type  application/octet-stream;
+
+    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
+                      '$status $body_bytes_sent "$http_referer" '
+                      '"$http_user_agent" "$http_x_forwarded_for"';
+
+    access_log  /var/log/nginx/access.log  main;
+
+    sendfile        on;
+    #tcp_nopush     on;
+
+    keepalive_timeout  65;
+
+    #gzip  on;
+
+    include /etc/nginx/conf.d/*.conf;
+}
+

Third, start container:

+
1$ docker run -id \
+2    --name=c_nginx \
+3    -p 80:80 \
+4    -v ~/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
+5    -v ~/nginx/logs:/var/log/nginx \
+6    -v ~/nginx/html:/usr/share/nginx/html \
+7    nginx
+

Now that the IP address outside container is 192.168.109.128, I open http://192.168.109.128:80, and it will display "Hello NGINX in Container".

+

Redis

+
1$ docker search redis
+2$ docker pull   redis:5.0
+3$ docker run -id \
+4    --name=c_redis \
+5    -p 6379:6379 \
+6    redis:5.0
+

DOCKERFILE

+

A Dockerfile is a text document that contains all the instructions a user could call on the command line to build an image. And Docker runs instructions in a Dockerfile in order.

+

Examples

+

Deploy Spring Boot

+

Frist, prepare the Spring Boot project. In this case, we will @RequestMapping("/helloworld") to print "Hello World" on http://localhost:8080/hello.

+

Second, pack the project to single *.jar file. In tab Maven Projects - <Your Spring Boot Project Name> - Lifecycle - package, and test *.jar file with: (the complete path is shown in Console))

+
1$ java -jar /path/to/springboot-hello.jar
+

Third, upload to CentOS 7 with SFTP command:

+
1sftp> PUT /path/to/springboot-hello.jar
+

And springboot-hello.jar will be uploaded as springboot-hello.jar (outside container). Later this file will be moved into ~/springboot-docker/springboot-hello.jar (also outside container).

+

Fourth, write springboot_dockerfile in path ~/springboot-docker/ (outside container):

+
1# 1. Require Parent Docker Image: `java:8`
+2FROM java:8
+3
+4# 2. Add `springboot-hello.jar` into container as `app.jar`
+5ADD springboot-hello.jar app.jar
+6
+7# 3. command to execute Spring Boot app
+8CMD java -jar app.jar
+

Fifth, build the Docker;

+
1$ docker build \
+2    --file ./springboot_dockerfile \
+3    --tag  springboot-hello-app \
+4    ~/springboot-docker
+

Note:

+
    +
  • --file or -f: specifies the Dockerfile named springboot_dockerfile.
  • +
  • --tag or -t: tags the image as springboot-hello-app
  • +
+

Sixth, start the image springboot-hello-app

+
1$ docker run -id -p 9090:8080 springboot-hello-app
+

Now that the IP address outside container is 192.168.109.128, we can display the Spring Boot app at http://192.168.109.128:9090/hello

+

Tailored CentOS

+

In path ~/tailored_centos/, create Dockerfile called centos_tailored_dockerfile:

+
 1# 1. Specify the parent Docker Image: `centos:7`
+ 2FROM  centos:7
+ 3
+ 4# 2. Specify the software to be installed
+ 5RUN   yum install -y  tomcat
+ 6
+ 7# 3. Change to directory
+ 8WORKDIR /usr/local/tomcat/webapps
+ 9
+10# 4. Set command to be executed
+11CMD  /bin/bash
+12
+13# 5. Expose port
+14EXPOSE 8080/tcp
+15EXPOSE 8080/udp
+16##  this also can be done with shell:
+17##   $ docker run \
+18##       -p 8080:8080/tcp \
+19##       -p 8080:8080/udp \
+20##       <the rest parameters...>
+

Then we will build the docker:

+
1$ docker build \
+2    -f ./centos_tailored_dockerfile \
+3    -t  tailored_centos:1
+4    ~/tailored_centos
+

Next, we will run the container out of the docker image:

+
1$ docker run -it \
+2    --name=c_tailored_centos \
+3    tailored_centos:1
+

Syntax

+

Syntax of Dockerfile:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameDescription
FROMspecifies the Parent Image from which you are building
RUNexecute commands in a new layer on top of the current image and commit the results
CMDsets the command to be executed when running the image.
LABELadds metadata (key-value pairs) to a docker image
EXPOSEinforms Docker that the container listens on the specified network ports at runtime (tcp by default)
ENVsets the environment variable
ADDcopies new files, directories or remote file URLs from <src> and adds them to the filesystem of the image at the path <dest>
COPYcopies new files or directories from <src> and adds them to the filesystem of the container at the path <dest>
ENTRYPOINTallows you to configure a container that will run as an executable
VOLUMEcreates a mount point and marks it as holding externally mounted volumes from native host or other containers
USERsets the user name (UID) and optionally the user group (GID) to use as the default user and group for the remainder of the current stage
WORKDIRsets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile
ARGdefines a variable that users can pass at build-time to the builder with the $ docker build command
ONBUILDadds to the image a trigger instruction to be executed at a later time, when the image is used as the base for another build
STOPSIGNALsets the system call signal that will be sent to the container to exit
HEALTHCHECKtells Docker how to test a container to check that it is still working
SHELLallows the default shell used for the shell form of commands to be overridden
+
+ + +
+
+
* This blog was last updated on 2023-06-17 23:10
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2023/06/maven/index.html b/2023/06/maven/index.html new file mode 100644 index 0000000..63f33bd --- /dev/null +++ b/2023/06/maven/index.html @@ -0,0 +1,684 @@ + + + + +Maven | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

Maven

+ + +

Maven is a project management tool that is based on POM (project object model). It is used for projects build, dependency and documentation.

+

This blog is built on Windows 10 (x64-based):

+
    +
  • Maven: 3.8.7
  • +
  • JDK 1.8
  • +
+

CONFIGURATION

+

settings.xml

+

In C:\Program Files\Java\apache-maven-3.8.7\conf\settings.xml:

+
    +
  1. to make C:\maven-repo a local Maven Repository, add the following to C:\Program Files\Java\apache-maven-3.8.7\conf\settings.xml:
  2. +
+
1<localRepository>C:\maven-repo</localRepository>
+
    +
  1. JDK Version +C:\Program Files\Java\apache-maven-3.8.7\conf\settings.xml:
  2. +
+
 1<profile>
+ 2    <id>jdk-1.8</id>
+ 3    <activation>
+ 4        <activeByDefault>true</activeByDefault>
+ 5        <jdk>1.8</jdk>
+ 6    </activation>
+ 7    <properties>
+ 8        <maven.compiler.source>1.8</maven.compiler.source>
+ 9        <maven.compiler.target>1.8</maven.compiler.target>
+10        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
+11    </properties>
+12</profile>
+

Environment Variables

+

First, check the version of current Java compiler by:

+
1$ java -version
+

Second, add JDK-related environment variables:

+
    +
  • set/new JAVA_HOME to C:\Program Files\Java\jdk1.8.0_231
  • +
  • append %JAVA_HONE%\bin to %PATH%
  • +
  • set/new JAVA_TOOL_OPTIONS to -Dfile.encoding=UTF-8
  • +
+

Third, add Maven-related environment variables:

+
    +
  • set/new MAVEN_HOME to C:\Program Files\Java\apache-maven-3.8.7
  • +
  • set/new M2_HOME to %MAVEN_HOME%
  • +
  • append %MAVEN_HOME%\bin to %PATH%
  • +
  • set/new MAVEN_OPTS to -Xms256m -Xmx512m -Dfile.encoding=UTF-8
  • +
+

Fourth, open a new termianal and test Maven with command:

+
1$ mvn --version
+

BEGINNER PRACTICE

+

Maven uses 3 vectors to locate a *.jar package:

+
    +
  • groupId: company/organization domain name in reverse order
  • +
  • artifactId: project name, or module name in a project
  • +
  • version: SNAPSHOT or RELEASE
  • +
+

Quick and Simple

+

In this section, I will create a quick and simple Maven Java project, which will serve as a template in the late project.

+

Considering my Blog address is https://mighten.github.io, and this is a learning practice for Maven, so my group id will be io.github.mighten.learn-maven, and artifact id will be maven-java.

+
1$ mkdir  C:\maven-workspace\learn-maven
+2$ cd C:\maven-workspace\learn-maven
+3
+4$ mvn  archetype:generate
+

Note:

+
    +
  • Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 7: (Press Enter to confirm default value)
  • +
  • Define value for property 'groupId': io.github.mighten.learn-maven
  • +
  • Define value for property 'artifactId': maven-java
  • +
  • Define value for property 'version' 1.0-SNAPSHOT: : (Press Enter to confirm default value)
  • +
  • Define value for property 'package' io.github.mighten.learn-maven: : (Press Enter to confirm default value)
  • +
  • Y: : (Press Enter to confirm default value)
  • +
+

And the BUILD SUCCESS is shown.

+

Change Dependencies

+

First, in path learn-maven/maven-jave/src, delete the default Java files:

+
    +
  • src/main/java/io/github/mighten/learn-maven/App.java
  • +
  • src/test/java/io/github/mighten/learn-maven/AppTest.java
  • +
+

Second, modify the version of JUnit (in learn-maven/maven-jave/pom.xml) from 3.8.1 to 4.12

+

MAVEN COMMANDS

+

change working directory to the directory of the current pom.xml.

+
    +
  1. clean
  2. +
+
1$ mvn clean
+

delete the target folder

+
    +
  1. compile the main
  2. +
+
1$ mvn compile
+

target file in target/classes

+
    +
  1. test
  2. +
+
1$ mvn test-compile
+2$ mvn test
+

target file in target/test-classes

+
    +
  1. pack to *.jar
  2. +
+
1$ mvn package
+
    +
  1. install into local Maven Repository
  2. +
+
1$ mvn install
+

Trick:

+
1$ mvn clean install
+

DEPENDENCY MANAGEMENT

+

Dependency management is a core feature of Maven.

+

Scope

+

Scope is used to define the dependencies of a project, e.g., JUnit in pom.xml has <scope>test</scope>:

+
1<dependency>
+2    <groupId>junit</groupId>
+3    <artifactId>junit</artifactId>
+4    <version>4.12</version>
+5    <scope>test</scope>
+6</dependency>
+

And we should notice:

+
    +
  • compile (default scope): used for both the compilation and the runtime of the project. But the Compile Scope does not use the classes in Test Scope
  • +
  • test: used for testing, but not required for the runtime
  • +
  • provided: used for dependencies that are part of the Java EE or other container environments. But the Provided Scope will not be packed into *.jar.
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Scope Name/main/testDevelopDeploy
compilevalidvalidvalidvalid
testN/AvalidvalidN/A
providedvalidvalidvalidN/A
+

These scopes help manage the classpath and control which dependencies are included at different stages of the build process.

+

Propagation

+

In the Maven tree, if the dependency of a child is compile-scope, then it can propagate to the parent; otherwise, if dependency of a child is test-scope or provided-scope, then it can not propagate to the parent.

+

For example, if I write a project_1.jar, which adds a dependency to JUnit with test scope. Then I create project_2 which uses a dependency to project_1.jar. The JUnit dependency will not be available for project_2 because JUnit is in test scope; if I want to use JUnit in project_2, I have to explicitly declare JUnit in pom.xml of project_2.

+

In addition, Maven can create an ASCII-styled dependency-tree graph, with the following command:

+
1$ mvn dependency:tree
+

Exclusion

+

Dependency Exclusions are used to fix *.jar confrontations.

+

For example, if I create a project_3 will add dependencies on project_1.jar (uses package A version 1.1) and project_2.jar (uses package A version 1.6), then certainly the package A will have confrontation with two version. To fix this issue, we usually choose the higher version (1.6) and exclude the lower version 1.1. So I will exclude package A in dependency of project_1.jar (in pom.xml of project_3):

+
 1<dependency>
+ 2	<groupId>io.github.mighten.learn_maven</groupId>
+ 3	<artifactId>project_1</artifactId>
+ 4	<version>1.0-SNAPSHOT</version>
+ 5	<scope>compile</scope>
+ 6
+ 7	<exclusions>
+ 8		<!-- 
+ 9            to exclude package `A`, 
+10            (no need to specify version)
+11        -->
+12		<exclusion>
+13			<groupId>A</groupId>
+14			<artifactId>A</artifactId>
+15		</exclusion>
+16
+17        <!-- 
+18            to exclude other packages 
+19        <exclusion>
+20            <groupId></groupId>
+21            <artifactId></artifactId>
+22        </exclusion>
+23        -->
+24	</exclusions>
+25</dependency>
+

Inheritance

+

Dependency Inheritance allows child POM to inherit dependency from a parent POM. It is typically used to prevent version confrontations. In pom.xml of parent project:

+
    +
  1. +

    set parent project parent to pack into POM file <packaging>pom</packaging>, which will allow the parent to manage all the child projects.

    +
  2. +
  3. +

    add tag <dependencyManagement> in pom.xml of parent, to manage all the dependencies:

    +
  4. +
+
 1<dependencyManagement>
+ 2	<dependencies>
+ 3		<dependency>
+ 4			<groupId>org.springframework</groupId>
+ 5			<artifactId>spring-core</artifactId>
+ 6			<version>4.0.0.RELEASE</version>
+ 7		</dependency>
+ 8        <!-- other dependencies -->
+ 9	</dependencies>
+10</dependencyManagement>
+

Note: the packages are not really import into the parent project

+
    +
  1. add tag <parent> to pom.xml of every children:
  2. +
+
1<parent>
+2	<groupId>com.atguigu.maven</groupId>
+3	<artifactId>pro03-maven-parent</artifactId>
+4	<version>1.0-SNAPSHOT</version>
+5</parent>
+
    +
  1. add dependencies into children pom.xml, and since the version is declared in parental pom.xml, the version in the children pom.xml can be omitted.
  2. +
+

Aggregation

+

If we want to aggregate all of the children projects into one, we can config in parent.xml (similar to inheritance):

+
1<modules>  
+2    <module>child_1</module>
+3    <module>child_2</module>
+4    <module>child_3</module>
+5</modules>
+

Note: DO NOT use cyclic reference.

+
+ + +
+
+
* This blog was last updated on 2023-06-21 00:00
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2023/06/mit-6.033-cse-distributed-systems/index.html b/2023/06/mit-6.033-cse-distributed-systems/index.html new file mode 100644 index 0000000..3a79e4e --- /dev/null +++ b/2023/06/mit-6.033-cse-distributed-systems/index.html @@ -0,0 +1,744 @@ + + + + +MIT 6.033 CSE Distributed Systems | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

MIT 6.033 CSE Distributed Systems

+ + +

MIT 6.033 (Computer System Engineering) covers 4 parts: Operating Systems, Networking, Distributed Systems, and Security.

+

This is the course note for Part III: Distributed Systems. And in this section, we mainly focus on: How reliable, usable distributed systems are able to be built on top of an unreliable network.

+

Reliability via Replication

+

In this section, we talk about how to achieve reliability via replication, especially RAID(Redundant Array of Independent Disks) that tolerates disk faults. And we assume that the entire machine could fail.

+

Generally, there are 3 steps to build reliable systems:

+
    +
  1. identify all possible faults
  2. +
  3. detect and contain the faults
  4. +
  5. handle faults ("recover")
  6. +
+

To quantify the reliability, we use availability: +$$ Availability = \frac{MTTF}{MTTF+MTTR} \tag{1.1}$$ +where MTTF (Mean Time To Failure) is the average time between non-repairable failures, and MTTR (Mean Time To Recovery) is the average time it takes to repair a system.

+

RAID replicates data across disks so that it can tolerate disk failures.

+
    +
  • RAID-1: mirrors a single disk, +but requires $2n$ disks.
  • +
  • RAID-4: has a dedicated parity disk, requires $n+1$ disks, but all writes go to the parity disk ("bottleneck").
  • +
  • RAID-5: spreads out the parity (stripes a single file across multiple disks), spreads out the write requests (better performance), requires $n+1$ disks.
  • +
+

Single-Machine Transactions

+

In this section, we talk about abstractions to make fault-tolerance achievable: transactions. And we assume that the entire machine works fine, but some operations may fail.

+

Transactions provide atomicity and isolation - make the reasoning about failures (and concurrency) easier.

+

Atomicity

+

Atomicity refers to an action either happens completely or does not happen at all.

+

For one user and one file, we implement atomicity by shadow copies (write to a temporary file, and then rename it to bank_file, for example), but they perform poorly.

+

We keep logs in cell storage on disk to record operations, so that uncommitted operations before crash can be reverted. There are two kinds of records: UPDATE and COMMIT:

+
    +
  • UPDATE records have the old and new values
  • +
  • COMMIT records indicate that a transaction has been commited.
  • +
+

To speed up the recovery process, we write checkpoints and truncate the log.

+

Isolation via 2PL

+

In this section, we use Two-Phase Locking (2PL) to run transactions ($T_1, T_2, ..., T_n$) concurrently, but to produce a schedule that is conflict serializable.

+

Isolation refers to how and when the effects of one action (A1) are visible to another (A2). As a result, A1 and A2 appear to have executed serially, even though they are actually executed in parallel.

+

Two operations are conflict if they operate on the same object and at least one of them is a write. A schedule is conflict serializable if the order of all its conflicts is the same as the order of the conflicts in sequential schedule.

+

We use conflict graph to express the order of conflicts succinctly, so a schedule is conflict-serializable $\Leftrightarrow$ it has an acyclic conflict graph. E.g., consider the following schedule:

+
1T1: read(x)
+2T2: write(x)
+3T1: write(x)
+4T3: write(x)
+

Explanation: Start from $T1$ reading x, we find $T2$ and $T3$ want to write to x. And then $T2$ is writing to x, we find $T1$ and $T3$ want to wirte to x. And then $T1$ is writing to x, we find $T3$ want to write to x.

+
---
+title: Figure 1. Conflict Graph
+---
+graph LR
+	T1 --> T2
+	T1 --> T3
+	T2 --> T1
+	T2 --> T3
+

So, the conflict graph has cycle, so this schedule is not conflict-serializable.

+

Two-Phase Locking (2PL) is a concurrency control protocol used in database management systems (DBMS) to ensure the serializability of transactions. It consists of two distinct phases: the growing phase (transaction acquires locks and increases its hold on resources) and the shrinking phase (transaction releases all the locks and reduces its hold on resources).

+

A valid Two-Phase Locking schedule has the following rules:

+
    +
  1. each shared variable has a lock
  2. +
  3. before any operation on a variable, the transaction must acquire the corresponding lock
  4. +
  5. after a transaction releases a lock, it may not acquire any other lock
  6. +
+

However, 2PL can result in deadlock. Normal solution is to global ordering on locks. But a more elegant solution is to take advantage of the atomicity (of transactions) and abort one of the transactions.

+

If we want better performance, we use the 2PL with reader/writer locks:

+
    +
  1. each variable has two locks: one for reading, one for writing
  2. +
  3. before any operation on a variable, the transaction must acquire the appropriate lock.
  4. +
  5. multiple transaction can hold reader locks for the same variable at once; a transaction can only hold a writer lock for a variable if there are no other locks held for that variable.
  6. +
  7. after a transaction releases a lock, it may not acquire any other lock.
  8. +
+

Distributed Transactions

+

When it comes to the distributed systems, the transactions are different.

+

Multisite Atomicity via 2PC

+

In this section, we use Two-Phase Commit (2PC) to get multisite atomicity, in the face of failures.

+

Two-Phase Commit (2PC) is a distributed transaction protocol to ensure the consistency of transactions across multiple nodes. 2PC consists of 2 phases:

+
    +
  • Prepare Phase: Coordinator uses Prepare message to check if participants are ready to finish this transaction.
  • +
  • Commit Phase: Coordinator sends a Commit request to participants, waits for their OK response, and informs the client of the committed transaction.
  • +
+
sequenceDiagram
+    title: Figure 2. Two-Phase Commit (no failure)
+	participant CL as Client
+	participant CO as Coordinator
+	participant AM as A-M Server
+	participant NZ as N-Z Server
+
+	CL->>CO: Commit Request
+	CO->>AM: Prepare
+    AM-->>CO: 
+	CO->>NZ: Prepare
+	NZ-->>CO: 
+	CO-->>CL: OK
+	CO->>AM: Commit
+    AM-->>CO: 
+	CO->>NZ: Commit
+	NZ-->>CO: 
+    CO-->>CL: OK
+

However, 3 types of failures may happen:

+
    +
  1. +

    Message Loss(at any stage) or Message Reordering: solved by reliable transport protocol, such as TCP (with sequence number and ACKs).

    +
  2. +
  3. +

    Failures before commit point that can be aborted:

    +
      +
    • Worker Failure BEFORE Prepare Phase: coordinator can saftly abort the transaction without additional communication to workers. (coordinator uses HELLO to detect failure of workers)
    • +
    +
  4. +
+
sequenceDiagram
+    title: Figure 3. Worker Failure BEFORE Prepare Phase
+	participant CL as Client
+	participant CO as Coordinator
+	participant A-M Server
+	participant N-Z Server
+    CL->>CO: Commit Request
+	CO-->>CL: Abort
+
    +
  • Worker Failure or Coordinator Failure DURING Prepare Phase: coordinator can saftly abort the transaction, will send explicit abort message to live workers.
  • +
+
sequenceDiagram
+    title: Figure 4. Worker Fails DURING Prepare Phase
+	participant CL as Client
+	participant CO as Coordinator
+	participant AM as A-M Server
+	participant NZ as N-Z Server
+
+	CL->>CO: Commit Request
+	CO->>AM: Prepare
+	AM-->>CO: 
+	CO->>NZ: Prepare
+	Note over NZ: worker fails
+	CO->>AM: Abort
+    AM-->>CO: 
+    CO-->>CL: Abort
+
sequenceDiagram
+    title: Figure 5. Coordinator Fails DURING Prepare Phase
+	participant CL as Client
+	participant CO as Coordinator
+	participant AM as A-M Server
+	participant NZ as N-Z Server
+
+	CL->>CO: Commit Request
+	CO->>AM: Prepare
+	AM-->>CO: 
+    Note over CO: coordinator fails and recovers
+	CO->>AM: Abort
+    AM-->>CO: 
+    CO->>NZ: Abort
+    NZ-->>CO: 
+    CO-->>CL: Abort
+
    +
  1. Worker Failure or Coordinator Failure during Commit Phase (after commit point): coordinator cannot abort the transaction; machines must commit the transaction during recovery.
  2. +
+
sequenceDiagram
+    title: Figure 6. Worker Fails during Commit Phase
+	participant CL as Client
+	participant CO as Coordinator
+	participant AM as A-M Server
+	participant NZ as N-Z Server
+
+	CL->>CO: Commit Request
+	CO->>AM: Prepare
+    AM-->>CO: 
+	CO->>NZ: Prepare
+	NZ-->>CO: 
+	CO-->>CL: OK
+	CO->>AM: Commit
+    AM-->>CO:  
+	CO->>NZ: Commit
+	Note over NZ: worker fails and recovers
+    NZ-->>CO: should I commit?
+    CO->>NZ: Commit
+    NZ-->>CO: 
+    CO-->>CL: OK
+
+
sequenceDiagram
+    title: Figure 7. Coordinator Fails during Commit Phase
+	participant CL as Client
+	participant CO as Coordinator
+	participant AM as A-M Server
+	participant NZ as N-Z Server
+
+	CL->>CO: Commit Request
+	CO->>AM: Prepare
+    AM-->>CO: 
+	CO->>NZ: Prepare
+	NZ-->>CO: 
+	CO-->>CL: OK
+	CO->>AM: Commit
+    AM-->>CO:  
+    Note over CO: coordinator fails and recovers
+    CO->>AM: Commit
+    AM-->>CO:  
+    CO->>NZ: Commit
+    NZ-->>CO: 
+    CO-->>CL: OK
+

Replicate State Machines

+

In this section, we replicate on multiple machines, so that the availability is increased.

+

Replicate State Machines (RSM) use primary/backup mechanism for replication:

+

+ + + + + + + + + + +
+ Figure 8. Replicate State Machine + +
+
+
+

+
    +
  • Coordinators make requests to View Server, to find out which replica is primary, and contact the primary.
  • +
  • View Server ensures that only one replica acts as primary, and can recruit new backups if servers fail. It keeps a table that maintains a sequence of views, and receives pings from primary and backups.
  • +
  • Primary pings View Server, and gets contacts from coordinator, and then sends updates to backups. Primary must get an ACK from its backups before completing the update.
  • +
  • Backups ping View Server, and receive update requests from primary. (Note: Backups will reject any requests that they get directly from Coordinator)
  • +
+
+ + +
+
+
* This blog was last updated on 2023-06-06 22:10
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2023/06/mit-6.033-cse-security/index.html b/2023/06/mit-6.033-cse-security/index.html new file mode 100644 index 0000000..91285ad --- /dev/null +++ b/2023/06/mit-6.033-cse-security/index.html @@ -0,0 +1,599 @@ + + + + +MIT 6.033 CSE Security | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

MIT 6.033 CSE Security

+ + +

MIT 6.033 (Computer System Engineering) covers 4 parts: Operating Systems, Networking, Distributed Systems, and Security.

+

This is the course note for Part IV: Security. And in this section, we mainly focus on common pitfalls in the security of computer systems, and how to combat them.

+

To build a secure system, we need to be clear about two aspects:

+
    +
  1. security policy (goal)
  2. +
  3. threat model (assumptions on adversaries)
  4. +
+

Authentication

+

In this section, we authenticate users through username and password.

+
    +
  • Security Policy: provide authentication for users
  • +
  • Threat Model: adversary has access to the entire stored username-password table and get password.
  • +
+

One solution is to use hash functions $H$, which take an input string of arbitary size and output a fixed-length string:

+
    +
  • $H$ is deterministic: if $x_1 = x_2$, then $H(x_1) = H(x_2)$
  • +
  • $H$ is collision-resistant: if $x_1 \neq x_2$, then the probability of $H(x_1)=H(x_2)$ is virtually $0$.
  • +
  • $H$ is one-way: given $x$, it is easy to compute $H(x)$; given $H(x)$ without knowing $x$, it is virtually impossible to determine $x$.
  • +
+

But the adversary can still use Rainbow Table to precompute hashes to determine password. This issue can be mitigated by slow hash functions with salt (a random info stored in plaintext), making it infeasible to determine password, especially without knowing salt.

+

Another solution is to limit transmission of passwords, because transmitting password frequently opens a user up to other attacks outside our current threat model.

+
    +
  • Session Cookies allow users to authenticate themselves for a period of time, without repeatedly transmitting their passwords.
  • +
+
sequenceDiagram
+    title: Figure 1. Session Cookies
+    actor User
+    participant Server
+
+    User->>+Server: username/password
+    Server-->>-User: cookie
+    User->>Server: cookie
+
    +
  • Challenge-Response Protocols authenticate users without ever transmitting passwords.
  • +
+
sequenceDiagram
+    title: Figure 2. Challenge-Response Protocols
+    actor User
+    participant Server
+
+    Server->>User: 658427(random number)
+    User-->>Server: H(password | 658427)
+

However, there are always trade-offs, many other measures do add security, but often add complexity and decrease usability.

+

Low-Level Exploits

+

In this section, our threat model is that the adversary has the ability to run code on that machine, and the goal of adversary is to input a string that overwrites the saved instruction pointer so that the code jumps to the target function to open a shell.

+

There is no perfect solution for this issue. Modern Linux has protections(NX, ASLR, etc.) to prevent attacks, but there are also some counter-attacks(return-to-libc, heap-smashing, pointer-subterfuge, etc.) to those protections. And Bound-checking is also a solution, but it ruins the ability to generate compact C code.(Note the trade-offs of security vs. performance)

+

The Ken Thompson Hack (in essay Reflections on Trusting Trust, Thompson hacked compiler, so that it will bring backdoors to UNIX system and all subsequent versions of the C compiler) tells us that, to some extents, we cannot trust the code we didn't write ourselves. It also advocates policy-based solutions, rather than technology-based.

+

Secure Channels

+

Secure Channels protect packet data from an adversary observing data on the network.

+
    +
  • Security Policy: to provide confidentiality (adversary cannot learn message contents) and integrity (adversary cannot tamper with packets and go undetected).
  • +
  • Threat Model: adversary can observe and tamper with packet data.
  • +
+
sequenceDiagram
+    title: Figure 3. TLS handshake
+    participant Client
+    participant Server
+
+    Client->>Server: ClientHello
+    Server-->>Client: ServerHello
+    Server-->>Client: {Server Certificate, CA Certificates}
+    Server-->>Client: ServerHelloDone
+    Note over Client: Verifies authenticity of server
+    Client->>Server: ClientKeyExchange
+    Note over Server: computes keys
+    Client->>Server: Finished
+    Server-->>Client: Finished
+

Encrypting with symmetric keys provides secrecy, and using Message Authentication Code (MAC) provides integrity. Diffie-Hellman key exchange lets us exchange the symmetric key securely. (The reason we use symmetric key to encrypt/decrypt data is that it is faster.)

+

To verify identities, we use public-key cryptography and cryptographic signatures. We often distribute public keys with certificate authorities (CA).

+

Note that the secure channel alone only provides confidentiality and integrity of packet data, but not for packet header.

+

Tor

+

Tor provides some level of anonymity for users, preventing an adversary from linking senders and receivers.

+
    +
  • Security Policy: provide anonymity (only the client should know that it is communicating with the server)
  • +
  • Threat Model: packet header exposes to the adversary that is A is communicating with B.
  • +
+

However, there are still ways to attack Tor, e.g., correlating traffic analysis from various points in the network.

+

DDoS

+

Distributed Denial of Service (DDoS) is a type of cyber attack that prevents legitimate access to the Internet.

+
    +
  • Security Policy: maintain availability of the service.
  • +
  • Threat Model: adversary controlls a botnet (large collection of compromised machines), and prevents access to a legitimate service via DDoS attacks.
  • +
+

Network-Intrusion Detection Systems (NIDS) may help to mitigate DDoS attacks, but are not perfect, because DDoS attacks are sophisticated and can miminc legitimate traffic.

+
+ + +
+
+
* This blog was last updated on 2023-06-13 09:00
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2023/06/putty-with-openssh/index.html b/2023/06/putty-with-openssh/index.html new file mode 100644 index 0000000..5f9a0a1 --- /dev/null +++ b/2023/06/putty-with-openssh/index.html @@ -0,0 +1,501 @@ + + + + +PuTTY with OpenSSH | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

PuTTY with OpenSSH

+ + +

Hi!

+

Today we use OpenSSH and PuTTY to log in remote computers.

+
    +
  • OpenSSH is an open-source version of the Secure Shell (SSH) tools used by administrators of remote systems
  • +
  • PuTTY is a free implementation of SSH
  • +
+

This blog is built on the following environment:

+
    +
  • Host Machine: OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2, and PuTTY Release 0.78 on Windows 10 x64.
  • +
  • Virtual Machine (Server): CentOS 7 Minimal on VMware Player 17 (Intel-VT Virtualization: ON)
  • +
+

Generate Key Pair

+

SSH requires public/private key pair. The public key is stored on server to authenticate the user who has the corresponding private key. For simplicity, I will use PuTTY to generate public/private key pair:

+
    +
  1. Open PUTTYGEN.EXE of PuTTY installation directory.
  2. +
  3. Click "Generate" to generate public/private key pair
  4. +
  5. Set Key passphase and Confirm the passphase.
  6. +
  7. Click "Save private key", and export to a putty_private_key.ppk file
  8. +
  9. Copy the content of "Public key for pasting into OpenSSH authorized_keys file" (begin with ssh-rsa ...), and paste it in server file (~/.ssh/authorized_keys of CentOS 7).
  10. +
  11. Open PUTTY.EXE of PuTTY installation directory
  12. +
  13. In the left menu, unfold category to find Connection/SSH/Auth/Credentials, and "Browse" to find putty_private_key.ppk
  14. +
  15. In the left menu, click Session, type in the IP address and "Save" this session with a name, like "CentOS7_VM"
  16. +
+

Config Server

+

If we want to log in without password, we will config the server:

+
    +
  1. (Optional) Allow SSH login as root: (find the following item and change its property in /etc/ssh/sshd_config to yes) +
    1PermitRootLogin yes
    +
  2. +
  3. Ensure the Public key authentication is enabled: (find the following items and change their properties in /etc/ssh/sshd_config to yes) +
    1RSAAuthentication yes
    +2PubkeyAuthentication yes
    +
  4. +
  5. Restrict to use the authorized public keys only: (to disallow password, find the following item and change its property in /etc/ssh/sshd_config to no) +
    1PasswordAuthentication no
    +
  6. +
  7. Restart SSH service to validate changes: (in terminal) +
    1$ service sshd restart
    +
  8. +
+

Connect

+

Open PUTTY.EXE, "Load" the saved session called CentOS7_VM, and "Open"

+
1login as: <Your User Name>
+2Authenticating with public key "rsa-key-YYYYMMDD"
+3Passphrase for key "rsa-key-YYYYMMDD": <Your Passphrase For private key>
+

So now we can log in with no passwords in transmission.

+

However, if you do not want to protect the private key (putty_private_key.ppk) with passphrase at all, you can load your private key with PUTTYGEN.EXE and then override the private key with no passphrase. (Highly unrecommended)

+
+ + +
+
+
* This blog was last updated on 2023-06-17 22:08
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2023/07/spring-framework/index.html b/2023/07/spring-framework/index.html new file mode 100644 index 0000000..7d379dc --- /dev/null +++ b/2023/07/spring-framework/index.html @@ -0,0 +1,2333 @@ + + + + +Spring Framework | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

Spring Framework

+ + +

Hi there!

+

In this blog, we talk about Spring Framework, a Java platform that provides comprehensive infrastructure support for developing Java applications. The content of this blog is shown below:

+
    +
  • Architecture
  • +
  • Spring IoC Container
  • +
  • Spring Beans
  • +
  • Dependency Injection (DI)
  • +
  • Spring Annotations
  • +
  • Aspect Oriented Programming (AOP)
  • +
+

1. ARCHITECTURE

+

The Spring Framework provides about 20 modules which can be used based on an application requirement.

+

+ + + + + + + + + + +
+ Figure 1. Spring Framework Architecture + +
+
+
+

+

Test layer supports the testing of Spring components with JUnit or TestNG frameworks.

+

Core Container layer consists of the Core, Beans, Context, and Spring Expression Language (SpEL) modules:

+
    +
  • Core provides the fundamental parts of the framework, including the Inversion of Control (IoC) and Dependency Injection (DI).
  • +
  • Bean provides BeanFactory, an implementation of the factory pattern.
  • +
  • Context is a medium to access any objects defined and configured, e.g., the ApplicationContext interface.
  • +
  • SpEL provides Spring Expression Language for querying and manipulating an object graph at runtime.
  • +
+

AOP layer provides an aspect-oriented programming implementation, allowing you to define method-interceptors and pointcuts to decouple the code.

+

Aspects layer provides integration with AspectJ, an AOP framework.

+

Instrumentation layer provides class instrumentation support and class loader implementations.

+

Messaging layer provides support for STOMP as the WebSocket sub-protocol.

+

Data Access/Integration layer consists of JDBC, ORM, OXM, JMS and Transaction:

+
    +
  • JDBC provides a JDBC-abstraction layer to simplify JDBC related coding.
  • +
  • ORM provides integration layers for object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
  • +
  • OXM provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
  • +
  • Java Messaging Service (JMS) produces and consumes messages.
  • +
  • Transaction supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs.
  • +
+

Web layer consists of the Web, MVC, WebSocket, and Portlet:

+
    +
  • MVC provides Model-View-Controller (MVC) implementation for Spring web applications.
  • +
  • WebSocket provides support for WebSocket-based, two-way communication between the client and the server in web applications.
  • +
  • Web provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context.
  • +
  • Portlet provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module.
  • +
+

2. IOC CONTAINER

+

Inversion of Control (IoC) is a design principle where the control of flow and dependencies in a program are inverted, meaning that the control is handed over to a container or framework which can manage dependencies (instead of allowing component to control its dependencies).

+

Dependency refers to an object that a class relies on to perform its functionality. Dependency Injection (DI) is a specific implementation of the IoC principle. DI injects the dependencies from outside the class (rather than having the class create them itself). Instead of hardcoding within the class, the dependencies are injected into it from an external source, usually a container or framework.

+

In Spring Framework, there are two types of IoC containers: BeanFactory and ApplicationContext. The ApplicationContext container includes all functionality of the BeanFactory container and thus is better; while BeanFactory is mostly used for lightweight applications where data volume and speed is significant.

+

2.1 BeanFactory

+

BeanFactory is the simplest container providing the basic support for DI. BeanFactory is defined by the org.springframework.beans.factory.BeanFactory interface.

+

Code 1-1 shows how to use BeanFactory:

+

Code 1-1(a). "Message.java"

+
 1package com.example;
+ 2
+ 3public class Message { 
+ 4   private String message;  
+ 5   
+ 6   public void setMessage(String message){ 
+ 7      this.message  = message; 
+ 8   }  
+ 9   public void getMessage(){ 
+10      System.out.println("Message : " + message); 
+11   } 
+12}
+

Code 1-1(a) declares a class named Message, and it has a pair of getter/setter for class member named message.

+

Code 1-1(b). "Beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <bean id = "demo" class = "com.example.Message">
+ 9      <property name = "message" value = "Hello World!"/>
+10   </bean>
+11
+12</beans>
+

Code 1-1(b) is a XML configuration file tell that a bean called demo is defined, and its message is set to "Hello World!".

+

Code 1-1(c). "BeanFactoryDemoTest.java"

+
 1package com.example;
+ 2
+ 3import org.springframework.beans.factory.xml.XmlBeanFactory; 
+ 4import org.springframework.core.io.ClassPathResource;  
+ 5
+ 6public class BeanFactoryDemoTest { 
+ 7   public static void main(String[] args) { 
+ 8      XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml")); 
+ 9      Message obj = (Message) factory.getBean("demo");    
+10      obj.getMessage();    
+11   }
+12}   
+

Code 1-1(c) is a test program, and it uses ClassPathResource() API to load the bean configuration file, and it uses XmlBeanFactory() to create and initialize beans in the configuration file "Beans.xml".

+

Then, getBean() method uses bean ID ("demo") to return a generic object, which finally can be casted to the BeanFactoryDemo object. By invoking obj.getMessage(), the code 1-1(a) is executed, and shows:

+
1Message : Hello World!
+

Summary: this section uses Code 1-1(a, b, c) to show how to get bean by using BeanFactory.

+

2.2 ApplicationContext

+

ApplicationContext is similar to BeanFactory, but it adds enterprise-specific functionality.

+

ApplicationContext is defined by the org.springframework.context.ApplicationContext interface, with several implementations: FileSystemXmlApplicationContext, ClassPathXmlApplicationContext, and WebXmlApplicationContext.

+
    +
  • FileSystemXmlApplicationContext loads the definitions of the beans, from the XML bean configuration file (full path to file) to the constructor.
  • +
  • ClassPathXmlApplicationContext loads the definitions of the beans from an XML file, and we need to set CLASSPATH.
  • +
  • WebXmlApplicationContext loads the XML file with definitions of all beans from within a web application.
  • +
+

Code 2-1, with Code 1-1(a, b), will show how to use FileSystemXmlApplicationContext of ApplicationContext:

+

Code 2-1. "FileSystemXmlApplicationContextDemoTest.java"

+
 1package com.example;
+ 2
+ 3import org.springframework.context.ApplicationContext;
+ 4import org.springframework.context.support.FileSystemXmlApplicationContext;
+ 5
+ 6public class FileSystemXmlApplicationContextDemoTest {
+ 7   public static void main(String[] args) {
+ 8      ApplicationContext context = new FileSystemXmlApplicationContext
+ 9         ("C:/path/to/Beans.xml");
+10
+11      Message obj = (Message) context.getBean("demo");
+12      obj.getMessage();
+13   }
+14}
+

Now we will reuse the codes defined in Code 1-1(a, b), and run the Code 2-1:

+
1Message : Hello World!
+

Summary: this section uses Code 1-1(a, b), Code 2-1 to show how to get bean by using ApplicationContext, especially the FileSystemXmlApplicationContext.

+

3. BEAN

+

Bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Bean definition contains the information called configuration metadata:

+

Table 3-1. Properties of Bean

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertiesDescription
idthe bean identifier(unique)
classthe bean class to create the bean
scopethe scope of the objects created
constructor-argto inject the dependencies
propertiesto inject the dependencies
autowiringto inject the dependencies
lazy-initlet IoC container to create a bean instance at first requested
init-methodexecuted after properties set by the container
destroy-methodexecuted when the container is destroyed
+

3.1 Scope

+

The scope of a bean defines the life cycle and visibility of that bean in the contexts we use it (singleton, prototype, request, session, global-session). In pratice, we mainly use singleton, prototype:

+

singleton: Spring IoC container creates exactly one instance of the object defined by that bean definition. Shown in Code 3-1, if we execute getBean("demo") multiple times, the object will always be the same one.

+

Code 3-1. Snippet of "bean.xml"

+
1<bean id = "demo" 
+2      class = "com.example.Message"
+3      scope = "singleton">
+4</bean>
+

prototype: Spring IoC container creates a new bean instance of the object every time a request for that specific bean is made. Shown in Code 3-2, if we execute getBean("demo") multiple times, there will be corresponsing multiple quite different objects.

+

Code 3-2. Snippet of "bean.xml"

+
1<bean id = "demo" 
+2      class = "com.example.Message"
+3      scope = "prototype">
+4</bean>
+

3.2 Life Cycle

+

Bean life cycle is managed by the Spring container. The spring container gets started before creating the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed.

+

Code 3-3(a). "LifeCycleDemo.java"

+
 1package com.example;
+ 2
+ 3public class LifeCycleDemo {
+ 4   public void init() {
+ 5      System.out.println("Bean initialized.");
+ 6   }
+ 7
+ 8   public void foo() {
+ 9      System.out.println("foo");
+10   }
+11
+12   public void destroy() {
+13      System.out.println("Bean destroyed.");
+14   }
+15}
+

In Code 3-3(a), a straightforward class named LifeCycleDemo is defined, comprising three methods: init(), foo(), and destroy(). Each of these methods prints out status information to indicate its current stage.

+

Code 3-3(b). "beans.java"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <bean id = "life_cycle_demo"
+ 9         class = "com.example.LifeCycleDemo"
+10         init-method = "init" 
+11         destroy-method = "destroy">
+12   </bean>
+13
+14</beans>
+

In Code 3-3(b), it defines a bean named "life_cycle_demo" of the class "com.example.LifeCycleDemo" with initialization(init) and destruction (destroy) methods.

+

Code 3-3(c). "LifeCycleDemoTest.java"

+
 1package com.example;
+ 2
+ 3import org.springframework.context.support.AbstractApplicationContext;
+ 4import org.springframework.context.support.ClassPathXmlApplicationContext;
+ 5
+ 6public class LifeCycleDemoTest {
+ 7   public static void main(String[] args) {
+ 8      AbstractApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
+ 9
+10      LifeCycleDemo obj = (LifeCycleDemo) context.getBean("life_cycle_demo");
+11      obj.foo();
+12      context.registerShutdownHook(); // display destroy info (registers a shutdown hook for the Spring application context)
+13   }
+14}
+

In Code 3-3(c), it demonstrates how to use the Spring Framework to initialize the Spring container, retrieve a bean from the container, and invoke a method on the bean. Additionally, it ensures that the Spring context is properly closed when the application exits by registering a shutdown hook.

+

When the Code 3-3(a, b, c) are executed, the following results should appear in the console:

+
1Bean initialized.
+2foo
+3Bean destroyed.
+

3.3 Postprocessors

+

BeanPostProcessor is an interface defined in org.springframework.beans.factory.config.BeanPostProcessor, and it allows for custom modification of new bean instance.

+

Code 3-4 shows how to use Postprocessor.

+

Code 3-4(a). "PostprocessorDemo.java"

+
 1package com.example;
+ 2
+ 3public class PostprocessorDemo {
+ 4   public void init(){
+ 5      System.out.println("init");
+ 6   }
+ 7
+ 8   public void foo() {
+ 9      System.out.println("foo...");
+10   }
+11
+12   public void destroy(){
+13      System.out.println("destroy");
+14   }
+15}
+

In Code 3-4(a), just like Code 3-3(a), a straightforward class named PostprocessorDemo is defined, comprising three methods: init(), foo(), and destroy(). Each of these methods prints out status information to indicate its current stage.

+

Code 3-4(b). "InitPostprocessorDemo.java"

+
 1package com.example;
+ 2
+ 3import org.springframework.beans.factory.config.BeanPostProcessor;
+ 4import org.springframework.beans.BeansException;
+ 5
+ 6public class InitPostprocessorDemo implements BeanPostProcessor {
+ 7   public Object postProcessBeforeInitialization(Object bean, String beanName) 
+ 8      throws BeansException {
+ 9      
+10      System.out.println("Before init of " + beanName);
+11      return bean;
+12   }
+13   public Object postProcessAfterInitialization(Object bean, String beanName) 
+14      throws BeansException {
+15      
+16      System.out.println("After init of " + beanName);
+17      return bean; 
+18   }
+19}
+

Code 3-4(b) is an example of implementing BeanPostProcessor, which prints a bean name before and after initialization of a bean. Note: the return type of postProcessBeforeInitialization and postProcessAfterInitialization is quite arbitrary, so they do not require bean as return values.

+

Code 3-4(c). "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <bean id = "demo" 
+ 9         class = "com.example.PostprocessorDemo"
+10         init-method = "init"
+11         destroy-method = "destroy" />
+12
+13   <bean class = "com.example.InitPostprocessorDemo" />
+14
+15</beans>
+

Code 3-4(c) defines two beans. The first bean with the ID "demo" associates itself with the class "com.example.PostprocessorDemo", and it specifies an initialization method called "init" as well as a destruction method called "destroy"; the second bean serves as a custom post-processor for "demo" in the Spring Application Context.

+

Code 3-4(d). "PostprocessorDemoTest.java"

+
 1package com.example;
+ 2
+ 3import org.springframework.context.support.AbstractApplicationContext;
+ 4import org.springframework.context.support.ClassPathXmlApplicationContext;
+ 5
+ 6public class PostprocessorDemoTest {
+ 7   public static void main(String[] args) {
+ 8      AbstractApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
+ 9
+10      PostprocessorDemo obj = (PostprocessorDemo) context.getBean("demo");
+11      obj.foo();
+12      context.registerShutdownHook();
+13   }
+14}
+

Code 3-4(d) demonstrates the usage of a Spring Framework postprocessor. It only load the bean with ID "demo" but not the Postprocessor class. And The expected output of Code 3-4 should be:

+
1Before init of demo
+2init
+3After init of demo
+4foo...
+5destroy
+

3.4 Definition Inheritance

+

Spring supports bean definition inheritance to promote reusability and minimize development effort.

+

Code 3-5 shows the basic usage of Bean definition inheritance:

+

Code 3-5(a). "Hello.java"

+
 1package com.example;
+ 2
+ 3public class Hello {
+ 4   private String name;
+ 5   private String type;
+ 6
+ 7   public void setName(String name){
+ 8      this.name = name;
+ 9   }
+10   public void setType(String type){
+11      this.type = type;
+12   }
+13   public void sayHello(){
+14      System.out.println("Hello " + name + ", type = " + type);
+15   }
+16}
+

Code 3-5(a) shows a basic class called Hello, and Hello has two private instance variables, name and type, along with corresponding setter methods setName and setType to set their values. Additionally, the class contains a method sayHello() that prints a greeting message with the name and type values.

+

Code 3-5(b). "HelloStudent.java"

+
 1package com.example;
+ 2
+ 3public class HelloStudent {
+ 4   private String name;
+ 5   private String type;
+ 6   private String school;
+ 7
+ 8   public void setName(String name) {
+ 9      this.name = name;
+10   }
+11
+12   public void setType(String type) {
+13      this.type = type;
+14   }
+15
+16   public void setSchool(String school) {
+17      this.school = school;
+18   }
+19
+20   public void sayHello(){
+21      System.out.println("Hello " + name + ", type = " + type + ", from " + school);
+22   }
+23}
+

Code 3-5(b) introduces a new class called HelloStudent which extends the functionality of the previous Hello class by adding an additional private instance variable, school, and a corresponding setter method setSchool() to set its value. With this extension, the HelloStudent class now represents a student entity with a name, a type, and the school they attend.

+

Code 3-5(c). "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <bean id = "hello" class = "com.example.Hello">
+ 9      <property name = "name" value = "Tom"/>
+10      <property name = "type" value = "student"/>
+11   </bean>
+12
+13   <bean id ="helloStudent" class = "com.example.HelloStudent" parent = "hello">
+14      <property name = "name" value = "Jerry"/>
+15      <property name = "school" value = "MIT"/>
+16   </bean>
+17</beans>
+

Code 3-5(c) sets up two beans, hello and helloStudent, and helloStudent inherits bean definition from its parent called hello. Note the parent="hello" attribute in the "helloStudent" bean definition: This attribute indicates that "helloStudent" is a child bean of "hello," and it will inherit the properties defined in the "hello" bean (i.e., type is set to student).

+

Code 3-5(d). "HelloInheritanceTest.java"

+
 1package com.example;
+ 2
+ 3import org.springframework.context.ApplicationContext;
+ 4import org.springframework.context.support.ClassPathXmlApplicationContext;
+ 5
+ 6public class HelloInheritanceTest {
+ 7   public static void main(String[] args) {
+ 8      ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
+ 9      
+10      Hello tom = (Hello) context.getBean("hello");
+11      tom.sayHello();
+12
+13      HelloStudent jerry = (HelloStudent) context.getBean("helloStudent");
+14      jerry.sayHello();
+15   }
+16}
+

Code 3-5(d) demonstrates how to incorporate beans hello and helloStudent. And the expected output for Code 3-5 should be:

+
1Hello Tom, type = student
+2Hello Jerry, type = student, from MIT
+

4. DI

+

Dependency injection (DI) is a pattern we can use to implement IoC. When writing a complex Java application, DI helps in gluing these classes together and keeping them independent at the same time.

+

There are two major variants for DI: Constructor-based DI, and Setter-based DI. It is recommended to use constructor arguments for mandatory dependencies and setters for optional dependencies.

+

In this section, we use two simple examples to show how DI works, and Code 4-1(a, b) are the generic parts for these two examples:

+

Code 4-1(a). "MessageService.java"

+
1package com.example.di;
+2
+3public interface MessageService {
+4    String getMessage();
+5}
+

Code 4-1(a) defines an interface MessageService that declares a method getMessage().

+

Code 4-1(b). "MessageServiceTest.java"

+
 1package com.example.di;
+ 2
+ 3import org.springframework.context.ApplicationContext;
+ 4import org.springframework.context.support.ClassPathXmlApplicationContext;
+ 5
+ 6public class MessageServiceTest {
+ 7    public static void main(String[] args) {
+ 8        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
+ 9        MessageService messageService = (MessageService) context.getBean("messageService");
+10        String message = messageService.getMessage();
+11        System.out.println("Message: " + message);
+12    }
+13}
+

Code 4-1(b) creates a class named MessageServiceTest that will load the Spring application context and retrieve the MessageService bean.

+

4.1 Constructor-based DI

+

Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments (each representing a dependency on the other class).

+

Code 4-1(a, b) and Code 4-2(a, b) demonstrate how to use Constructor-based DI:

+

Code 4-2(a). "MessageServiceImplConstructorBased.java"

+
 1package com.example.di;
+ 2
+ 3public class MessageServiceImplConstructorBased implements MessageService {
+ 4    private String message;
+ 5
+ 6    // Constructor for DI
+ 7    public MessageServiceImplConstructorBased(String message) {
+ 8        this.message = message;
+ 9    }
+10
+11    @Override
+12    public String getMessage() {
+13        return message;
+14    }
+15}
+

Code 4-2(a) defines the implementation of the MessageService interface as MessageServiceImplConstructorBased.

+

Code 4-2(b). "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <bean id="messageService" class="com.example.di.MessageServiceImplConstructorBased">
+ 9      <constructor-arg value="Hello, this is a constructor-based DI example!" />
+10   </bean>
+11
+12</beans>
+

Code 4-2(b) defines a bean with the ID "messageService" and specifies the class com.example.di.MessageServiceImplConstructorBased. It also provides a constructor argument (value = "Hello, this is a constructor-based DI example!") for DI. This argument will be passed to the constructor of MessageServiceImplConstructorBased when the bean is created.

+

The expected output for Code 4-1(a, b) and Code 4-2(a, b) is:

+
1Message: Hello, this is a constructor-based DI example!
+

Now, let's dig it deeper. If we want to pass multiple objects into a constructor:

+

Code 4-2-extend(a). "Foo.java"

+
 1package  com.example.di;
+ 2
+ 3public class Foo {
+ 4   private int  id;
+ 5   private String name;
+ 6   private Bar bar;
+ 7   private Baz baz;
+ 8
+ 9   //Constructor for DI
+10   public Foo(int id, String name, Bar bar, Baz baz) {
+11        this.id = id;
+12        this.name = name;
+13        this.bar = bar;
+14        this.baz = baz;
+15    }
+16
+17   public show() {
+18      // ...
+19   }
+20}
+

Code 4-2-extend(a) shows a more complex example of Constructor-based DI. Assuming the Bar and Baz classes in the package com.example.di, we will initialize Foo object with a four-parameter (id, name, bar, and baz) constructor.

+

Code 4-2-extend(b). "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <!-- Define the bean for the Bar and Baz -->
+ 9   <bean id="bar" class="com.example.di.Bar" />
+10   <bean id="baz" class="com.example.di.Baz" />
+11
+12   <!-- Define the bean for the Foo class with constructor-based Dependency Injection -->
+13   <bean id="foo" class="com.example.di.Foo">
+14       <constructor-arg value="1001" />  <!-- id -->
+15       <constructor-arg value="Tommy" /> <!-- name -->
+16       <constructor-arg ref="bar" />     <!-- bar -->
+17       <constructor-arg ref="baz" />     <!-- baz -->
+18   </bean>
+19
+20</beans>
+

Code 4-2-extend(b) shows how to pass different parameters into constructor. For simple types like int and String, use value; for complex types like Bar and Baz, define the separate beans and then use ref.

+

Code 4-2-extend(c). "FooTest.java"

+
 1package com.example.di;
+ 2
+ 3import org.springframework.context.ApplicationContext;
+ 4import org.springframework.context.support.ClassPathXmlApplicationContext;
+ 5
+ 6public class FooTest {
+ 7   public static void main(String[] args) {
+ 8      ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
+ 9      Foo foo = (Foo) context.getBean("foo");
+10      foo.show();  
+11   }
+12}
+

So, when passing a reference to an object, use ref attribute of <constructor-arg> tag; when passing a value directly, use value attribute.

+

4.2 Setter-based DI

+

Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

+

Code 4-1(a, b) and Code 4-3(a, b) demonstrate how to use Setter-based DI:

+

Code 4-3(a). "MessageServiceImplSetterBased.java"

+
 1package com.example.di;
+ 2
+ 3public class MessageServiceImplSetterBased implements MessageService {
+ 4    private String message;
+ 5
+ 6    // Setter for DI
+ 7    public void setMessage(String message) {
+ 8        this.message = message;
+ 9    }
+10
+11    @Override
+12    public String getMessage() {
+13        return message;
+14    }
+15}
+

Code 4-3(a) defines the implementation of the MessageService interface using Setter setMessage() to pass values into bean.

+

Code 4-3(b). "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <bean id="messageService" class="com.example.di.MessageServiceImplSetterBased">
+ 9      <property name="message" value="Hello, this is a setter-based DI example!" />
+10   </bean>
+11
+12</beans>
+

Code 4-3(b) provides a <property> element with the name "message" and the value "Hello, this is a setter-based DI example!".

+

The expected output for Code 4-1(a, b) and Code 4-3(a, b) is:

+
1Message: Hello, this is a setter-based DI example!
+

Now, let's dig it deeper. If we want to use multiple setters:

+

Code 4-3-extend(a). "Foo.java"

+
 1package  com.example.di;
+ 2
+ 3public class Foo {
+ 4   private int  id;
+ 5   private String name;
+ 6   private Bar bar;
+ 7   private Baz baz;
+ 8
+ 9   // Setters for DI
+10   public void setId(int id) {
+11        this.id = id;
+12   }
+13
+14   public void setName(String name) {
+15        this.name = name;
+16   }
+17
+18   public void setBar(Bar bar) {
+19       this.bar = bar;
+20   }
+21
+22   public void setBaz(Baz baz) {
+23       this.baz = baz;
+24   }
+25
+26   // other methods ...
+27   public void show() {
+28       // ...
+29   }
+30}
+

Code 4-3-extend(a) shows a more complex example of Constructor-based DI. Assuming the Bar and Baz classes in the package com.example.di, we will initialize Foo object with four setters (setId(), setName(), setBar(), and setBaz()).

+

Code 4-3-extend(b). "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <!-- Define the bean for the Bar and Baz -->
+ 9   <bean id="bar" class="com.example.di.Bar" />
+10   <bean id="baz" class="com.example.di.Baz" />
+11
+12   <!-- Define the bean for the Foo class with setter-based Dependency Injection -->
+13   <bean id="foo" class="com.example.di.Foo">
+14      <property name="id" value="1001" />
+15      <property name="name" value="Tommy" />
+16      <property name="bar" ref="bar" />
+17      <property name="baz" ref="baz" />
+18   </bean>
+19
+20</beans>
+

Code 4-3-extend(b) shows how to pass different parameters into setters. For simple types like int and String, use value; for complex types like Bar and Baz, define the separate beans and then use ref.

+

Code 4-3-extend(c). "FooTest.java"

+
 1package com.example.di;
+ 2
+ 3import org.springframework.context.ApplicationContext;
+ 4import org.springframework.context.support.ClassPathXmlApplicationContext;
+ 5
+ 6public class FooTest {
+ 7   public static void main(String[] args) {
+ 8      ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
+ 9      Foo foo = context.getBean("foo", Foo.class);
+10      foo.show();  
+11   }
+12}
+

In Setter-based DI, the Spring container will call the appropriate setter methods on the Foo instance after creating it, injecting the Bar and Baz dependencies into the Foo object foo.

+

4.3 Injecting Collection

+

Injecting collections refers to the process of providing a collection of objects (array, list, set, map, or properties) to a Spring bean during its initialization.

+

Code 4-4(a). "CollectionInjection.java"

+
 1package com.example.di;
+ 2
+ 3import java.util.List;
+ 4import java.util.Set;
+ 5import java.util.Map;
+ 6import java.util.Properties;
+ 7
+ 8public class CollectionInjection {
+ 9   private int[] array;
+10   private List<String> list;
+11   private Set<String> set;
+12   private Map<String,String> map;
+13   private Properties properties;
+14
+15   // Setters
+16   public void setArray(int[] array) {
+17       this.array = array;
+18   }
+19
+20   public void setList(List<String> list) {
+21       this.list = list;
+22   }
+23
+24   public void setSet(Set<String> set) {
+25       this.set = set;
+26   }
+27
+28   public void setMap(Map<String, String> map) {
+29       this.map = map;
+30   }
+31
+32   public void setProperties(Properties properties) {
+33       this.properties = properties;
+34   }
+35}
+

Code 4-4(a) shows the target class for Collection Injection.

+

Code 4-4(b). "beans.xml"

+
 1<?xml version="1.0" encoding="UTF-8"?>
+ 2<beans xmlns="http://www.springframework.org/schema/beans"
+ 3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ 4       xsi:schemaLocation="http://www.springframework.org/schema/beans
+ 5       http://www.springframework.org/schema/beans/spring-beans.xsd">
+ 6
+ 7    <!-- Define the CollectionInjection bean -->
+ 8    <bean id="collectionInjection" class="com.example.di.CollectionInjection">
+ 9        <!-- Inject an array -->
+10        <property name="array">
+11            <array>
+12                <value>1</value>
+13                <value>2</value>
+14                <value>3</value>
+15            </array>
+16        </property>
+17
+18        <!-- Inject a list -->
+19        <property name="list">
+20            <list>
+21                <value>First element</value>
+22                <value>Second element</value>
+23                <value>Third element</value>
+24            </list>
+25        </property>
+26
+27        <!-- Inject a set -->
+28        <property name="set">
+29            <set>
+30                <value>Set element 1</value>
+31                <value>Set element 2</value>
+32                <value>Set element 3</value>
+33            </set>
+34        </property>
+35
+36        <!-- Inject a map -->
+37        <property name="map">
+38            <map>
+39                <entry key="id" value="404"/>
+40                <entry key="msg" value="Page Not Found"/>
+41            </map>
+42        </property>
+43
+44        <!-- Inject properties -->
+45        <property name="properties">
+46            <props>
+47                <prop key="property1">Property Value 1</prop>
+48                <prop key="property2">Property Value 2</prop>
+49                <prop key="property3">Property Value 3</prop>
+50            </props>
+51        </property>
+52    </bean>
+53</beans>
+

Code 4-4(b) shows how to use XML file to inject array, list, set, map, and properties.

+

4.4 Autowire

+

Autowire is a specific feature of Spring DI that simplifies the process of injecting dependencies by automatically wiring beans together (without explicit configuration).

+

There are five autowiring modes:

+

Table 4-1. Autowiring Modes

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModeDescription
noNo autowiring (default mode)
byNameAutowiring by property name
byTypeAutowiring by property data type, match exactly one
constructorAutowiring by constructor, match exactly one
autodetectfirst autowire by constructor, then autowire by byType
+

Note: to wire arrays and other typed-collections, use byType or constructor autowiring mode.

+

Now we will use the spell checker textEditor.spellCheck() to demonstrate autowiring modes, and partial codes are shown in Code 4-5(a, b, c):

+

Code 4-5(a). "TextEditorTest.java"

+
 1package com.example.di;
+ 2
+ 3import org.springframework.context.ApplicationContext;
+ 4import org.springframework.context.support.ClassPathXmlApplicationContext;
+ 5
+ 6public class TextEditorTest {
+ 7   public static void main(String[] args) {
+ 8      ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
+ 9      TextEditor textEditor = (TextEditor) context.getBean("textEditor");
+10      textEditor.spellCheck();
+11   }
+12}
+

Code 4-5(a) is a test class to demonstrate how various autowire modes work.

+

Code 4-5(b). "SpellChecker.java"

+
1package com.example.di;
+2
+3public class SpellChecker {
+4   public void checkSpelling() {
+5      System.out.println("check Spelling...");
+6   }
+7}
+

Code 4-5(b) defines a class named SpellChecker, which is a simple Java class responsible for checking spellings. The SpellChecker class has a single method called checkSpelling() that prints the message "check Spelling..." to the console.

+

Code 4-5(c). "TextEditor.java"

+
 1package com.example.di;
+ 2
+ 3public class TextEditor {
+ 4   // autowire the `spellChecker` from Spring Container
+ 5   private SpellChecker spellChecker;
+ 6
+ 7   public void setSpellChecker( SpellChecker spellChecker ) {
+ 8      this.spellChecker = spellChecker;
+ 9   }
+10
+11   public SpellChecker getSpellChecker() {
+12      return spellChecker;
+13   }
+14
+15   public void spellCheck() {
+16      spellChecker.checkSpelling();
+17   }
+18}
+

Code 4-5(c) defines a class named TextEditor, which is used to perform spell checking through the use of the SpellChecker defined in Code 4-5(b).

+

With Code 4-5(d, e, or f), the expected output for Code 4-5(a, b, c) should be:

+
1check Spelling...
+

4.4.1 Autowire byName

+

In XML configuration file, Spring container looks at the beans on which autowire attribute is set to byName, Spring container will then look for other beans with names that match the properties of the bean (the bean set to byName-autowiring). If matches are found, Spring will automatically inject those matching beans into the properties of the specified bean; otherwise, the bean's properties will remain unwired.

+

Code 4-5(a, b, c) and Code 4-5(d) demonstrate how autowire byName works:

+

Code 4-5(d) "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <!-- Definition for spellChecker bean -->
+ 9   <bean id = "spellChecker" class = "com.example.di.SpellChecker" />
+10
+11   <!-- Definition for textEditor bean -->
+12   <bean id = "textEditor"
+13         class = "com.example.di.TextEditor"
+14         autowire = "byName" />
+15</beans>
+

In Code 4-5(d), Spring will look for a bean with the name spellChecker in the Spring Container and inject it into spellChecker property of textEditor bean, due to autowire = "byName" on textEditor. And to enable the byName autowiring, TextEditor must have a class member whose type is SpellChecker.

+

4.4.2 Autowire byType

+

In the XML configuration file, when the autowire attribute is set to byType for a particular bean, the Spring container will attempt to find other beans in its context whose types match the property types of the bean being configured.

+

Code 4-5(a, b, c) and Code 4-5(e) demonstrate how autowire byType works:

+

Code 4-5(e). "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <!-- Definition for spellChecker bean -->
+ 9   <bean id = "spellChecker" class = "com.example.di.SpellChecker" />
+10
+11   <!-- Definition for textEditor bean -->
+12   <bean id = "textEditor"
+13         class = "com.example.di.TextEditor"
+14         autowire = "byType" />
+15</beans>
+

In Code 4-5(e), Spring will automatically inject the spellChecker into spellChecker property of textEditor bean, because the SpellChecker class is defined as a Spring bean with the id spellChecker, and it matches the type of the spellChecker property in the TextEditor class.

+

4.4.3 Autowire constructor

+

In the XML configuration file, Spring container looks at the beans on which autowire attribute is set constructor. It then tries to match and wire its constructor's argument with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans; otherwise, bean(s) will remain unwired.

+

Code 4-5(f). "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <!-- Definition for spellChecker bean -->
+ 9   <bean id = "spellChecker" class = "com.example.di.SpellChecker" />
+10
+11   <!-- Definition for textEditor bean -->
+12   <bean id = "textEditor"
+13         class = "com.example.di.TextEditor"
+14         autowire = "constructor" />
+15</beans>
+

5. ANNOTATIONS

+

Annotations are a form of metadata, that applies to the Java classes, methods, or fields, to provide additional information and instructions to the Spring container. Annotations offer a straightforward alternative to XML files for efficient configuration and management of components and their dependencies.

+

5.1 Configuration Annotations

+

Below are some configuration annotations used to configure the Spring container, manage properties, and activate specific profiles.

+

5.1.1 @Bean

+

@Bean indicates that the return value of the annotated method should be registered as a bean in the Spring application context.

+

Code 5-1. Snippet of "Address.java"

+
1  @Bean
+2  public Address getAddress(){
+3    return new Address();
+4  }
+

In Code 5-1, getAddress() is annotated with @Bean, meaning that Spring will register the Address object returned by that method as a bean.

+

5.1.2 @Configuration

+

@Configuration annotation is used to declare a class as a configuration class in Spring.

+

Code 5-2. Snippet of "DataConfig.java"

+
 1@Configuration
+ 2public class DataConfig{ 
+ 3  @Bean
+ 4  public DataSource source(){
+ 5    DataSource source = new OracleDataSource();
+ 6    source.setURL();
+ 7    source.setUser();
+ 8    return source;
+ 9  }
+10}
+

In Code 5-2, @Configuration annotation declares the class DataConfig as a configuration class in Spring.

+

5.1.3 @ComponentScan

+

@ComponentScan annotation is used to enable component scanning in Spring.

+

Code 5-3(a). "AppConfig.java"

+
 1package com.example.annotation;
+ 2
+ 3import org.springframework.context.annotation.ComponentScan;
+ 4import org.springframework.context.annotation.Configuration;
+ 5
+ 6@Configuration
+ 7@ComponentScan(basePackages = "com.example.annotation")
+ 8public class AppConfig {
+ 9
+10}
+

In Code 5-3(a): AppConfig uses @ComponentScan to specify the base package for component scanning. When Spring performs component scanning, it looks for classes annotated with stereotypes like @Component, within the specified package and its sub-packages. Spring will then automatically create Spring beans for these classes and add them to the application context.

+

Code 5-3(b). "HelloService.java"

+
 1package com.example.annotation;
+ 2
+ 3import org.springframework.stereotype.Component;
+ 4
+ 5@Component
+ 6public class HelloService {
+ 7    public void sayHello() {
+ 8        System.out.println("Hello World");
+ 9    }
+10}
+

In Code 5-3(b): HelloService is annotated with @Component, indicating that it is a Spring bean that will be managed by the Spring container.

+

Code 5-3(c). "AppTest.java"

+
 1package com.example.annotation;
+ 2
+ 3import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+ 4
+ 5public class AppTest {
+ 6    public static void main(String[] args) {
+ 7        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
+ 8        HelloService helloService = context.getBean(HelloService.class);
+ 9        helloService.sayHello();
+10        context.close(); // !!! it is important to close the Annotation Config Application Context
+11    }
+12}
+

Code 5-3(c) creates an AnnotationConfigApplicationContext using AppConfig.class as the configuration class, retrieves the HelloService bean from the context, and then calls the sayHello() method.

+

The expected output for Code 5-3(a, b, c) is:

+
1Hello World
+

5.1.4 @PropertySource

+

@PropertySource annotation is used to specify the location of properties files containing configuration settings for the Spring application.

+

Code 5-4(a). "AppConfig.java"

+
 1package com.example.annotation.propertysource;
+ 2
+ 3import org.springframework.context.annotation.Configuration;
+ 4import org.springframework.context.annotation.PropertySource;
+ 5
+ 6@Configuration
+ 7@ComponentScan(basePackages = "com.example.annotation.propertysource")
+ 8@PropertySource("classpath:application.yml")
+ 9public class AppConfig {
+10   
+11}
+

Code 5-4(a) is a Java configuration class, and it specifies that it will define Spring beans and loads properties from the "application.yml" file.

+

Code 5-4(b). "application.yml"

+
1greeting:
+2  message: "Hello, World!"
+

Code 5-4(b) is a YAML file that sets the property "greeting.message" with the value "Hello, World!" for the Spring application.

+

Code 5-4(c). "GreetingService.java"

+
 1package com.example.annotation.propertysource;
+ 2
+ 3import org.springframework.beans.factory.annotation.Value;
+ 4import org.springframework.stereotype.Component;
+ 5
+ 6@Component
+ 7public class GreetingService {
+ 8    @Value("${greeting.message}")
+ 9    private String message;
+10
+11    public void sayGreeting() {
+12        System.out.println(message);
+13    }
+14}
+

Code 5-4(c) is a Spring component class, and it injects the value of the property "greeting.message" into the private field greetingMessage and provides a method to print the greeting message.

+

Code 5-4(d). "AppTest.java"

+
 1import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+ 2
+ 3public class AppTest {
+ 4    public static void main(String[] args) {
+ 5        // Create the application context using AppConfig
+ 6        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
+ 7
+ 8        // Get the GreetingService bean from the context
+ 9        GreetingService greetingService = context.getBean(GreetingService.class);
+10
+11        // Call the sayGreeting() method to print "Hello, World!" on the console
+12        greetingService.sayGreeting();
+13
+14        // Close the context
+15        context.close();
+16    }
+17}
+

The expected output for Code 5-4(a, b, c, d) should be:

+
1Hello, World!
+

5.1.5 @Profile

+

@Profile annotation is used to define specific configurations for different application environments or scenarios.

+

Code 5-5(a). "DatabaseConfig.java"

+
 1package com.example.annotation.profile;
+ 2
+ 3import org.springframework.context.annotation.Bean;
+ 4import org.springframework.context.annotation.Configuration;
+ 5import org.springframework.context.annotation.Profile;
+ 6
+ 7@Configuration
+ 8public class DatabaseConfig {
+ 9
+10    @Bean
+11    @Profile("development")
+12    public DataSource developmentDataSource() {
+13        // Create and configure the H2 data source for development
+14        return new H2DataSource();
+15    }
+16
+17    @Bean
+18    @Profile("production")
+19    public DataSource productionDataSource() {
+20        // Create and configure the MySQL data source for production
+21        return new MySQLDataSource();
+22    }
+23}
+

Code 5-5(b). "DataSource.java"

+
 1package com.example.annotation.profile;
+ 2
+ 3public interface DataSource {
+ 4    // Define common data source methods here
+ 5}
+ 6
+ 7public class H2DataSource implements DataSource {
+ 8    // H2 data source implementation
+ 9}
+10
+11public class MySQLDataSource implements DataSource {
+12    // MySQL data source implementation
+13}
+

Code 5-5(c). "application.yml"

+
1spring:
+2  profiles:
+3    active: development
+

This will activate the @Profile("development") part of DataSource bean.

+

5.1.6 @Import

+

@Import annotation is used to import one or more configuration classes into the current configuration.

+

Code 5-6(a). "AppConfig.java"

+
 1import org.springframework.context.annotation.Bean;
+ 2import org.springframework.context.annotation.Configuration;
+ 3
+ 4@Configuration
+ 5public class AppConfig {
+ 6
+ 7    @Bean
+ 8    public MyBean myBean() {
+ 9        return new MyBean();
+10    }
+11}
+

Code 5-6(b). "AnotherAppConfig.java"

+
1import org.springframework.context.annotation.Configuration;
+2import org.springframework.context.annotation.Import;
+3
+4@Configuration
+5@Import(AppConfig.class)
+6public class AnotherConfig {
+7    // Additional configuration or beans can be defined here
+8}
+9
+

Code 5-6(b) makes all the beans defined in AppConfig (in this case, just MyBean) available in the current application context, when AnotherConfig is used.

+

5.1.7 @ImportResource

+

@ImportResource annotation is used to import XML-based Spring configurations into the current Java-based configuration class.

+

Code 5-7(a). "AppConfig.java"

+
 1package com.example.annotation.config;
+ 2
+ 3import org.springframework.context.annotation.Configuration;
+ 4import org.springframework.context.annotation.ImportResource;
+ 5
+ 6@Configuration
+ 7@ImportResource("classpath:config.xml") // Load the XML configuration file
+ 8public class AppConfig {
+ 9    // Java-based configuration can also be defined here if needed
+10}
+

Code 5-7(a) indicates that it contains Spring bean definitions. It also uses @ImportResource to load the XML configuration file "config.xml."

+

Code 5-7(b). "config.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2
+ 3<beans xmlns = "http://www.springframework.org/schema/beans"
+ 4   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ 7
+ 8   <!-- Define a bean in the XML configuration -->
+ 9   <bean id="messageService" class="com.example.MessageService">
+10      <property name="message" value="Hello, Spring!"/>
+11   </bean>
+12</beans>
+

Code 5-7(c). "MessageService.java"

+
 1package com.example.annotation.config;
+ 2
+ 3public class MessageService {
+ 4    private String message;
+ 5
+ 6    public String getMessage() {
+ 7        return message;
+ 8    }
+ 9
+10    public void setMessage(String message) {
+11        this.message = message;
+12    }
+13}
+

Code 5-7(d). "AppTest.java"

+
 1package com.example.annotation.config;
+ 2
+ 3import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+ 4
+ 5public class Main {
+ 6    public static void main(String[] args) {
+ 7        // Load the Java configuration class
+ 8        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
+ 9
+10        // Get the bean from the Spring context
+11        MessageService messageService = context.getBean("messageService", MessageService.class);
+12
+13        // Use the bean
+14        System.out.println(messageService.getMessage());
+15
+16        // Close the context
+17        context.close();
+18    }
+19}
+

The expected output of running Code 5-7(a, b, c, d) should be:

+
1Hello, Spring!
+

5.2 Bean Annotations

+

Below are some bean annotations that are commonly used in Spring applications:

+

5.2.1 @Component, @Controller, @Repository, @Service

+

These are used to automatically detect and register beans with the Spring container during component scanning.

+
    +
  • @Component indicates that the class is a general-purpose Spring component
  • +
  • @Controller marks the class as a Spring MVC controller
  • +
  • @Repository indicates that the class is a data repository (database operations)
  • +
  • @Servicemarks the class as a service bean dealing with business logic
  • +
+

For the reason of simplicity, I will reuse the Code 5-3(b) as the demo.

+

5.2.2 @Autowired

+

@Autowired annotation is used to automatically inject dependent beans into the target bean.

+

@Autowired can be applied on fields, setter methods, and constructors.

+

Code 5-8. "AutowiredField.java"

+
 1package com.example.autowired.field;
+ 2
+ 3import org.springframework.beans.factory.annotation.Autowired;
+ 4
+ 5public class Customer {
+ 6   @Autowired
+ 7   private Person person;
+ 8
+ 9   // ...
+10}
+

Code 5-8 shows how to use the @Autowired annotation to automatically inject a bean into the person field of Customer class.

+

Code 5-9. "AutowiredSetter.java"

+
 1package com.example.autowired.setter;
+ 2
+ 3import org.springframework.beans.factory.annotation.Autowired;
+ 4
+ 5public class Customer {
+ 6    private Person person;
+ 7
+ 8    @Autowired
+ 9    public void setPerson(Person person) {
+10        this.person = person;
+11    }
+12
+13    // ...
+14}
+

Code 5-9 shows how to use the @Autowired annotation to automatically inject a bean into the setter setPerson() of the Customer class. Spring tries to perform the byType autowiring on the method.

+

Code 5-10. "AutowiredConstructor.java"

+
 1package com.example.autowired.constructor;
+ 2
+ 3import org.springframework.beans.factory.annotation.Autowired;
+ 4
+ 5public class Customer {
+ 6    private Person person;
+ 7
+ 8    @Autowired
+ 9    public Customer(Person person) {
+10        this.person = person;
+11    }
+12
+13    // ...
+14}
+

Code 5-10 shows how to use the @Autowired annotation to automatically inject a bean into the constructor of the Customer class. Note: only one constructor of any bean class can carry the @Autowired annotation.

+

5.2.3 @Qualifier

+

The @Qualifier annotation is used in conjunction with @Autowired to resolve ambiguity when multiple beans of the same type are available for injection.

+

Code 5-11(a). "MessageService.java"

+
 1package com.example.annotation.qualifier;
+ 2
+ 3public interface MessageService {
+ 4   public void  sendMessage();
+ 5}
+ 6
+ 7@Component
+ 8public class MailService implements MessageService {
+ 9   @Override
+10   public void sendMessage() {
+11      System.out.println("Mail sent.");
+12   }
+13}
+14
+15@Component
+16public class SmsService implements MessageService {
+17   @Override
+18   public void sendMessage() {
+19      System.out.println("SMS sent.");
+20   }
+21}
+

Code 5-11(a) defines an interface MessageService, which declares a single method sendMessage(). The interface is then implemented by two classes, MailService and SmsService. These classes provide their own implementations of the sendMessage() method.

+

Code 5-11(b). "App.java"

+
 1package com.example.annotation.qualifier;
+ 2
+ 3import org.springframework.beans.factory.annotation.Autowired;
+ 4import org.springframework.beans.factory.annotation.Qualifier;
+ 5import org.springframework.stereotype.Component;
+ 6
+ 7@Component
+ 8public class App {
+ 9
+10   @Autowired
+11   @Qualifier("mailService")
+12   private MessageService messageService;
+13
+14   public void action() {
+15      messageService.sendMessage();
+16   }
+17}
+

Code 5-11(b) injects mailService into messageService by @Qualifier annotation. Note: the MailService class is annotated with @Component, which makes it a Spring bean. So the default bean name for MailService class would be mailService (with the first letter converted to lowercase).

+

5.2.4 @Value

+

@Value annotation is used to inject values from properties files, environment variables, or other sources directly into bean fields or constructor parameters.

+

Code 5-12. "HelloService.java"

+
 1import org.springframework.beans.factory.annotation.Value;
+ 2import org.springframework.stereotype.Component;
+ 3
+ 4@Component
+ 5public class HelloService {
+ 6    @Value("Hello Spring Framework")
+ 7    private String message;
+ 8
+ 9    public void sayHello() {
+10        System.out.println(message);
+11    }
+12}
+

Code 5-12 defines a Spring component class named HelloService with a field message that is initialized with the value "Hello Spring Framework" using the @Value annotation, and a method sayHello() to print the message to the console when called.

+

5.2.5 @Scope

+

@Scope annotation is used to specify the the scope of a @Component class or a @Bean definition (just like scope field in <bean> tag), defining the lifecycle and visibility of the bean instance.

+

The default scope for a bean is Singleton, and we can define the scope of a bean as a Prototype using the scope="prototype" attribute of the <bean> tag in the XML file or using @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) annotation, shown in Code 5-13.

+

Code 5-13. Snippet of "AppConfig.java"

+
1@Configuration
+2public class AppConfig {
+3   @Bean
+4   @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+5   public MessageService messageService() {
+6      return new EmailMessageService();
+7   }
+8}
+

5.2.6 @PostConstructand @PreDestroy

+

@PostConstruct annotation is used to indicate a method (init-method field in <bean> tag) that should be executed after the bean has been initialized by the Spring container.

+

@PreDestroy annotation is used to indicate a method (destroy-method field in <bean> tag) that should be executed just before the bean is destroyed by the Spring container.

+

Code 5-14(a). ""

+
 1package com.example.ctordtor;
+ 2
+ 3import javax.annotation.PostConstruct;
+ 4import javax.annotation.PreDestroy;
+ 5
+ 6import org.springframework.stereotype.Component;
+ 7
+ 8@Component
+ 9public class ExampleBean {
+10
+11   @PostConstruct
+12   public void init() {
+13      System.out.println("Initializing bean...");
+14   }
+15
+16   @PreDestroy
+17   public void cleanup() {
+18      System.out.println("Destroying bean...");
+19   }
+20}
+

Code 5-14(b). "AppConfig.java"

+
 1package com.example.ctordtor;
+ 2
+ 3import org.springframework.context.annotation.ComponentScan;
+ 4import org.springframework.context.annotation.Configuration;
+ 5
+ 6@Configuration
+ 7@ComponentScan(basePackages = "com.example.springdemo")
+ 8public class AppConfig {
+ 9
+10}
+

5.2.7 @Lazy

+

The @Lazy annotation is used to delay the initialization of a bean until the first time it is requested.

+

Code 5-15. "AppConfig.java"

+
 1package com.example.annotation.lazy;
+ 2
+ 3import org.springframework.context.annotation.Bean;
+ 4import org.springframework.context.annotation.Configuration;
+ 5import org.springframework.context.annotation.Lazy;
+ 6
+ 7@Configuration
+ 8public class AppConfig {
+ 9
+10   @Lazy(value = true)
+11   @Bean
+12   public FirstBean firstBeanLazy() {
+13      return new FirstBean();
+14   }
+15
+16   @Lazy
+17   @Bean
+18   public SecondBean secondBeanLazy() {
+19      return new SecondBean();
+20   }
+21
+22   @Lazy(value = false)
+23   @Bean
+24   public ThirdBean thirdBeanNotLazy() {
+25      return new ThirdBean();
+26   }
+27
+28   @Bean
+29   public FourthBean fourthBeanNotLazy() {
+30      return new FourthBean();
+31   }
+32}
+

Code 5-15 defines 4 beans: firstBeanLazy and secondBeanLazy will be lazily initialized, while thirdBeanNotLazy and fourthBeanNotLazy will be eagerly initialized during the application startup.

+

5.2.8 @Primary

+

@Primary annotation is used to indicate a preferred bean when multiple beans of the same type are available for injection with @Autowired.

+

Code 5-16(a). Snippet of "AppConfig.java"

+
 1@Configuration
+ 2public class AppConfig {
+ 3
+ 4    @Bean
+ 5    public MessageService getEmailService() {
+ 6        return new MessageService("Email");
+ 7    }
+ 8
+ 9    @Bean
+10    @Primary
+11    public MessageService getSmsService() {
+12        return new MessageService("SMS");
+13    }
+14}
+

Code 5-16(a) defines two beans (MessageService instances) with different type names ("Email" and "SMS") and marks the return value of getSmsService() as the primary bean using the @Primary annotation.

+

Code 5-16(b). Snippet of "MessageService.java"

+
1public class MessageService {
+2   private String type;
+3
+4   public MessageService(String type) {
+5      this.type = type;
+6   }
+7
+8   // ...
+9}
+

Code 5-16(b) declares the MessageService class with a constructor to set the type of MessageService when creating an instance.

+

6. AOP

+

Aspect-Oriented Programming (AOP) is a framework in Spring that allows breaking down program logic into separate concerns, which are conceptually independent from core business logic of the application, providing a way to decouple cross-cutting concerns from the objects they affect.

+

6.1 AOP Concepts

+

The concepts shown in the table below are general terms that are related to AOP in a broader sense beyond Spring Framework.

+

Table 6-1. General Terms of AOP

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TermsDescription
Aspecta module which has a set of APIs providing cross-cutting requirements
Target objectThe object being advised by one or more aspects
Join pointa point in your application where you can plugin the AOP aspect
Pointcuta set of one or more join points where an advice should be executed
Advicethe actual action to be taken either before or after the method execution
Introductionallows you to add new methods or attributes to the existing classes.
Weavingthe process of linking aspects with other application types or objects to create an advised object
+

Spring AOP is a technique that modularizes cross-cutting concerns using aspects, which consist of advice and pointcuts. Aspects define specific behaviors, and pointcuts specify where these behaviors should be applied (e.g., method invocations).

+

During runtime weaving, the advice is applied to the target objects at the designated join points, effectively incorporating the desired functionalities into the application and improving code modularity.

+

Spring aspects can work with five kinds of advice mentioned:

+

Table 6-2. Types of Advice

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Types of AdviceDescription
beforerun advice before the execution of the method
afterrun advice after the execution of the method
after-returningrun advice after the a method only if its execution is completed successfully
after-throwingrun advice after the a method only if its execution throws exception
aroundrun advice before and after the advised method is invoked
+

6.2 XML Schema based AOP

+

Aspects can be implemented using the regular classes along with XML Schema based configuration. The basic structure for XML to config AOP looks like Code 6-0:

+

Code 6-0. Skeleton of AOP config in "beans.xml"

+
1<aop:config>
+2   <aop:aspect id = "{AOP_ID}" ref = "{CONFIG_CLASS_lowerCammelNotation}">
+3      <aop:pointcut id = "{POINTCUT_ID}" expression = "{POINTCUT_EXPRESSION}"/>
+4         <aop:{ADVICE_NAME} pointcut-ref = "{POINTCUT_ID}" method = "{CONFIG_CLASS_CERTAIN_METHOD}"/>
+5         <aop:after-returning pointcut-ref = "{POINTCUT_ID}" returning = "{RETURN_VAR_NAME}" method = "{CONFIG_CLASS_CERTAIN_METHOD}"/>
+6         <aop:after-throwing  pointcut-ref = "{POINTCUT_ID}" throwing = "{EXCEPTION_NAME}" method = "{CONFIG_CLASS_CERTAIN_METHOD}"/>
+7   </aop:aspect>
+8</aop:config>
+

Code 6-0 shows how to config AOP:

+
    +
  • An aspect is declared using the <aop:aspect> element, and the backing bean is referenced using the ref attribute.
  • +
  • A pointcut is declared using the <aop:pointcut> element to determine the join points (i.e., methods) of interest to be executed with different advices.
  • +
  • Advices can be declared inside <aop:aspect> tag using the element <aop:{ADVICE_NAME}>, such as <aop:before>, <aop:after>, <aop:after-returning>, <aop:after-throwing> and <aop:around>. (Please refer to Table 6-1).
  • +
+

PointCut Designator (PCD) is a keyword telling Spring AOP what to match.

+
    +
  1. execution(primary Spring PCD): matches method execution join points
  2. +
  3. within: limits matching to join points of certain types
  4. +
  5. this: limits matching to join points where the bean reference is an instance of the given type (when Spring AOP creates a CGLIB-based proxy).
  6. +
  7. target: limits matching to join points where the target object is an instance of the given type (when a JDK-based proxy is created).
  8. +
  9. args: matches particular method arguments
  10. +
+

Pointcut Expression looks like expression = "execution(* com.example.aop.*.*(..))", in expression field of <aop:pointcut> tag:

+
    +
  • the execution is a Spring PCD
  • +
  • the first Asterisk Sign (*) in execution(* is a wildcard character that matches any return type of the intercepted method, e.g., void, Integer, String, etc.
  • +
  • the second asterisk (*) in com.example.aop.* is a wildcard character that matches any class in the com.example.aop package.
  • +
  • the dot and asterisk (.*) in com.example.aop.*.* is a wildcard character that matches any method with any name in the specified class.
  • +
  • (..)is another wildcard that matches any number of arguments in the method. (..) means the method can take zero or more arguments.
  • +
+

Code 6-1(a). "Logging.java"

+
 1package com.example.aop;
+ 2
+ 3public class Logging {
+ 4
+ 5    public void beforeAdvice(){
+ 6        System.out.println("`beforeAdvice()` invoked.");
+ 7    }
+ 8
+ 9    public void afterAdvice(){
+10        System.out.println("`afterAdvice()` invoked.");
+11    }
+12
+13    public void afterReturningAdvice(Object retVal) {
+14        System.out.println("[Success] `afterReturningAdvice()` reads return value: " + retVal.toString() );
+15        System.out.println("------");
+16    }
+17
+18    public void afterThrowingAdvice(Exception exception){
+19        System.out.println("[FAILURE] `afterThrowingAdvice()` detects Exception: " + exception.toString());
+20        System.out.println("------");
+21    }
+22}
+

Code 6-1(a) represents an aspect in an AOP context, and it contains various advice methods that will be executed at specific points during the execution of the target methods in the application:

+
    +
  • beforeAdvice() method will be executed before the target method is invoked.
  • +
  • afterAdvice() method will be executed after the target method has been invoked, regardless of whether it completed successfully or threw an exception.
  • +
  • afterReturningAdvice(Object retVal) method will be executed after the target method has successfully completed and returned a value. (The retVal parameter contains the value returned by the target method.)
  • +
  • afterThrowingAdvice(Exception exception) method will be executed if the target method throws an exception. (The exception parameter contains the exception thrown by the target method.)
  • +
+

Code 6-1(b). "Student.java"

+
 1package com.example.aop;
+ 2
+ 3public class Student {
+ 4    private Integer age;
+ 5    private String name;
+ 6
+ 7    public void setAge(Integer age) {
+ 8        this.age = age;
+ 9    }
+10    public Integer getAge() {
+11        System.out.println("Class method `getAge()` gets `age` = " + age );
+12        return age;
+13    }
+14    public void setName(String name) {
+15        this.name = name;
+16    }
+17    public String getName() {
+18        System.out.println("Class method `getName()` gets `name` = " + name );
+19        return name;
+20    }
+21    public void throwsException(){
+22        System.out.println("Class method `throwsException()` will throw 'IllegalArgumentException'");
+23        if (true)
+24         throw new IllegalArgumentException(); // For Test
+25    }
+26}
+

In Code 6-1(b), Student class has getters/setters for age and name properties, and also has the throwsException() method, which will throw an IllegalArgumentException to demonstrate how AOP and exception handling work together.

+

Code 6-1(c). "AopDemoTest.java"

+
 1package com.example.aop;
+ 2
+ 3import org.springframework.context.ApplicationContext;
+ 4import org.springframework.context.support.ClassPathXmlApplicationContext;
+ 5
+ 6public class AopDemoTest {
+ 7    public static void main(String[] args) {
+ 8        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
+ 9
+10        Student student = (Student) context.getBean("student");
+11        student.getName();
+12        student.getAge();
+13        student.throwsException();
+14    }
+15}
+

Code 6-1(c) contains the main method that demonstrates the usage of AOP.

+

Code 6-1(d). "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2<beans xmlns = "http://www.springframework.org/schema/beans"
+ 3   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
+ 4   xmlns:aop = "http://www.springframework.org/schema/aop"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
+ 7   http://www.springframework.org/schema/aop 
+ 8   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
+ 9
+10    <!-- Bean definition for student -->
+11    <bean id = "student" class = "com.example.aop.Student">
+12        <property name = "name" value = "Tom" />
+13        <property name = "age" value = "83"/>
+14    </bean>
+15
+16    <!-- Bean definition for logging aspect -->
+17    <bean id = "logging" class = "com.example.aop.Logging"/>
+18
+19    <!-- AOP Configurations -->
+20    <aop:config>
+21        <!--
+22           `<aop:aspect id = "log">`: defines an aspect named "log" 
+23            `ref = "logging"`:  refer to the bean named "logging", 
+24                                   representing the "Logging.java" aspect
+25        -->
+26        <aop:aspect id = "log" ref = "logging">
+27            <!-- 
+28               A pointcut named "selectAll" is defined using an `expression` 
+29                  to target *all methods* 
+30                     within the package "com.example.aop" and its sub-packages. 
+31            -->
+32            <aop:pointcut id = "selectAll"
+33                          expression = "execution(* com.example.aop.*.*(..))"/>
+34
+35            <!--
+36               Associates the "beforeAdvice()" method 
+37                  with the "selectAll" pointcut
+38                     to be executed **before** the target methods
+39            -->
+40            <aop:before pointcut-ref = "selectAll" method = "beforeAdvice"/>
+41            
+42            <!--  
+43               Associates the "afterAdvice()" method 
+44                  with the "selectAll" pointcut 
+45                     to be executed **after** the target methods.
+46            -->
+47            <aop:after pointcut-ref = "selectAll" method = "afterAdvice"/>
+48
+49            <!--
+50               Associates the "afterReturningAdvice()" method 
+51                  with the "selectAll" pointcut 
+52                     to be executed after the **successful return** of the target methods.
+53                     
+54               The returning value will be the parameter for `afterReturningAdvice()`.
+55            -->
+56            <aop:after-returning pointcut-ref = "selectAll"
+57                                 returning = "retVal" method = "afterReturningAdvice"/>
+58
+59            <!--
+60               Associates the "afterThrowingAdvice()" method 
+61                  with the "selectAll" pointcut
+62                     to be executed if the target methods throw an exception.
+63               The Exception object will be the parameter for `afterThrowingAdvice()`.
+64            -->
+65            <aop:after-throwing pointcut-ref = "selectAll"
+66                                throwing = "exception" method = "afterThrowingAdvice"/>
+67
+68        </aop:aspect>
+69    </aop:config>
+70
+71</beans>
+

Code 6-1(d) shows how to config Spring AOP.

+

The expected output for Code 6-1(a, b, c, d) is:

+
 1`beforeAdvice()` invoked.
+ 2Class method `getName()` gets `name` = Tom
+ 3`afterAdvice()` invoked.
+ 4[Success] `afterReturningAdvice()` reads return value: Tom
+ 5------
+ 6`beforeAdvice()` invoked.
+ 7Class method `getAge()` gets `age` = 83
+ 8`afterAdvice()` invoked.
+ 9[Success] `afterReturningAdvice()` reads return value: 83
+10------
+11`beforeAdvice()` invoked.
+12Class method `throwsException()` will throw 'IllegalArgumentException'
+13`afterAdvice()` invoked.
+14[FAILURE] `afterThrowingAdvice()` detects Exception: java.lang.IllegalArgumentException
+15------
+16Exception in thread "main" java.lang.IllegalArgumentException
+17	at com.example.aop.Student.throwsException(Student.java:23)
+18	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
+19	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
+20   (Omit the rest 22-line-long Exception message...)
+

Code 6-1(e). "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2<beans xmlns = "http://www.springframework.org/schema/beans"
+ 3   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
+ 4   xmlns:aop = "http://www.springframework.org/schema/aop"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
+ 7   http://www.springframework.org/schema/aop 
+ 8   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
+ 9
+10    <!-- Definition for student bean -->
+11    <bean id = "student" class = "com.example.aop.Student">
+12        <property name = "name" value = "Jerry" />
+13        <property name = "age" value = "83"/>
+14    </bean>
+15
+16    <!-- Definition for logging aspect -->
+17    <bean id = "logging" class = "com.example.aop.Logging"/>
+18
+19    <!-- AOP Configurations -->
+20    <aop:config>
+21        <aop:aspect id = "log" ref = "logging">
+22
+23            <!--
+24               A pointcut named "selectGetName" using an expression
+25                  to target the `getName()` method of the `Student` class.
+26
+27               Note: `(..)` is a wildcard that 
+28                        represents zero or more arguments of any type.
+29            -->
+30            <aop:pointcut id = "selectGetName"
+31                          expression = "execution(* com.example.aop.Student.getName(..))"/>
+32
+33            <aop:before pointcut-ref = "selectGetName" method = "beforeAdvice"/>
+34            <aop:after pointcut-ref = "selectGetName" method = "afterAdvice"/>
+35            <aop:after-returning pointcut-ref = "selectGetName"
+36                                 returning = "retVal" method = "afterReturningAdvice"/>
+37            <aop:after-throwing pointcut-ref = "selectGetName"
+38                                throwing = "exception" method = "afterThrowingAdvice"/>
+39
+40        </aop:aspect>
+41    </aop:config>
+42
+43</beans>
+

Code 6-1(e) looks like Code 6-1(d), except for the element <aop:pointcut id = "selectGetName" expression = "execution(* com.example.aop.Student.getName(..))"/>, which targets only on the method Student.getName() rather than all methods in the Student class.

+

The expected output for Code 6-1(a, b, c, e) is:

+
 1`beforeAdvice()` invoked.
+ 2Class method `getName()` gets `name` = Tom
+ 3[Success] `afterReturningAdvice()` reads return value: Tom
+ 4------
+ 5`afterAdvice()` invoked.
+ 6Class method `getAge()` gets `age` = 83
+ 7Class method `throwsException()` will throw 'IllegalArgumentException'
+ 8Exception in thread "main" java.lang.IllegalArgumentException
+ 9	at com.example.aop.Student.throwsException(Student.java:23)
+10	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
+11	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
+12	(Omit the rest 10-line-long Exception message...)
+

6.3 AspectJ based AOP

+

AspectJ refers declaring aspects as regular Java classes with Java 5 annotations.

+

First, the "beans.xml" need to be modified with <aop:aspectj-autoproxy/> tag, shown in Code 6-2.

+

Code 6-2. "beans.xml"

+
 1<?xml version = "1.0" encoding = "UTF-8"?>
+ 2<beans xmlns = "http://www.springframework.org/schema/beans"
+ 3   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
+ 4   xmlns:aop = "http://www.springframework.org/schema/aop"
+ 5   xsi:schemaLocation = "http://www.springframework.org/schema/beans
+ 6   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
+ 7   http://www.springframework.org/schema/aop 
+ 8   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
+ 9
+10   <!-- AOP Configurations -->
+11   <aop:aspectj-autoproxy/>
+12
+13   <!-- Bean definition for student -->
+14   <bean id = "student" class = "com.example.aop.Student">
+15      <property name = "name" value = "Tom" />
+16      <property name = "age" value = "83"/>
+17   </bean>
+18
+19   <!-- Bean definition for logging aspect -->
+20   <bean id = "logging" class = "com.example.aop.Logging"/>
+21   
+22</beans>
+

Code 6-2 shows how to use <aop:aspectj-autoproxy/> tag to simplify AOP configuration.

+

Then I will rewrite the Code 6-1(a, c) to show how to use AspectJ. To declare Pointcuts and Advices, rewrite Code 6-1(a) to Code 6-1-AOP(a):

+

Code 6-1-AOP(a). "Logging.java"

+
 1package com.example.aop;
+ 2
+ 3import org.aspectj.lang.annotation.Aspect;
+ 4import org.aspectj.lang.annotation.Pointcut;
+ 5import org.aspectj.lang.annotation.Before;
+ 6import org.aspectj.lang.annotation.After;
+ 7import org.aspectj.lang.annotation.AfterThrowing;
+ 8import org.aspectj.lang.annotation.AfterReturning;
+ 9// import org.aspectj.lang.annotation.Around;
+10
+11@Aspect
+12public class Logging {
+13
+14   /*
+15      A pointcut named "selectAll" is defined using `@Pointcut` 
+16                  to target *all methods* 
+17                     within the package "com.example.aop" and its sub-packages. 
+18      the method `selectAll()` is just a signature
+19   */
+20   @Pointcut("execution(* com.example.aop.*.*(..))")
+21   private void selectAll(){}
+22
+23   @Before("selectAll()")
+24   public void beforeAdvice(){
+25      System.out.println("`beforeAdvice()` invoked.");
+26   }
+27
+28   @After("selectAll()")
+29   public void afterAdvice(){
+30      System.out.println("`afterAdvice()` invoked.");
+31   }
+32
+33   @AfterReturning(pointcut = "selectAll()", returning = "retVal")
+34   public void afterReturningAdvice(Object retVal) {
+35      System.out.println("[Success] `afterReturningAdvice()` reads return value: " + retVal.toString() );
+36      System.out.println("------");
+37   }
+38
+39   @AfterThrowing(pointcut = "selectAll()", throwing = "exception")
+40   public void afterThrowingAdvice(Exception exception){
+41      System.out.println("[FAILURE] `afterThrowingAdvice()` detects Exception: " + exception.toString());
+42      System.out.println("------");
+43   }
+44}
+

Code 6-1-AOP(a) defines an AspectJ aspect named Logging, which contains advice methods (@Before, @After, @AfterReturning, @AfterThrowing) to log messages before and after the execution of all methods in the package "com.example.aop" and its sub-packages, as well as handling method return values and exceptions.

+

Note: in XML Schema based AOP, we use <aop:pointcut id = "POINTCUT_NAME" expression = "POINTCUT_EXPRESSION"; in AspectJ based AOP, we use @Pointcut("POINTCUT_EXPRESSION") annotation on an empty method called private void POINTCUT_NAME(){}.

+

The expected output for Code 6-1-AOP(a), Code 6-1(b, c), and Code 6-2 should be:

+
 1`beforeAdvice()` invoked.
+ 2Class method `getName()` gets `name` = Tom
+ 3[Success] `afterReturningAdvice()` reads return value: Tom
+ 4------
+ 5`afterAdvice()` invoked.
+ 6`beforeAdvice()` invoked.
+ 7Class method `getAge()` gets `age` = 83
+ 8[Success] `afterReturningAdvice()` reads return value: 83
+ 9------
+10`afterAdvice()` invoked.
+11`beforeAdvice()` invoked.
+12Class method `throwsException()` will throw 'IllegalArgumentException'
+13[FAILURE] `afterThrowingAdvice()` detects Exception: java.lang.IllegalArgumentException
+14------
+15`afterAdvice()` invoked.
+16Exception in thread "main" java.lang.IllegalArgumentException
+17	at com.example.aop.Student.throwsException(Student.java:26)
+18   (Omit the rest Exception message...)
+

And if we want to target the Pointcut to Student.getName() method only, we can modify Code 6-1-AOP(a) to Code 6-1-AOP-selectGetName(a):

+

Code 6-1-AOP-selectGetName(a). "Logging.java"

+
 1package com.example.aop;
+ 2
+ 3import org.aspectj.lang.annotation.Aspect;
+ 4import org.aspectj.lang.annotation.Pointcut;
+ 5import org.aspectj.lang.annotation.Before;
+ 6import org.aspectj.lang.annotation.After;
+ 7import org.aspectj.lang.annotation.AfterThrowing;
+ 8import org.aspectj.lang.annotation.AfterReturning;
+ 9// import org.aspectj.lang.annotation.Around;
+10
+11@Aspect
+12public class Logging {
+13
+14   /*
+15      A pointcut named "selectGetName" using an expression
+16         to target the `getName()` method of the `Student` class.
+17
+18      Note: `(..)` is a wildcard that 
+19               represents zero or more arguments of any type.
+20   */
+21   @Pointcut("execution(* com.example.aop.Student.getName(..))")
+22   private void selectGetName(){}
+23
+24   @Before("selectGetName()")
+25   public void beforeAdvice(){
+26      System.out.println("`beforeAdvice()` invoked.");
+27   }
+28
+29   @After("selectGetName()")
+30   public void afterAdvice(){
+31      System.out.println("`afterAdvice()` invoked.");
+32   }
+33
+34   @AfterReturning(pointcut = "selectGetName()", returning = "retVal")
+35   public void afterReturningAdvice(Object retVal) {
+36      System.out.println("[Success] `afterReturningAdvice()` reads return value: " + retVal.toString() );
+37      System.out.println("------");
+38   }
+39
+40   @AfterThrowing(pointcut = "selectGetName()", throwing = "exception")
+41   public void afterThrowingAdvice(Exception exception){
+42      System.out.println("[FAILURE] `afterThrowingAdvice()` detects Exception: " + exception.toString());
+43      System.out.println("------");
+44   }
+45}
+

Code 6-1-AOP-selectGetName(a) changes pointcut to target only on method Student.getName().

+

The expected output for Code 6-1-AOP-selectGetName(a), Code 6-1(b, c), and Code 6-2 should be:

+
 1`beforeAdvice()` invoked.
+ 2Class method `getName()` gets `name` = Tom
+ 3[Success] `afterReturningAdvice()` reads return value: Tom
+ 4------
+ 5`afterAdvice()` invoked.
+ 6Class method `getAge()` gets `age` = 83
+ 7Class method `throwsException()` will throw 'IllegalArgumentException'
+ 8Exception in thread "main" java.lang.IllegalArgumentException
+ 9	at com.example.aop.Student.throwsException(Student.java:24)
+10	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
+11	(Omit the rest message...)
+
+
+ + +
+
+
* This blog was last updated on 2023-07-19 00:00
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/2024/05/kia-ch01-introducing-kubernetes/index.html b/2024/05/kia-ch01-introducing-kubernetes/index.html new file mode 100644 index 0000000..5d2864e --- /dev/null +++ b/2024/05/kia-ch01-introducing-kubernetes/index.html @@ -0,0 +1,828 @@ + + + + +KIA CH01 Introducing Kubernetes | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

KIA CH01 Introducing Kubernetes

+ + +

Hi there.

+

Today, let us read the Chapter 01: Introducing Kubernetes of Kubernetes in Action

+
    +
  1. the history of software developing
  2. +
  3. isolation by containers
  4. +
  5. how containers and Docker are used by Kubernetes
  6. +
  7. how to simplify works by Kubernetes
  8. +
+

The software architecture has transitioned from Monolithic to Microservice. Legacy software applications were big monoliths; nowadays, microservices, the small and independently running components, are introduced to decouple from each other, and are therefore easily developed, deployed, updated, and scaled, to meet changing business requirements.

+

Kubernetes (k8s) is introduced to reduce complexity brought by bigger number of microservices, automating the process of scheduling components to our servers, automatic configuration, supervision, and failure-handling. K8s abstracts the hardware infrastructure as a single enormous computational resource, selects a server for each component, deploys it, and enables it to easily find and communicate with all the other components.

+

1.1 Understanding the need for a system like Kubernetes

+

In this section, the book talks about how the development and deployment of applications has changed in recent years, caused by:

+
    +
  • splitting big monolithic apps into smaller microservices
  • +
  • the changes in the infrastructure that runs those apps
  • +
+

1.1.1 Moving from monolithic to microservices

+

Monolithic applications: components that are all tightly coupled together and have to be developed, deployed, and managed as one entity, because they all run as a single OS process.

+

microservices: smaller independently deployable components.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MonolithicMicroservices
componentstightly coupled togetherindependently deployable
scalingvertical scaling (scaling up)horizontal scaling (scaling out)
communicationfunction invokingwell-defined interfaces (RESTful APIs, AMQP, etc.)
changesredeployment of whole systemminimal redeployment
deploymenteasytedious and error-prone
debug/ traceeasyhard: span multiple processes and machines (requires Zipkin)
+

1.1.2 Providing a consistent environment to applications

+

The environments on which the apps rely can differ from one machine to another, from one operating system to another, and from one library to another.

+

A consistent environment is required, to prevent failures :

+
    +
  • exact same operating system, libraries, system configuration, networking environment, etc.
  • +
  • add applications to the same server without affecting any of the existing applications on that server.
  • +
+

1.1.3 Moving to continuous delivery: DevOps and NoOps

+

Nowadays, there are two typical practices that the same team develops the app, deploys it, and takes cares of it over its whole lifetime:

+
    +
  • DevOps: a practice that the developer, QA, and operations teams collaborate throughout the whole process. +
      +
    • a better understanding of issues from users and ops team, early feedback
    • +
    • streamlining the deployment process, more often of releasing newer versions of applications
    • +
    +
  • +
  • NoOps: a practice that the developers can deploy applications themselves without knowing hardware infrastructure and without dealing with the ops team. +
      +
    • Kubernetes allows developers to configure and deploy their apps independently
    • +
    • sysadmins focus on how to keep the underlying infrastructure up and running, rather than on how the apps run on top of the underlying infrastructure.
    • +
    +
  • +
+

1.2 Introducing container technologies

+

Kubernetes uses Linux container technologies to provide isolation.

+

1.2.1 What are containers

+

Containers are much more lightweight (than VMs), which allows you to run many software components on the same hardware.

+
    +
  • the process in the container is isolated from other processes inside the same host OS
  • +
  • containers consume only necessary resources (while VMs require a whole separate operating systems and additional compute resources)
  • +
+

Two mechanisms that containers use to isolate processes: Linux Namespaces, and Linux Control Groups(cgroups)

+
    +
  1. +

    Linux Namespaces

    +

    Linux Namespaces isolates system resources, and make each process can only see resources that are inside the same namespace.

    +

    The following table shows kinds of namespace:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    namespacemeaning
    mntMount
    pidProcess ID
    netNetwork namespace 1
    ipcInter-process communication
    UTShostname and domain name 2
    userUser ID
    +
  2. +
+
    +
  1. +

    Linux Control Groups (cgroups)

    +

    Linux Control Groups(cgroups) is a Linux kernel feature that can limit the resource usage of a process, or a group of processes.

    +
  2. +
+

1.2.2 Introducing the Docker container platform

+

Docker is a platform for packaging, distributing, and running applications.

+
    +
  • Image: packaging application and environment, comprised of: +
      +
    • isolated filesystem, which is available to the app
    • +
    • metadata, which is used to execute the image on running image
    • +
    +
  • +
  • Registry: a (public or private) repository that stores and shares Docker images. +
      +
    • push: uploading the image to a registry
    • +
    • pull: downloading the image from a registry
    • +
    +
  • +
  • Container: a process that is isolated (running) and resource-constrained, running on the host OS, created from a Docker-based container image.
  • +
+
@startuml
+start
+:Docker builds image;
+:Docker pushes image to registry;
+:Docker pulls image from registry;
+:Docker runs container from image;
+stop
+@enduml
+

Docker container images are composed of "layers":

+
    +
  • shared and reused by building a new image on top of an existing parent image +
      +
    • speeding up distribution across network
    • +
    • reducing the storage footprint (each layer stored only once)
    • +
    +
  • +
  • readonly for layers in images +
      +
    • until a new container is run, and a new writable layer is to be created;
    • +
    • until a write request is made to a file located in underlying image layers, the write operation is then applied to the newly created top-most layer that contains a copy of the file.
    • +
    +
  • +
+

However, Docker uses Linux kernel of the host OS, it therefore does have limitations:

+
    +
  • same version of Linux kernel
  • +
  • same kernel modules available
  • +
+

1.2.3 Introducing 'rkt' — an alternative to Docker

+

Just like Docker, rkt is a platform for running containers, but with a strong emphasis on security, composability, and conforming to open standards.

+

1.3 Introducing Kubernetes

+

Kubernetes is a software system that allows you to easily deploy and manage containerized applications.

+

1.3.1 The origins of Kubernetes

+

Google invented Kubernetes out of its internal systems like 'Borg' and 'Omega':

+
    +
  • Simplification of Development and Management
  • +
  • higher utilization of infrastructure
  • +
+

1.3.2 Looking at Kubernetes from the top of a mountain

+

There are 3 features that Kubernetes has:

+
    +
  1. +

    easy deployment and management

    +
      +
    • Linux containers to run heterogeneous applications +
        +
      • without detailed knowledge of their internals
      • +
      • without manual deployment on each host
      • +
      +
    • +
    • containerization to isolate applications, on shared hardware +
        +
      • optimal hardware utilization
      • +
      • complete isolation of hosted applications
      • +
      +
    • +
    +
  2. +
  3. +

    abstraction of the underlying infrastructure

    +
      +
    • runs applications on thousands of nodes as if all nodes were one single enormous computer
    • +
    • easy development, deployment and management for both development and the operations teams
    • +
    +
  4. +
  5. +

    Deploying applications in Kubernetes is a consistent process

    +
      +
    • cluster nodes represent amount of resources available to the apps
    • +
    • number of nodes does not change the process of deployment
    • +
    +
  6. +
+

In practice, Kubernetes exposes the whole data center as a single deployment platform. Kubernetes allows developers to focus on implementing the actual features of the applications. And Kubernetes will handle infrastructure-related services (such as service discovery, scaling, load-balancing, self-healing, and leader election ).

+

1.3.3 Architecture of a Kubernetes cluster

+

Kubernetes cluster is composed of 2 types of nodes:

+
    +
  1. Control Plane (Master): controls the cluster +
      +
    • API Server: communicates with other components
    • +
    • Scheduler: schedules apps by assigning a worker node to each deployable component of app
    • +
    • Controller Manager: performs cluster-level functions, such as replicating components, keeping track of worker nodes, and handling node failures.
    • +
    • etcd: a reliable distributed database that persistently stores the cluster configuration
    • +
    +
  2. +
  3. Worker Nodes: runs containerized applications +
      +
    • Kubelet: talks to the API server and manages containers on its node
    • +
    • kube-proxy (Kubernetes Service Proxy): load-balances network traffic between application components
    • +
    • container runtime: runs containers, e.g., Docker rkt
    • +
    +
  4. +
+
@startuml
+title "components of Kubernetes cluster"
+node "Control Plane (master)" {
+    database "etcd" as etcd
+    rectangle  "API server" as apiServer
+    rectangle  "Scheduler" as scheduler
+    rectangle  "Controller Manager" as controllerManager
+    scheduler --> apiServer
+    controllerManager --> apiServer
+    apiServer --> etcd
+}
+node "Worker node(s)" {
+    rectangle  "Container Runtime" as containerRuntime
+    rectangle  "Kubelet" as kubelet
+    rectangle  "kube-proxy" as kubeProxy
+    kubelet --> containerRuntime
+    kubelet --> apiServer
+    kubeProxy --> apiServer
+}
+@enduml
+

1.3.4 Running an application in Kubernetes

+

When the developer submits App Descriptor(a list of apps) to the master, Kubernetes then chooses worker nodes and deploys apps.

+

And App Descriptor is used to describe the detail of the running container:

+
    +
  • which container images, or which images that contain your application
  • +
  • how many replicas for each component
  • +
  • how components are related to each other +
      +
    • co-located: run together on the same worker node
    • +
    • otherwise, spread around the cluster.
    • +
    +
  • +
  • whether a service is internal or external
  • +
+

The diagram below shows how an App Descriptor works in starting app:

+
@startuml
+start
+:Developer submits App Descriptor to API Server;
+:Scheduler schedules the specified groups of containers onto the available worker nodes;
+:Kubelet on the worker node instruct Container Runtime to pull and run the containers;
+stop
+@enduml
+

After the application is running, Kubernetes continuously makes sure that the deployed state of the application always matches the description :

+
    +
  • if one instance stopped working, Kubernetes will restart this instance
  • +
  • if one worker node dies (becomes inaccessible), Kubernetes will select a new node and run all the previous containers on the newly selected worker node
  • +
+

If workload fluctuates, Kubernetes can also automatically scale(increase/decrease) the number of replicas, based on real-time metrics your app exposes, such as CPU load, memory consumption, queries per second, etc.

+

However, Kubernetes may need to move containers around the cluster, under the following 2 circumstances:

+
    +
  • worker node failure
  • +
  • running container evicted to make room for other containers
  • +
+

To ensure services remain available to clients during the movement of containers, Kubernetes uses environment variables to expose a single static IP address to all applications running in the cluster. This allows clients to access the containers with a constant IP address, and kube-proxy will also ensure connections to the service are load-balanced across all the containers providing the service.

+

1.3.5 benefits of using Kubernetes

+
    +
  • +

    Simplifying application deployment

    +
  • +
  • +

    Achieving better utilization of hardware

    +
  • +
  • +

    Health checking and self-healing

    +
  • +
  • +

    Automatic scaling

    +
  • +
  • +

    Simplifying application development

    +
  • +
+
+
+
    +
  1. +

    Each network interface belongs to exactly one namespace, but can be moved from one namespace to another. ↩︎

    +
  2. +
  3. +

    Different UTS namespaces makes processes see different host names↩︎

    +
  4. +
+
+
+ + +
+
+
* This blog was last updated on 2024-05-06 15:54
+
+ + + + + + + + + + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/404.html b/404.html new file mode 100644 index 0000000..53bd2dc --- /dev/null +++ b/404.html @@ -0,0 +1,221 @@ + + + + +404 Page not found | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+

Lost

+

We couldn't find the page you're looking for


+
Go Back
+
+ +
+ + + + + + + + diff --git a/about/index.html b/about/index.html new file mode 100644 index 0000000..81abe27 --- /dev/null +++ b/about/index.html @@ -0,0 +1,416 @@ + + + + +About | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+

About

+ + +

Hi, welcome to Mighten's Tech blog!

+

This blog focuses on Cloud Computing and Machine Learning.

+

Currently, I am studying Big Data and Artificial Intelligence (M.Eng. degree in Software Engineering) at University of Science and Technology of China (USTC).

+

PLANS

+

There are lists of what I gonna do:

+

Plan on Skills

+ +

Plan on Courses

+ +

Plan on Readings

+
    +
  • Algorithms parts in Introduction to Java Programming Language (The Complete Version).
  • +
  • Designing Data-Intensive Applications, which was written by Prof. Martin Kleppmann
  • +
+

ACKNOWLEDGEMENTS

+

There is a list of fantastic components that help to build this blog:

+
    +
  • Hugo, a fast and modern static site generator written in Go.
  • +
  • Hugo Clarity, A theme based on VMware's Clarity Design System for publishing technical blogs with Hugo.
  • +
  • KaTeX, a fast, easy-to-use JavaScript library for TeX math rendering on the web.
  • +
  • Mermaid, a JavaScript-based diagramming and charting tool that uses Markdown-inspired text definitions and a renderer to create and modify complex diagrams.
  • +
  • Utterances, a lightweight comments widget built on GitHub issues.
  • +
  • Cloudflare Web Analytics, a free and privacy-first analytics tool for your website.
  • +
  • Vecta Nano, a SVG file optimizer that can embed fonts and minify SVG file to save space and bandwidth.
  • +
+ +
+ + +
+
+
* This blog was last updated on 2022-05-20 12:07
+
+ + + + + + +
+ + + + +
+ + + +
+ + +
+ + + + + + + + diff --git a/assets/img/Note-Snippet.gif b/assets/img/Note-Snippet.gif new file mode 100644 index 0000000..4c6888a Binary files /dev/null and b/assets/img/Note-Snippet.gif differ diff --git a/assets/img/bar.svg b/assets/img/bar.svg new file mode 100644 index 0000000..0defb0a --- /dev/null +++ b/assets/img/bar.svg @@ -0,0 +1 @@ + diff --git a/assets/img/broken-image-error-msg.png b/assets/img/broken-image-error-msg.png new file mode 100644 index 0000000..06293a9 Binary files /dev/null and b/assets/img/broken-image-error-msg.png differ diff --git a/assets/img/building.png b/assets/img/building.png new file mode 100644 index 0000000..b437490 Binary files /dev/null and b/assets/img/building.png differ diff --git a/assets/img/cancel.svg b/assets/img/cancel.svg new file mode 100644 index 0000000..f2e8469 --- /dev/null +++ b/assets/img/cancel.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/img/caret-icon.svg b/assets/img/caret-icon.svg new file mode 100644 index 0000000..8f9bb98 --- /dev/null +++ b/assets/img/caret-icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/img/close.svg b/assets/img/close.svg new file mode 100644 index 0000000..0b43290 --- /dev/null +++ b/assets/img/close.svg @@ -0,0 +1 @@ + diff --git a/assets/img/dollar.png b/assets/img/dollar.png new file mode 100644 index 0000000..da93ff9 Binary files /dev/null and b/assets/img/dollar.png differ diff --git a/assets/img/expand.svg b/assets/img/expand.svg new file mode 100644 index 0000000..dce2376 --- /dev/null +++ b/assets/img/expand.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/img/night-moon.jpg b/assets/img/night-moon.jpg new file mode 100644 index 0000000..cfa8bb3 Binary files /dev/null and b/assets/img/night-moon.jpg differ diff --git a/assets/img/post/2023-04/MIT-6.033-CSE-Operating-System/VirtualMachineEnvironment.svg b/assets/img/post/2023-04/MIT-6.033-CSE-Operating-System/VirtualMachineEnvironment.svg new file mode 100644 index 0000000..8a11cc3 --- /dev/null +++ b/assets/img/post/2023-04/MIT-6.033-CSE-Operating-System/VirtualMachineEnvironment.svg @@ -0,0 +1 @@ +Physical HardwareU/K, PTR, Page Table, ...Virtual Machine Monitor (VMM)Virtual HardwareU/K, PTR, Page Table, ...Guest OSVirtual HardwareU/K, PTR, Page Table, ...Guest OS \ No newline at end of file diff --git a/assets/img/post/2023-04/MIT-6.033-CSE-Operating-System/latency_vs_num_of_users.svg b/assets/img/post/2023-04/MIT-6.033-CSE-Operating-System/latency_vs_num_of_users.svg new file mode 100644 index 0000000..f246cfa --- /dev/null +++ b/assets/img/post/2023-04/MIT-6.033-CSE-Operating-System/latency_vs_num_of_users.svg @@ -0,0 +1 @@ +latencynumber of users \ No newline at end of file diff --git a/assets/img/post/2023-04/MIT-6.033-CSE-Operating-System/throughput_vs_num_of_users.svg b/assets/img/post/2023-04/MIT-6.033-CSE-Operating-System/throughput_vs_num_of_users.svg new file mode 100644 index 0000000..c437798 --- /dev/null +++ b/assets/img/post/2023-04/MIT-6.033-CSE-Operating-System/throughput_vs_num_of_users.svg @@ -0,0 +1 @@ +throughputnumber of users \ No newline at end of file diff --git a/assets/img/post/2023-05/MIT-6.033-CSE-Networking/4-layers-TCP_IP-model.svg b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/4-layers-TCP_IP-model.svg new file mode 100644 index 0000000..1ba65a9 --- /dev/null +++ b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/4-layers-TCP_IP-model.svg @@ -0,0 +1 @@ +LinkNetworkTransportApplication \ No newline at end of file diff --git a/assets/img/post/2023-05/MIT-6.033-CSE-Networking/AIMD-Algorithm.svg b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/AIMD-Algorithm.svg new file mode 100644 index 0000000..37e5897 --- /dev/null +++ b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/AIMD-Algorithm.svg @@ -0,0 +1 @@ +sending rate of Bsending rate of AA = BA + B = bandwidth \ No newline at end of file diff --git a/assets/img/post/2023-05/MIT-6.033-CSE-Networking/Client-Server-CDN-P2P.svg b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/Client-Server-CDN-P2P.svg new file mode 100644 index 0000000..7cbb171 --- /dev/null +++ b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/Client-Server-CDN-P2P.svg @@ -0,0 +1 @@ +OriginOriginCDNCDNClient-ServerCDNP2P \ No newline at end of file diff --git a/assets/img/post/2023-05/MIT-6.033-CSE-Networking/Internet-of-AS.svg b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/Internet-of-AS.svg new file mode 100644 index 0000000..2093d96 --- /dev/null +++ b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/Internet-of-AS.svg @@ -0,0 +1 @@ +TransitPeer \ No newline at end of file diff --git a/assets/img/post/2023-05/MIT-6.033-CSE-Networking/autonomous-systems.svg b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/autonomous-systems.svg new file mode 100644 index 0000000..c7e045f --- /dev/null +++ b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/autonomous-systems.svg @@ -0,0 +1 @@ +TransitPeer6573241 \ No newline at end of file diff --git a/assets/img/post/2023-05/MIT-6.033-CSE-Networking/congested-network.svg b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/congested-network.svg new file mode 100644 index 0000000..116430c --- /dev/null +++ b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/congested-network.svg @@ -0,0 +1 @@ +ABDCR1R2 \ No newline at end of file diff --git a/assets/img/post/2023-05/MIT-6.033-CSE-Networking/form-innetwork-resource-management.svg b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/form-innetwork-resource-management.svg new file mode 100644 index 0000000..d043f13 --- /dev/null +++ b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/form-innetwork-resource-management.svg @@ -0,0 +1 @@ +pros/cons?how does the protocol workexample protocolwhat does this type ofmanagement allow aswitch to dotype ofmanagementsimple, but queue get fulldrop packets before queue fullDropTailSignal congestion,potentially beforequeues are fullQueueManagementqueue not get full, but complicateddrop/mark packets before queue fullRED, ECNstarve out the othersserve some queues before othersPriority-Queueingprioritizelatency-sensitive trafficDelay-basedSchedulingcan't handle variable packet sizeequal share of bandwidthRound-Robin (RR)enforce (weighted)fairness among differenttypes of trafficBandwidth-basedSchedulinghard to get avg. packet sizeRR with avg. packet sizeWeight Round-Robinhonestly goodRR, with better packet sizeDeficit Round-Robin \ No newline at end of file diff --git a/assets/img/post/2023-05/MIT-6.033-CSE-Networking/network-endpoints-switches-links.svg b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/network-endpoints-switches-links.svg new file mode 100644 index 0000000..96e5da8 --- /dev/null +++ b/assets/img/post/2023-05/MIT-6.033-CSE-Networking/network-endpoints-switches-links.svg @@ -0,0 +1 @@ +End PointSwitchLink \ No newline at end of file diff --git a/assets/img/post/2023-06/MIT-6.033-CSE-DistributedSystems/ReplicateStateMachine.svg b/assets/img/post/2023-06/MIT-6.033-CSE-DistributedSystems/ReplicateStateMachine.svg new file mode 100644 index 0000000..47dc31b --- /dev/null +++ b/assets/img/post/2023-06/MIT-6.033-CSE-DistributedSystems/ReplicateStateMachine.svg @@ -0,0 +1 @@ +CVSWho is primary?S1S2S1UpdateACKHeart BeatHeart Beat(primary)(backup)(view server)(clients) \ No newline at end of file diff --git a/assets/img/post/2023-07/spring-framework/spring-framework-architecture.svg b/assets/img/post/2023-07/spring-framework/spring-framework-architecture.svg new file mode 100644 index 0000000..49d719a --- /dev/null +++ b/assets/img/post/2023-07/spring-framework/spring-framework-architecture.svg @@ -0,0 +1 @@ +TestCoreContainerAOPAspectsInstrumentationMessagingData Access /IntegrationWebSpring Framework \ No newline at end of file diff --git a/assets/img/post/2023-08/Discrete-Math-Ch01-Speaking-Mathematically/Arrow-Diagram-relation-R.svg b/assets/img/post/2023-08/Discrete-Math-Ch01-Speaking-Mathematically/Arrow-Diagram-relation-R.svg new file mode 100644 index 0000000..a6e26b7 --- /dev/null +++ b/assets/img/post/2023-08/Discrete-Math-Ch01-Speaking-Mathematically/Arrow-Diagram-relation-R.svg @@ -0,0 +1 @@ +21123 \ No newline at end of file diff --git a/assets/img/post/2023-08/Discrete-Math-Ch01-Speaking-Mathematically/Degree-with-Loop.svg b/assets/img/post/2023-08/Discrete-Math-Ch01-Speaking-Mathematically/Degree-with-Loop.svg new file mode 100644 index 0000000..644c774 --- /dev/null +++ b/assets/img/post/2023-08/Discrete-Math-Ch01-Speaking-Mathematically/Degree-with-Loop.svg @@ -0,0 +1 @@ +v \ No newline at end of file diff --git a/assets/img/sun.svg b/assets/img/sun.svg new file mode 100644 index 0000000..cddceed --- /dev/null +++ b/assets/img/sun.svg @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/categories/index.html b/categories/index.html new file mode 100644 index 0000000..25d916e --- /dev/null +++ b/categories/index.html @@ -0,0 +1,354 @@ + + + + +Categories | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/categories/index.xml b/categories/index.xml new file mode 100644 index 0000000..984008f --- /dev/null +++ b/categories/index.xml @@ -0,0 +1,10 @@ + + + + Categories on Mighten's Blog + https://mighten.github.io/categories/ + Recent content in Categories on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + + diff --git a/categories/page/1/index.html b/categories/page/1/index.html new file mode 100644 index 0000000..e53b404 --- /dev/null +++ b/categories/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/categories/ \ No newline at end of file diff --git a/css/figcaption-container.css b/css/figcaption-container.css new file mode 100644 index 0000000..0905220 --- /dev/null +++ b/css/figcaption-container.css @@ -0,0 +1,8 @@ +/* figcaption-container.css */ + +/* Center the .align-center-figcaption div horizontally */ +.figcaption-container { + align-content: center; + text-align: center; +} + \ No newline at end of file diff --git a/css/styles.72b41e6b5df8f2f781e1de22fa7cc43b66e1ad2c55d5cf57d579f8a69f71a6f65e6012daf718ea86c35a5ace56bd6364e8258139cfe5fb551449616495939934.css b/css/styles.72b41e6b5df8f2f781e1de22fa7cc43b66e1ad2c55d5cf57d579f8a69f71a6f65e6012daf718ea86c35a5ace56bd6364e8258139cfe5fb551449616495939934.css new file mode 100644 index 0000000..1eb4068 --- /dev/null +++ b/css/styles.72b41e6b5df8f2f781e1de22fa7cc43b66e1ad2c55d5cf57d579f8a69f71a6f65e6012daf718ea86c35a5ace56bd6364e8258139cfe5fb551449616495939934.css @@ -0,0 +1,3 @@ +html{--color-mode: 'lit';--light: #fff;--dark: #000;--bg: #002538;--haze: #f2f2f2;--gray: #020202;--accent: var(--gray);--text: #575757;--header-text: var(--dark);--font: Metropolis, sans-serif;--theme: #0077b8;--ease: cubic-bezier(.19,1,.22,1);--code-bg: var(--bg);--table-bg: var(--light);--table-haze: var(--haze);--table-border: #dedede;--footer-bg: var(--haze);--shadow: rgba(0,0,0,0.12);--translucent: rgba(0,0,0,0.05);--translucent-light: rgba(255,255,255,0.05);--post-bg: var(--light);--choice-bg: var(--haze);--ease: cubic-bezier(0.39, 0.575, 0.565, 1);--easing: cubic-bezier(.19,1,.22,1);--notice-code-bg: var(--bg);--notice-info-border-color: #6AB0DE;--notice-info-background: #E7F2FA;--notice-note-border-color: #F0B37E;--notice-note-background: #FFF2DB;--notice-tip-border-color: rgba(92, 184, 92, 0.8);--notice-tip-background: #E6F9E6;--notice-warning-border-color: rgba(217, 83, 79, 0.8);--notice-warning-background: #FAE2E2}html.page{--choice-bg: var(--light)}html[data-mode="dim"]{--light: hsla(0,0%,100%,0.87);--color-mode: 'dim';--text: var(--light);--accent: var(--bubble);--choice-bg: var(--bg);--code-bg: var(--translucent-light);--header-text: var(--light);--table-bg: var(--code-bg);--table-haze: rgba(255,255,255,0.1);--table-border: var(--code-bg);--footer-bg: var(--bg);--post-bg: var(--translucent-light)}html[data-mode="dim"] blockquote{background:var(--translucent-light);color:#dedede}html[data-mode="dim"] svg.icon{fill:var(--light)}html[data-mode="dim"] .icon img{background:none}html[data-mode="dim"] .icon svg{fill:#fafafa}html[data-mode="dim"] .sidebar_inner::before{display:none}html[data-mode="dim"] .color_choice::after{background-image:url("../assets/img/night-moon.jpg");transform:translateX(1.4rem)}@media (prefers-color-scheme: dark){html:not([data-mode="lit"]){--light: hsla(0,0%,100%,0.87);--color-mode: 'dim';--text: var(--light);--accent: var(--bubble);--choice-bg: var(--bg);--code-bg: var(--translucent-light);--header-text: var(--light);--table-bg: var(--code-bg);--table-haze: rgba(255,255,255,0.1);--table-border: var(--code-bg);--footer-bg: var(--bg);--post-bg: var(--translucent-light)}html:not([data-mode="lit"]) blockquote{background:var(--translucent-light);color:#dedede}html:not([data-mode="lit"]) svg.icon{fill:var(--light)}html:not([data-mode="lit"]) .icon img{background:none}html:not([data-mode="lit"]) .icon svg{fill:#fafafa}html:not([data-mode="lit"]) .sidebar_inner::before{display:none}html:not([data-mode="lit"]) .color_choice::after{background-image:url("../assets/img/night-moon.jpg");transform:translateX(1.4rem)}}@font-face{font-family:'Metropolis';font-style:normal;font-weight:200;src:local("Metropolis Extra Light"),local("Metropolis-Light"),url("../fonts/Metropolis-ExtraLight.woff2") format("woff2"),url("../fonts/Metropolis-ExtraLight.woff") format("woff");font-display:swap}@font-face{font-family:'Metropolis';font-style:italic;font-weight:200;src:local("Metropolis Extra Light Italic"),local("Metropolis-ExtraLightItalic"),url("../fonts/Metropolis-ExtraLightItalic.woff2") format("woff2"),url("../fonts/Metropolis-ExtraLightItalic.woff") format("woff");font-display:swap}@font-face{font-family:'Metropolis';font-style:normal;font-weight:300;src:local("Metropolis Light"),local("Metropolis-Light"),url("../fonts/Metropolis-Light.woff2") format("woff2"),url("../fonts/Metropolis-Light.woff") format("woff");font-display:swap}@font-face{font-family:'Metropolis';font-style:italic;font-weight:300;src:local("Metropolis Light Italic"),local("Metropolis-LightItalic"),url("../fonts/Metropolis-LightItalic.woff2") format("woff2"),url("../fonts/Metropolis-LightItalic.woff") format("woff");font-display:swap}@font-face{font-family:'Metropolis';font-style:normal;font-weight:400;src:local("Metropolis Regular"),local("Metropolis-Regular"),url("../fonts/Metropolis-Regular.woff2") format("woff2"),url("../fonts/Metropolis-Regular.woff") format("woff");font-display:swap}@font-face{font-family:'Metropolis';font-style:italic;font-weight:400;src:local("Metropolis Regular Italic"),local("Metropolis-RegularItalic"),url("../fonts/Metropolis-RegularItalic.woff2") format("woff2"),url("../fonts/Metropolis-RegularItalic.woff") format("woff");font-display:swap}@font-face{font-family:'Metropolis';font-style:normal;font-weight:500;src:local("Metropolis Medium"),local("Metropolis-Medium"),url("../fonts/Metropolis-Medium.woff2") format("woff2"),url("../fonts/Metropolis-Medium.woff") format("woff");font-display:swap}@font-face{font-family:'Metropolis';font-style:italic;font-weight:500;src:local("Metropolis Medium Italic"),local("Metropolis-MediumItalic"),url("../fonts/Metropolis-MediumItalic.woff2") format("woff2"),url("../fonts/Metropolis-MediumItalic.woff") format("woff");font-display:swap}@font-face{font-family:'Metropolis';font-style:normal;font-weight:700;src:local("Metropolis Bold"),local("Metropolis-Bold"),url("../fonts/Metropolis-Bold.woff2") format("woff2"),url("../fonts/Metropolis-Bold.woff") format("woff");font-display:swap}@font-face{font-family:'Metropolis';font-style:italic;font-weight:700;src:local("Metropolis Bold Italic"),local("Metropolis-BoldItalic"),url("../fonts/Metropolis-BoldItalic.woff2") format("woff2"),url("../fonts/Metropolis-BoldItalic.woff") format("woff");font-display:swap}*{box-sizing:border-box;-webkit-appearance:none;margin:0;padding:0}body,html{scroll-behavior:smooth;-webkit-text-size-adjust:100%;font-kerning:normal;-webkit-font-feature-settings:"kern" 1;text-rendering:optimizeLegibility;text-rendering:geometricPrecision;-webkit-text-size-adjust:100%;font-size:100%;scroll-padding-top:4.5rem}body::-webkit-scrollbar-corner,html::-webkit-scrollbar-corner{background-color:transparent}body{font-family:var(--font);background:var(--choice-bg);color:var(--text);font-size:1.1rem;line-height:1.5;max-width:1920px;margin:0 auto;position:relative;display:flex;flex-direction:column;justify-content:space-between;min-height:100vh;font-kerning:normal;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}a{text-decoration:none;color:inherit}a:focus,a:focus-within{outline:none !important}h1,h2,h3,h4,h5{font-family:inherit;font-weight:300;padding:5px 0;margin:15px 0;color:var(--header-text);line-height:1.35}h1:hover .link,h2:hover .link,h3:hover .link,h4:hover .link,h5:hover .link{opacity:1}h1{font-size:200%;font-weight:400}h2{font-size:175%}h3{font-size:150%}h4{font-size:125%}h5{font-size:120%}h6{font-size:100%}img,svg{max-width:100%;vertical-align:middle}img{height:auto;margin:1rem auto;padding:0}img:focus,img:focus-within{outline:none !important;border:none !important}main{flex:1}ul{list-style:none;-webkit-padding-start:0;-moz-padding-start:0}em{font-weight:500}b,strong{font-weight:700}hr{border:none;padding:1px;background:#e7e7e7;opacity:0.5;margin:1rem 0}@media (prefers-color-scheme: dark){hr{background:var(--theme)}}aside h3{position:relative;margin:0 !important}aside ul{list-style:initial;padding-left:1rem}aside li{padding:0.25rem 0}table{width:100%;border-collapse:collapse;background:var(--table-haze);margin-bottom:1.5rem}table:not(.ln-table) t{background:var(--table-bg)}td,th{padding:0.5rem 1rem;border:1px solid var(--table-border)}td,th{padding:0.5rem 1rem;font-weight:400}td:not(:first-child),th:not(:first-child){padding-left:1.5rem}th{font-weight:700}tbody{padding:0}tbody tr:nth-child(even){background-color:var(--table-haze)}tbody tr:nth-child(odd){background-color:var(--table-bg)}blockquote{margin:25px auto;quotes:"“" "”" "‘" "’";padding:1.5rem;color:#555555;padding:1rem 1.5rem;border-left:0.2rem solid #0077b8;position:relative;background:var(--haze)}blockquote+.highlight_wrap{margin-top:2.25rem}p{padding:0.8rem 0}picture{display:block;width:100%}.nav_open+.nav_sub::before,.nav_open+.nav_sub .nav_child:first-child::before{width:0;height:0;border-left:0.33rem solid transparent;border-right:0.33rem solid transparent;top:-0.5rem;left:1rem}.nav{color:#fafafa;display:flex;justify-content:space-between;--maxWidth: 1440px;max-width:var(--maxWidth);margin-left:auto;margin-right:auto}.nav_active{background-color:rgba(255,255,255,0.05);border-radius:0.25rem}.nav_icon{width:0.7rem;margin-left:0.33rem;transition:transform 0.3s var(--ease);transform-origin:50% 50%}.nav_body{display:flex;flex:1}.nav_header{background-color:#002538;padding:0 1.5rem;position:fixed;width:100%;z-index:99;left:0}.nav_item{padding:0.5rem 1rem;display:inline-flex;align-items:center}.nav_sub{width:100%;left:0;position:absolute;z-index:20;border-radius:0 0 0.5rem 0.5rem;top:3rem;transition:height 0.3s ease-in-out;height:0;overflow:hidden;padding:0.96rem 0 0;background:transparent}.nav_parent{position:relative;display:flex;align-items:center;margin:0.25rem 0;border-radius:0.5rem}.nav_open+.nav_sub .nav_child{padding-top:0.5rem;padding-bottom:0.5rem;z-index:3}@media screen and (min-width: 769px){.nav_open+.nav_sub .nav_child+a{padding-top:0}}.nav_open+.nav_sub .nav_child:not(:first-child){position:relative}.nav_open+.nav_sub .nav_child:first-child::before{position:absolute;content:"";border-bottom:0.5rem solid var(--translucent-light);z-index:2}.nav_open+.nav_sub{height:initial;z-index:999;overflow:initial;border-radius:0.5rem;padding-bottom:0.5rem}@media screen and (min-width: 769px){.nav_open+.nav_sub{color:var(--text)}}.nav_open+.nav_sub::before,.nav_open+.nav_sub::after{content:"";position:absolute}.nav_open+.nav_sub::before{z-index:1}@media screen and (min-width: 769px){.nav_open+.nav_sub::before{border-bottom:0.5rem solid var(--choice-bg)}}.nav_open+.nav_sub::after{top:0;left:0;right:0;bottom:0;background:var(--translucent-light);border-radius:0.5rem;box-shadow:0 1rem 3rem rgba(0,0,0,0.25)}@media screen and (min-width: 769px){.nav_open+.nav_sub{background:var(--choice-bg);width:auto;white-space:nowrap}}.nav_open .nav_icon{transform:rotate(180deg)}.nav_sub .nav_item{z-index:5;display:block;padding-top:0.75rem;padding-bottom:0.75rem;transition:background 0.3s ease-out;margin:0}.nav_sub .nav_item:not(.nav_child){position:relative}.nav_brand img{max-width:15rem;margin:0}@media screen and (min-width: 769px){.nav_brand{padding-left:0}.nav_brand img{background:transparent !important}}.nav_center{display:none}@media screen and (min-width: 769px){.nav_center{display:flex;flex:1;align-items:center;justify-content:center}.nav_center+.follow{flex:initial}}@media screen and (min-width: 769px){.nav_hide{display:none}}.nav_close{display:none}.content,.footer{padding:1.5rem}@media screen and (min-width: 1441px){.content,.footer{padding:1.5rem 0}}.content{padding-top:5rem;--maxWidth: 1440px;max-width:var(--maxWidth);margin-left:auto;margin-right:auto}.footer{background:var(--footer-bg);margin-top:2rem;font-size:0.9rem}.footer_inner{--maxWidth: 1440px;max-width:var(--maxWidth);margin-left:auto;margin-right:auto;display:grid;grid-template-columns:4rem 1fr;align-items:center;position:relative}.button{background-color:#0077b8;color:#fff;display:inline-flex;padding:0.5rem 1.5rem;text-transform:uppercase;border:1px solid #0077b8;border-radius:1.5rem;font-size:0.9rem;align-items:center;user-select:none}.button_back{color:#fff;outline:none;border:none;appearance:none;background-color:#0077b8;font-size:1rem;cursor:pointer;padding:0.5rem 1rem;margin-bottom:1.33rem;border-radius:1.5rem}.button:hover,.button:focus{background-color:#003552;color:#fff;border:1px solid #003552}.button_translucent{background-color:rgba(0,119,184,0.15);color:#0077b8;border:1px solid transparent}.button_tally{padding:0 0.75rem;border-radius:0.5rem;background-color:#0077b8;display:inline-flex;justify-content:center;align-items:center;color:#fff;margin:0.1rem 0 0.1rem 0.2rem;font-size:0.7rem}.post_link,.post_title{margin-bottom:0}.post_link{line-height:1}.post_link>a{display:block;line-height:1.35}.posts{margin-top:2rem}.post_header{height:50vh;max-height:35rem;background-color:#002538;background-size:cover;background-position:center;margin-top:4.2rem}@media screen and (max-width: 992px){.post_header{height:40vh;margin-top:3rem}}@media screen and (max-width: 667px){.post_header{height:30vh}}.post_header+.content{padding-top:0}.post_item{margin-bottom:3rem;border-radius:0.5rem;background:var(--post-bg)}.post_tag{padding:0.2rem 0.8rem;font-size:0.8rem}.post_tags{display:none}.post_tags.jswidgetopen{display:initial;position:fixed;top:0;left:0;height:100vh;overflow-y:auto;width:100vw;padding:5rem 1.5rem;background:var(--translucent-light);cursor:pointer;z-index:999;overflow-y:auto}.post_tags_toggle{margin-top:0.5rem;margin-left:0.5rem;cursor:pointer}.post_tag,.post_share{margin:0.5rem}.post_share{display:inline-flex}.post_meta{align-items:stretch}.post_meta,.post_meta span{display:inline-flex;flex-flow:row wrap}.post_meta span{align-items:center;margin-bottom:0.5rem}@media screen and (min-width: 557px){.post_meta span{gap:0.5rem 0}}@media screen and (max-width: 667px){.post_meta span:last-of-type{margin-top:-0.5rem}}@media screen and (min-width: 667px){.post_meta .button{margin:0 0.5rem}}.post_date{margin-right:0.5rem;margin-left:0.25rem}.post_featured{display:block;margin:1rem auto}.post_content a:not(.button){color:#0077b8}.post_content ul,.post_content ol{list-style:initial;padding:0.5rem 1.25rem}.post_content ul li,.post_content ol li{padding-top:0.25rem}.post_content ol{list-style:decimal}.scrollable{display:grid;width:100%;max-width:100%;overflow-x:auto}.to-top{position:fixed;bottom:2rem;right:1.5rem;height:2.25rem;width:2.25rem;background-color:#0077b8;display:flex;align-items:center;justify-content:center;border:none;-webkit-appearance:none;border-radius:50%;color:#fff !important;text-decoration:none !important;font-size:1.25rem;cursor:pointer}@media screen and (max-width: 667px){.to-top{bottom:2.25rem}}.to-top,.to-top:focus{outline:none}.mb-0{margin-bottom:0 !important}.tags_list{cursor:initial;background:var(--choice-bg);padding:4.5rem 1.5rem 1.5rem 1.5rem;border-radius:1rem;max-width:720px;margin:0 auto;box-shadow:0 0.5rem 1.5rem rgba(0,0,0,0.12);position:relative;display:flex;flex-flow:row wrap}.tags_nav{position:relative}.tags_hide{position:absolute;top:1rem;right:1.5rem;padding:0.5rem;border-radius:50%;cursor:pointer}@media screen and (min-width: 992px){.tags_hide{display:none}}.tags_sort{font-size:1rem;color:var(--light);background:var(--theme);position:absolute;top:1.5rem;left:1.5rem;border-radius:1.5rem;padding:0.1rem}.tags_sort,.tags_sort span{user-select:none}.tags_sort span{display:inline-flex;justify-content:center;align-items:center;height:2rem;position:relative;z-index:5;cursor:pointer;width:5rem;font-weight:500}.tags_sort::before{content:"";position:absolute;width:4.5rem;top:0.25rem;bottom:0.25rem;left:0.25rem;z-index:3;background:var(--bg);opacity:0.5;border-radius:1.5rem;transition:0.25s transform var(--ease)}.tags_sort.sorted::before{transform:translateX(5rem)}.tag-title{border-bottom:none !important;display:inline-block !important;position:relative;font-size:2rem;margin-bottom:-1rem}.tag-title::after{content:attr(data-count);margin-left:1.5rem;background-color:#eee;padding:0.25rem 1rem;border-radius:15%;font-size:1.5rem}.icon{display:inline-flex;justify-content:center;align-items:center;margin:0 0.5rem}.icon,.icon img,.icon svg{width:1.1rem;height:1.1rem}.icon_2{width:2.2rem;height:2.2rem}.link{opacity:0;position:relative}.link_owner .icon{background-image:url("../favicon/link.svg");background-size:100%;background-repeat:no-repeat;background-position:center right}.link_yank{opacity:1}.link_yanked{position:absolute;right:-1rem;top:-2rem;background-color:#0077b8;color:#fff;width:7rem;padding:0.25rem 0.5rem;font-size:0.9rem;border-radius:1rem;text-align:center}.link_yanked::after{position:absolute;top:1rem;content:"";border-color:#0077b8 transparent;border-style:solid;border-width:1rem 1rem 0 1rem;height:0;width:0;transform-origin:50% 50%;transform:rotate(145deg);right:0.45rem}.excerpt_header,.excerpt_footer{padding:1rem}.excerpt_footer{padding:0 1rem 2.25rem 1rem}.excerpt_thumbnail{min-height:10rem;display:none}@media screen and (min-width: 769px){.excerpt_thumbnail{display:block;border-radius:0.5rem}}.excerpt_footer.partition{display:grid}@media screen and (min-width: 769px){.excerpt_footer.partition{grid-template-columns:2fr 7fr;grid-gap:1rem}}.sidebar_inner{position:relative}.sidebar_inner::before{content:"";padding:0.5px;top:0;bottom:0;background:linear-gradient(to bottom, var(--haze), var(--light), var(--haze));position:absolute;left:-2rem}.author_header{display:grid;grid-template-columns:3rem 1fr;grid-gap:1rem}.author_bio a{color:#0077b8}.pagination{display:flex}.page-item{padding:0.2rem}.page-item.disabled{opacity:0.7}.page-item:first-child,.page-item:last-child{display:none}.page-item.active a{background-color:#003552}.page-link{padding:0.25rem 0.75rem;background-color:#0077b8;color:#fff;border-radius:1rem}.page_only{display:none !important}.page .page_only{display:initial !important}.round{border-radius:50%;max-width:100%;height:auto;padding:0;vertical-align:middle}.float_left{float:left;margin-right:1rem}.float_left+p{padding-top:0}.float_right{float:right;margin-left:1rem}.float_left::after,.float_right::after{clear:both}.follow{display:flex;align-items:center;flex:1;justify-content:flex-end}.follow svg{fill:#fafafa;margin-left:0.75rem}figcaption{font-style:italic;opacity:0.67;font-size:0.9rem}.to_top{background-color:#0077b8;width:2.75rem;height:2.75rem;display:flex;justify-content:center;align-items:center;cursor:pointer;border-radius:50%;position:fixed;bottom:1.5rem;right:1.5rem;z-index:99}.to_top.ios{position:absolute;bottom:0.75rem;right:0}.to_top:hover{background-color:#0077b8}.to_top svg{fill:#fff;opacity:0.5;transition:0.3s opacity var(--ease)}.to_top:hover svg{opacity:1}.color_mode{height:1.5rem;display:grid;align-items:center;margin:0 0.5rem}@media screen and (min-width: 769px){.color_mode{margin:0 1.5rem;grid-template-columns:1fr}}.color_choice{width:3rem;background-color:var(--translucent-light);border-radius:1rem;height:1.5rem;outline:none;border:none;-webkit-appearance:none;cursor:pointer;position:relative;position:relative;overflow:hidden;box-shadow:0 0.25rem 1rem rgba(0,0,0,0.15)}.color_choice::after{content:"";position:absolute;top:0.1rem;left:0.1rem;width:1.3rem;height:1.3rem;background-image:url("../assets/img/sun.svg");background-position:center;background-size:cover;border-radius:50%;z-index:2}.color_animate{transition:transform 0.5s cubic-bezier(0.075, 0.82, 0.165, 1)}.color_animate::after{transition:transform 0.5s cubic-bezier(0.19, 1, 0.22, 1);will-change:transform}.taxonomy{text-transform:capitalize}.image-scale{position:fixed;z-index:999999;left:0;right:0;height:100vh;top:0;padding:1.5rem;background-color:var(--bg);display:grid;align-items:center;overflow:auto}.image-scale .image-scalable{background-color:var(--text)}.image-scalable{cursor:pointer;transition:transform 0.3s var(--ease)}.image_featured{display:block;margin-left:auto !important;margin-right:auto !important}.image_thumbnail{margin:0}.video{overflow:hidden;padding-bottom:56.25%;position:relative;height:0;margin:1.5rem 0;border-radius:0.6rem;background-color:var(--bg);box-shadow:0 1rem 2rem rgba(0,0,0,0.17)}.video iframe{left:0;top:0;height:100%;width:100%;border:none;position:absolute;transform:scale(1.02)}.notices{border-top-width:2rem;border-top-style:solid;color:#666;margin:2rem 0;padding-bottom:.1px;padding-left:1rem;padding-right:1rem}.notices .label{color:#fff;margin-top:-1.75rem;font-weight:bold}.notices .label:first-child::before{font-weight:900;margin-left:-.35rem;margin-right:.35rem}.notices.info{border-color:var(--notice-info-border-color);background:var(--notice-info-background)}.notices.warning{border-color:var(--notice-warning-border-color);background:var(--notice-warning-background)}.notices.image-warning{margin:0}.notices.note{border-color:var(--notice-note-border-color);background:var(--notice-note-background)}.notices.tip{border-color:var(--notice-tip-border-color);background:var(--notice-tip-background)}.notices .highlight_wrap{background:var(--notice-code-bg) !important}.search{flex:1;display:flex;justify-content:flex-end;position:relative;max-width:25rem;margin:0.5rem 0 0;--border: transparent}.search_field{padding:0.5rem 1rem;width:100%;outline:none;color:var(--text);background:var(--post-bg);border:1px solid var(--border);border-radius:8px;font-size:1rem;box-shadow:0 0.25rem 1rem rgba(0,0,0,0.1)}.search_field:focus+.search_label{opacity:0}.search_label{position:absolute;z-index:9;opacity:0.67;right:0.67rem;top:0.25rem;width:1rem;height:1rem}.search_label svg{width:100%;height:100%;fill:#7C849B}.search_result{padding:0.5rem 1rem}.search_result:not(.passive):hover{background-color:var(--code-bg);color:#fff}.search_result.passive{display:grid}.search_results{width:100%;background-color:var(--choice-bg);color:var(--text);border-radius:var(--radius);box-shadow:0 1rem 4rem rgba(0,0,0,0.17) !important;position:absolute;top:125%;display:grid;overflow:hidden;z-index:3}.search_results:empty{display:none}.search_title{padding:0.25rem 1rem !important;background-color:#0077b8;color:var(--light);margin:0;font-size:1.25rem}.search_title:empty{display:none}.search_submit{position:absolute;--margin: 3px;right:var(--margin);top:var(--margin);bottom:var(--margin);z-index:9;cursor:pointer;border-radius:calc(var(--radius) / 2)}#results .search_title,#results .search_result{padding:0.5rem 0}.openstreetmap{border:none}.pt-1{padding-top:1.5rem}.pb-1{padding-bottom:1.5rem}.mt-1{margin-top:1.5rem}.mb-1{margin-bottom:1.5rem}.pt-2{padding-top:3rem}.pb-2{padding-bottom:3rem}.mt-2{margin-top:3rem}.mb-2{margin-bottom:3rem}.flex{display:flex;flex-direction:column;align-items:center}.shadow{box-shadow:0 0 60px rgba(0,0,0,0.17)}@media screen and (min-width: 42rem){.grid-2,.grid-3,.grid-4,.grid-auto,.grid-inverse{display:grid;grid-template-columns:1fr}[class*='grid-']{grid-gap:2rem}.grid-inverse{grid-template-columns:70% 1fr;grid-column-gap:4rem}.grid-2{grid-template-columns:1fr 1fr}.grid-3{grid-template-columns:repeat(auto-fit, minmax(19rem, 1fr))}.grid-4{grid-template-columns:repeat(auto-fit, minmax(16rem, 1fr))}}.facebook svg{fill:#325c94}.twitter svg{fill:#00abdc}.linkedin svg{fill:#007bb6}.never{height:75vh;display:flex;justify-content:center;align-items:center;flex-direction:column;padding:1.5rem;text-align:center}.inline{display:inline;margin:0}.hidden{display:none}@media screen and (max-width: 769px){.nav,.nav_body{flex-direction:column}.nav_body{position:fixed;width:90%;max-width:16.5rem;top:0;bottom:0;background-color:#002538;transition:transform 0.3s var(--easing)}.nav_body_right{transform:translateX(100vw);right:0}.nav_body_left{transform:translateX(-100vw);left:0}.nav_close{width:3rem;position:absolute;right:-4rem;top:0;bottom:0;height:100%;cursor:pointer;z-index:1000;display:flex;justify-content:center;align-items:center}.nav_close svg{width:1.25rem;fill:var(--light);height:1.25rem;display:none}.nav_close svg:first-child{display:initial}.nav_close svg.isopen{display:none}.nav_close svg.isopen+svg{display:initial}.nav_brand{position:relative;z-index:999;width:calc(100% - 3rem);padding-left:0}.nav_parent{display:grid}.nav_sub{position:relative;top:initial;padding-top:0}.jsopen::after{content:"";position:fixed;z-index:2;background-color:rgba(0,0,0,0.3);top:0;left:0;right:0;bottom:0}.jsopen .nav_body{transform:translateX(0);padding-left:1.5rem;padding-right:1.5rem}.jsopen .nav_parent:first-child{margin-top:4.4rem}.jsopen .nav .follow{justify-content:flex-start;flex:initial;margin-top:0.75rem}}@keyframes pulse{0%{opacity:1}75%{opacity:0.1}100%{opacity:1}}code{font-size:85%;font-weight:400;overflow-y:hidden;display:block;font-family:'Monaco', monospace;word-break:break-all}code.noClass{--inlineColor: rgb(194, 29, 0);color:var(--inlineColor);display:inline;line-break:anywhere}.windows .highlight{overflow-x:hidden}.windows .highlight:hover{overflow-x:auto}.highlight{display:grid;width:100%;border-radius:0 0.2rem 0.2rem 0;overflow-x:auto;position:relative}.highlight_wrap{background:var(--code-bg) !important;border-radius:0.5rem;position:relative;padding:0 1rem;margin:1.5rem auto 1rem auto}.highlight_wrap+.highlight_wrap{margin-top:2.25rem}.highlight_wrap:hover>div{opacity:1}.highlight_wrap .lang{position:absolute;top:0;right:0;text-align:right;width:7.5rem;padding:0.5rem 1rem;font-style:italic;text-transform:uppercase;font-size:67%;opacity:0.5;color:var(--light)}.highlight_wrap:hover .lang{opacity:0.1}.highlight .highlight{margin:0}.highlight pre{color:var(--light) !important;border-radius:4px;font-family:'Monaco', monospace;padding-top:1.5rem;padding-bottom:2rem}.highlight table{display:grid;max-width:100%;margin-bottom:0;background:transparent}.highlight td,.highlight th{padding:0}.highlight .lntd{width:100%;border:none}.highlight .lntd:first-child,.highlight .lntd:first-child pre{width:2.5rem !important;padding-left:0;padding-right:0;color:rgba(255,255,255,0.5);user-select:none}.highlight .lntd:first-child pre{width:100%;display:flex;align-items:center;flex-direction:column}.err{color:#a61717;background-color:#e3d2d2}.hl{width:100%;background-color:rgba(255,255,255,0.25)}.ln,.lnt{margin-right:0.75rem;padding:0;transition:opacity 0.3s var(--ease)}.ln,.ln span,.lnt,.lnt span{color:rgba(255,255,255,0.5);user-select:none}.k,.kc,.kd,.kn,.kp,.kr,.kt,.nt{color:#6ab825;font-weight:500}.kn,.kp{font-weight:400}.nb,.no,.nv{color:#24909d}.nc,.nf,.nn{color:#447fcf}.s,.sa,.sb,.sc,.dl,.sd,.s2,.se,.sh,.si,.sx,.sr,.s1,.ss{color:#ed9d13}.m,.mb,.mf,.mh,.mi,.il,.mo{color:#3677a9}.ow{color:#6ab825;font-weight:500}.c,.ch,.cm,.c1{color:#999;font-style:italic}.cs{color:#e50808;background-color:#520000;font-weight:500}.cp,.cpf{color:#cd2828;font-weight:500}.gd,.gr{color:#d22323}.ge{font-style:italic}.gh,.gu,.nd,.na,.ne{color:#ffa500;font-weight:500}.gi{color:#589819}.go{color:#ccc}.gp{color:#aaa}.gs{font-weight:500}.gt{color:#d22323}.w{color:#666}.hljs-string{color:#6ab825}.hljs-attr{color:#ed9d13}.p .hljs-attr{color:var(--light)}.pre_wrap{white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word}.pre_nolines.line .ln{display:none}.panel_box{display:inline-flex;perspective:300px;grid-gap:0.5rem;transition:opacity 0.3s var(--easing);background:var(--code-bg);padding:0.5rem 1.5rem;border-radius:2rem;align-items:center;position:absolute;right:0rem;top:-2.1rem;opacity:0}.panel_icon{display:inline-flex;align-items:center;justify-content:center;cursor:pointer;padding:0.1rem;transform-origin:50% 50%;background-size:100%;background-repeat:no-repeat}.panel_icon.active{animation:pulse 0.1s linear}.panel_icon svg{fill:var(--light);width:1.5rem;height:1.5rem}.panel_hide{display:none}.panel_from{position:absolute;color:var(--theme);bottom:0;font-size:1.5rem;font-weight:500;padding:0.5rem 0;cursor:pointer;letter-spacing:0.1px;z-index:19}.panel_expanded .panel_from{display:none} + +/*# sourceMappingURL=styles.css.map */ \ No newline at end of file diff --git a/css/styles.css.map b/css/styles.css.map new file mode 100644 index 0000000..567d36e --- /dev/null +++ b/css/styles.css.map @@ -0,0 +1,31 @@ +{ + "version": 3, + "file": "styles.css", + "sourceRoot": "/home/mighten/Mighten.github.io", + "sources": [ + "themes/hugo-clarity/assets/sass/main.sass", + "themes/hugo-clarity/assets/sass/_variables.sass", + "themes/hugo-clarity/assets/sass/_override.sass", + "themes/hugo-clarity/assets/sass/_fonts.sass", + "themes/hugo-clarity/assets/sass/_base.sass", + "themes/hugo-clarity/assets/sass/_components.sass", + "themes/hugo-clarity/assets/sass/_utils.sass", + "themes/hugo-clarity/assets/sass/_mobile.sass", + "themes/hugo-clarity/assets/sass/_syntax.sass", + "themes/hugo-clarity/assets/sass/_custom.sass" + ], + "sourcesContent": [ + "$baseURL: 'https://mighten.github.io/';\n$fontsPath: '../fonts/';\n$imagesPath: '../assets/img/';\n$iconsPath: '../favicon/';\n@import 'variables';\n@import 'override';\n@import 'fonts';\n@import 'base';\n@import 'components';\n@import 'utils';\n@import 'mobile';\n@import 'syntax';\n@import 'custom';\n", + "$light: #fff;\n$haze: #fafafa;\n$xhaze: darken($haze, 11%);\n$bg: #002538;\n$theme: #0077b8;\n$mobile-menu-breakpoint: 769px;\n$single-column-breakpoint: 42rem;\n\n@mixin content() {\n --maxWidth: 1440px;\n max-width: var(--maxWidth);\n margin-left: auto;\n margin-right: auto; }\n\n@mixin viewport($width: 1024px, $margin: 25px) {\n max-width: $width;\n margin: $margin auto;\n @content; }\n\n@mixin shadow($opacity: 0.17) {\n box-shadow: 0 0 3rem rgba(0,0,0,$opacity);\n &:hover {\n box-shadow: 0 0 5rem rgba(0,0,0, (1.5 * $opacity)); } }\n\nhtml {\n --color-mode: 'lit';\n --light: #fff;\n --dark: #000;\n --bg: #002538;\n --haze: #f2f2f2;\n --gray: #020202;\n --accent: var(--gray);\n --text: #575757;\n --header-text: var(--dark);\n --font: Metropolis, sans-serif;\n --theme: #0077b8;\n --ease: cubic-bezier(.19,1,.22,1);\n --code-bg: var(--bg);\n --table-bg: var(--light);\n --table-haze: var(--haze);\n --table-border: #dedede;\n --footer-bg: var(--haze);\n --shadow: rgba(0,0,0,0.12);\n --translucent: rgba(0,0,0,0.05);\n --translucent-light: rgba(255,255,255,0.05);\n --post-bg: var(--light);\n --choice-bg: var(--haze);\n --ease: cubic-bezier(0.39, 0.575, 0.565, 1);\n --easing: cubic-bezier(.19,1,.22,1);\n --notice-code-bg: var(--bg);\n --notice-info-border-color: #6AB0DE;\n --notice-info-background: #E7F2FA;\n --notice-note-border-color: #F0B37E;\n --notice-note-background: #FFF2DB;\n --notice-tip-border-color: rgba(92, 184, 92, 0.8);\n --notice-tip-background: #E6F9E6;\n --notice-warning-border-color: rgba(217, 83, 79, 0.8);\n --notice-warning-background: #FAE2E2;\n\n &.page {\n --choice-bg: var(--light); }\n @mixin darkmode {\n --light: hsla(0,0%,100%,0.87);\n --color-mode: 'dim';\n --text: var(--light);\n --accent: var(--bubble);\n --choice-bg: var(--bg);\n --code-bg: var(--translucent-light);\n --header-text: var(--light);\n --table-bg: var(--code-bg);\n --table-haze: rgba(255,255,255,0.1);\n --table-border: var(--code-bg);\n --footer-bg: var(--bg);\n --post-bg: var(--translucent-light);\n * {\n } } // box-shadow: none !important\n\n &[data-mode=\"dim\"] {\n @include darkmode;\n blockquote {\n background: var(--translucent-light);\n color: #dedede; }\n svg.icon {\n fill: var(--light); }\n .icon {\n img {\n background: none; }\n svg {\n fill: #fafafa; } }\n .sidebar {\n &_inner {\n &::before {\n display: none; } } }\n .color {\n &_choice {\n &::after {\n background-image: url(\"#{$imagesPath}night-moon.jpg\");\n transform: translateX(1.4rem); } } } }\n\n @media (prefers-color-scheme: dark) {\n\n &:not([data-mode=\"lit\"]) {\n @include darkmode;\n blockquote {\n background: var(--translucent-light);\n color: #dedede; }\n svg.icon {\n fill: var(--light); }\n .icon {\n img {\n background: none; }\n svg {\n fill: #fafafa; } }\n .sidebar {\n &_inner {\n &::before {\n display: none; } } }\n .color {\n &_choice {\n &::after {\n background-image: url(\"#{$imagesPath}night-moon.jpg\");\n transform: translateX(1.4rem); } } } } } }\n", + "// override clarity theme's _variables.sass file.\n// we recommend not editing this file directly. Instead, create an `assets/sass/_override.sass` file at the root level of your site.\n// if you edit this file directly, you will have to resolve git conflicts when and if you decide to pull changes we make on the theme\n", + "@font-face {\n font-family: 'Metropolis';\n font-style: normal;\n font-weight: 200;\n src: local('Metropolis Extra Light'), local('Metropolis-Light'), url('#{$fontsPath}Metropolis-ExtraLight.woff2') format('woff2'), url('#{$fontsPath}Metropolis-ExtraLight.woff') format('woff');\n font-display: swap; }\n\n@font-face {\n font-family: 'Metropolis';\n font-style: italic;\n font-weight: 200;\n src: local('Metropolis Extra Light Italic'), local('Metropolis-ExtraLightItalic'), url('#{$fontsPath}Metropolis-ExtraLightItalic.woff2') format('woff2'), url('#{$fontsPath}Metropolis-ExtraLightItalic.woff') format('woff');\n font-display: swap; }\n\n@font-face {\n font-family: 'Metropolis';\n font-style: normal;\n font-weight: 300;\n src: local('Metropolis Light'), local('Metropolis-Light'), url('#{$fontsPath}Metropolis-Light.woff2') format('woff2'), url('#{$fontsPath}Metropolis-Light.woff') format('woff');\n font-display: swap; }\n\n@font-face {\n font-family: 'Metropolis';\n font-style: italic;\n font-weight: 300;\n src: local('Metropolis Light Italic'), local('Metropolis-LightItalic'), url('#{$fontsPath}Metropolis-LightItalic.woff2') format('woff2'), url('#{$fontsPath}Metropolis-LightItalic.woff') format('woff');\n font-display: swap; }\n\n@font-face {\n font-family: 'Metropolis';\n font-style: normal;\n font-weight: 400;\n src: local('Metropolis Regular'), local('Metropolis-Regular'), url('#{$fontsPath}Metropolis-Regular.woff2') format('woff2'), url('#{$fontsPath}Metropolis-Regular.woff') format('woff');\n font-display: swap; }\n\n@font-face {\n font-family: 'Metropolis';\n font-style: italic;\n font-weight: 400;\n src: local('Metropolis Regular Italic'), local('Metropolis-RegularItalic'), url('#{$fontsPath}Metropolis-RegularItalic.woff2') format('woff2'), url('#{$fontsPath}Metropolis-RegularItalic.woff') format('woff');\n font-display: swap; }\n\n@font-face {\n font-family: 'Metropolis';\n font-style: normal;\n font-weight: 500;\n src: local('Metropolis Medium'), local('Metropolis-Medium'), url('#{$fontsPath}Metropolis-Medium.woff2') format('woff2'), url('#{$fontsPath}Metropolis-Medium.woff') format('woff');\n font-display: swap; }\n\n@font-face {\n font-family: 'Metropolis';\n font-style: italic;\n font-weight: 500;\n src: local('Metropolis Medium Italic'), local('Metropolis-MediumItalic'), url('#{$fontsPath}Metropolis-MediumItalic.woff2') format('woff2'), url('#{$fontsPath}Metropolis-MediumItalic.woff') format('woff');\n font-display: swap; }\n\n@font-face {\n font-family: 'Metropolis';\n font-style: normal;\n font-weight: 700;\n src: local('Metropolis Bold'), local('Metropolis-Bold'), url('#{$fontsPath}Metropolis-Bold.woff2') format('woff2'), url('#{$fontsPath}Metropolis-Bold.woff') format('woff');\n font-display: swap; }\n\n@font-face {\n font-family: 'Metropolis';\n font-style: italic;\n font-weight: 700;\n src: local('Metropolis Bold Italic'), local('Metropolis-BoldItalic'), url('#{$fontsPath}Metropolis-BoldItalic.woff2') format('woff2'), url('#{$fontsPath}Metropolis-BoldItalic.woff') format('woff');\n font-display: swap; }\n", + "* {\n box-sizing: border-box;\n -webkit-appearance: none;\n margin: 0;\n padding: 0; }\n\nbody, html {\n scroll-behavior: smooth;\n -webkit-text-size-adjust: 100%;\n font-kerning: normal;\n -webkit-font-feature-settings: \"kern\" 1;\n text-rendering: optimizeLegibility;\n text-rendering: geometricPrecision;\n -webkit-text-size-adjust: 100%;\n font-size: 100%;\n scroll-padding-top: 4.5rem;\n &::-webkit-scrollbar-corner {\n background-color: transparent; } }\nbody {\n font-family: var(--font);\n background: var(--choice-bg);\n color: var(--text);\n font-size: 1.1rem;\n line-height: 1.5;\n max-width: 1920px;\n margin: 0 auto;\n position: relative;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n min-height: 100vh;\n font-kerning: normal;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale; }\na {\n text-decoration: none;\n color: inherit;\n &:focus, &:focus-within {\n outline: none !important; } }\n\nh1,h2,h3,h4,h5 {\n font-family: inherit;\n font-weight: 300;\n padding: 5px 0;\n margin: 15px 0;\n color: var(--header-text);\n line-height: 1.35;\n &:hover .link {\n opacity: 1; } }\n\nh1 {\n font-size: 200%;\n font-weight: 400; }\nh2 {\n font-size: 175%; }\nh3 {\n font-size: 150%; }\nh4 {\n font-size: 125%; }\nh5 {\n font-size: 120%; }\nh6 {\n font-size: 100%; }\nimg, svg {\n max-width: 100%;\n vertical-align: middle; }\nimg {\n height: auto;\n margin: 1rem auto;\n padding: 0;\n &:focus, &:focus-within {\n outline: none !important;\n border: none !important; } }\n\nmain {\n flex: 1; }\n\nul {\n list-style: none;\n -webkit-padding-start: 0;\n -moz-padding-start: 0; }\n\nem {\n font-weight: 500; }\n\nb, strong {\n font-weight: 700; }\n\nhr {\n border: none;\n padding: 1px;\n background: darken($haze, 7.5%);\n opacity: 0.5;\n margin: 1rem 0;\n @media (prefers-color-scheme: dark) {\n background: var(--theme); } }\n\naside {\n h3 {\n position: relative;\n margin: 0 !important; }\n ul {\n list-style: initial;\n padding-left: 1rem; }\n li {\n padding: 0.25rem 0; } }\n\ntable {\n width: 100%;\n border-collapse: collapse;\n background: var(--table-haze);\n // border-style: hidden\n margin-bottom: 1.5rem;\n &:not(.ln-table) t {\n background: var(--table-bg); } }\n\ntd, th {\n padding: 0.5rem 1rem;\n border: 1px solid var(--table-border); }\n\ntd,\nth {\n padding: 0.5rem 1rem;\n font-weight: 400;\n &:not(:first-child) {\n padding-left: 1.5rem; } }\n\nth {\n font-weight: 700; }\n\ntbody {\n padding: 0;\n tr {\n &:nth-child(even) {\n background-color: var(--table-haze); }\n &:nth-child(odd) {\n background-color: var(--table-bg); } } }\n\nblockquote {\n margin: 25px auto;\n quotes: '\\201C''\\201D''\\2018''\\2019';\n padding: 1.5rem;\n color: #555555;\n padding: 1rem 1.5rem;\n border-left: 0.2rem solid $theme;\n position: relative;\n background: var(--haze);\n + .highlight_wrap {\n margin-top: 2.25rem; } }\np {\n padding: 0.8rem 0; }\n\npicture {\n display: block;\n width: 100%; }\n", + "%upcaret {\n width: 0;\n height: 0;\n border-left: 0.33rem solid transparent;\n border-right: 0.33rem solid transparent;\n top: -0.5rem;\n left: 1rem; }\n.nav {\n color: $haze;\n display: flex;\n justify-content: space-between;\n @include content;\n &_active {\n background-color: rgba($light, 0.05);\n border-radius: 0.25rem; }\n &, &_body {}\n &_icon {\n width: 0.7rem;\n margin-left: 0.33rem;\n transition: transform 0.3s var(--ease);\n transform-origin: 50% 50%; }\n &_body {\n display: flex;\n flex: 1; }\n &_header {\n background-color: $bg;\n padding: 0 1.5rem;\n position: fixed;\n width: 100%;\n z-index: 99;\n left: 0; }\n &_item {\n padding: 0.5rem 1rem;\n display: inline-flex;\n align-items: center; }\n &_sub {\n width: 100%;\n left: 0;\n position: absolute;\n z-index: 20;\n border-radius: 0 0 0.5rem 0.5rem;\n top: 3rem;\n transition: height 0.3s ease-in-out;\n height: 0;\n overflow: hidden;\n padding: 0.96rem 0 0;\n background: transparent; }\n\n &_parent {\n position: relative;\n display: flex;\n align-items: center;\n margin: 0.25rem 0;\n border-radius: 0.5rem; }\n\n &_open + &_sub &_child {\n padding-top: 0.5rem;\n padding-bottom: 0.5rem;\n z-index: 3;\n & + a {\n @media screen and (min-width: $mobile-menu-breakpoint) {\n padding-top: 0; } }\n &:not(:first-child) {\n position: relative; }\n &:first-child::before {\n position: absolute;\n content: \"\";\n @extend %upcaret;\n border-bottom: 0.5rem solid var(--translucent-light);\n z-index: 2; } }\n &_open + &_sub {\n height: initial;\n z-index: 999;\n overflow: initial;\n border-radius: 0.5rem;\n padding-bottom: 0.5rem;\n @media screen and (min-width: $mobile-menu-breakpoint) {\n color: var(--text); }\n &::before, &::after {\n content: \"\";\n position: absolute; }\n &::before {\n @extend %upcaret;\n z-index: 1;\n @media screen and (min-width: $mobile-menu-breakpoint) {\n border-bottom: 0.5rem solid var(--choice-bg); } }\n &::after {\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--translucent-light);\n border-radius: 0.5rem;\n box-shadow: 0 1rem 3rem rgba(0,0,0,0.25); }\n @media screen and (min-width: $mobile-menu-breakpoint) {\n background: var(--choice-bg);\n width: auto;\n white-space: nowrap; } }\n &_open &_icon {\n transform: rotate(180deg); }\n\n &_sub &_item {\n &:not(.nav_child) {\n position: relative; }\n z-index: 5;\n display: block;\n padding-top: 0.75rem;\n padding-bottom: 0.75rem;\n transition: background 0.3s ease-out;\n margin: 0; }\n\n &_brand {\n img {\n max-width: 15rem;\n margin: 0; }\n @media screen and (min-width: $mobile-menu-breakpoint) {\n padding-left: 0;\n // margin-left: -16rem\n // transform: translateX(50rem)\n img {\n background: transparent !important; } } }\n\n &_center {\n display: none;\n @media screen and (min-width: $mobile-menu-breakpoint) {\n display: flex;\n flex: 1;\n align-items: center;\n justify-content: center;\n + .follow {\n flex: initial; } } }\n\n &_hide {\n @media screen and (min-width: $mobile-menu-breakpoint) {\n display: none; } }\n &_close {\n display: none; } }\n\n.content, .footer {\n padding: 1.5rem;\n @media screen and (min-width: 1441px) {\n padding: 1.5rem 0; } }\n\n.content {\n padding-top: 5rem;\n @include content; }\n\n.footer {\n // border-top: 1px solid $xhaze\n background: var(--footer-bg);\n margin-top: 2rem;\n font-size: 0.9rem;\n &_inner {\n @include content;\n display: grid;\n grid-template-columns: 4rem 1fr;\n align-items: center;\n position: relative; } }\n\n.button {\n background-color: $theme;\n color: $light;\n display: inline-flex;\n padding: 0.5rem 1.5rem;\n text-transform: uppercase;\n border: 1px solid $theme;\n border-radius: 1.5rem;\n font-size: 0.9rem;\n align-items: center;\n user-select: none;\n &_back {\n color: $light;\n outline: none;\n border: none;\n appearance: none;\n background-color: $theme;\n font-size: 1rem;\n cursor: pointer;\n padding: 0.5rem 1rem;\n margin-bottom: 1.33rem;\n border-radius: 1.5rem; }\n &:hover, &:focus {\n background-color: darken($theme, 20%);\n color: $light;\n border: 1px solid darken($theme, 20%); }\n\n &_translucent {\n background-color: rgba($theme, 0.15);\n color: $theme;\n border: 1px solid transparent; }\n &_tally {\n padding: 0 0.75rem;\n border-radius: 0.5rem;\n background-color: $theme;\n display: inline-flex;\n justify-content: center;\n align-items: center;\n color: $light;\n margin: 0.1rem 0 0.1rem 0.2rem;\n font-size: 0.7rem; } }\n\n.post {\n &_link, &_title {\n margin-bottom: 0; }\n &_link {\n line-height: 1;\n > a {\n display: block;\n line-height: 1.35; } }\n &s {\n margin-top: 2rem; }\n &_header {\n height: 50vh;\n max-height: 35rem;\n background-color: $bg;\n // background-image: url(#{$imagesPath}island.jpg)\n background-size: cover;\n background-position: center;\n margin-top: 4.2rem;\n @media screen and (max-width: 992px) {\n height: 40vh;\n margin-top: 3rem; }\n @media screen and (max-width: 667px) {\n height: 30vh; }\n & + .content {\n padding-top: 0; } }\n &_item {\n // box-shadow: 0 2.25rem 1.25rem -1.25rem var(--shadow)\n margin-bottom: 3rem;\n border-radius: 0.5rem;\n background: var(--post-bg); }\n &_tag {\n padding: 0.2rem 0.8rem;\n font-size: 0.8rem;\n &s {\n display: none;\n &.jswidgetopen {\n display: initial;\n position: fixed;\n top: 0;\n left: 0;\n height: 100vh;\n overflow-y: auto;\n width: 100vw;\n padding: 5rem 1.5rem;\n background: var(--translucent-light);\n cursor: pointer;\n z-index: 999;\n overflow-y: auto; }\n &_toggle {\n margin-top: 0.5rem;\n margin-left: 0.5rem;\n cursor: pointer; } } }\n &_tag, &_share {\n margin: 0.5rem; }\n &_share {\n display: inline-flex; }\n &_meta {\n align-items: stretch;\n &, span {\n display: inline-flex;\n flex-flow: row wrap; }\n span {\n align-items: center;\n margin-bottom: 0.5rem;\n @media screen and (min-width: 557px) {\n gap: 0.5rem 0; }\n &:last-of-type {\n @media screen and (max-width: 667px) {\n margin-top: -0.5rem; } } }\n .button {\n @media screen and (min-width: 667px) {\n margin: 0 0.5rem; } } }\n\n &_date {\n margin-right: 0.5rem;\n margin-left: 0.25rem; }\n &_featured {\n display: block;\n margin: 1rem auto; }\n &_content {\n a:not(.button) {\n color: $theme; }\n ul, ol {\n list-style: initial;\n padding: 0.5rem 1.25rem;\n li {\n padding-top: 0.25rem; } }\n ol {\n list-style: decimal; } } }\n\n.scrollable {\n display: grid;\n width: 100%;\n max-width: 100%;\n overflow-x: auto; }\n\n.to-top {\n position: fixed;\n bottom: 2rem;\n @media screen and (max-width: 667px) {\n bottom: 2.25rem; }\n right: 1.5rem;\n height: 2.25rem;\n width: 2.25rem;\n background-color: $theme;\n display: flex;\n align-items: center;\n justify-content: center;\n border: none;\n -webkit-appearance: none;\n border-radius: 50%;\n color: $light !important;\n text-decoration: none !important;\n font-size: 1.25rem;\n cursor: pointer;\n &, &:focus {\n outline: none; } }\n\n.mb-0 {\n margin-bottom: 0 !important; }\n\n.tag {\n &s {\n &_list {\n cursor: initial;\n background: var(--choice-bg);\n padding: 4.5rem 1.5rem 1.5rem 1.5rem;\n border-radius: 1rem;\n max-width: 720px;\n margin: 0 auto;\n box-shadow: 0 0.5rem 1.5rem rgba(0,0,0,0.12);\n position: relative;\n display: flex;\n flex-flow: row wrap; }\n &_nav {\n position: relative; }\n &_hide {\n position: absolute;\n top: 1rem;\n right: 1.5rem;\n padding: 0.5rem;\n border-radius: 50%;\n cursor: pointer;\n @media screen and (min-width: 992px) {\n display: none; } }\n &_sort {\n font-size: 1rem;\n color: var(--light);\n background: var(--theme);\n position: absolute;\n top: 1.5rem;\n left: 1.5rem;\n border-radius: 1.5rem;\n padding: 0.1rem;\n &, span {\n user-select: none; }\n span {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n height: 2rem;\n position: relative;\n z-index: 5;\n cursor: pointer;\n width: 5rem;\n font-weight: 500; }\n &::before {\n content: \"\";\n position: absolute;\n width: 4.5rem;\n top: 0.25rem;\n bottom: 0.25rem;\n left: 0.25rem;\n z-index: 3;\n background: var(--bg);\n opacity: 0.5;\n border-radius: 1.5rem;\n transition: 0.25s transform var(--ease); }\n &.sorted {\n &::before {\n transform: translateX(5rem); } } } }\n &-title {\n border-bottom: none !important;\n display: inline-block !important;\n position: relative;\n font-size: 2rem;\n margin-bottom: -1rem;\n &::after {\n content: attr(data-count);\n margin-left: 1.5rem;\n background-color: #eee;\n padding: 0.25rem 1rem;\n border-radius: 15%;\n font-size: 1.5rem; } } }\n\n.icon {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n margin: 0 0.5rem;\n &, img, svg {\n width: 1.1rem;\n height: 1.1rem; }\n &_2 {\n width: 2.2rem;\n height: 2.2rem; } }\n.link {\n opacity: 0;\n position: relative;\n &_owner {\n .icon {\n background-image: url('#{$iconsPath}link.svg');\n background-size: 100%;\n background-repeat: no-repeat;\n background-position: center right; } }\n &_yank {\n opacity: 1;\n &ed {\n position: absolute;\n right: -1rem;\n top: -2rem;\n background-color: $theme;\n color: $light;\n width: 7rem;\n padding: 0.25rem 0.5rem;\n font-size: 0.9rem;\n border-radius: 1rem;\n text-align: center;\n &::after {\n position: absolute;\n top: 1rem;\n content: \"\";\n border-color: $theme transparent;\n border-style: solid;\n border-width: 1rem 1rem 0 1rem;\n height: 0;\n width: 0;\n transform-origin: 50% 50%;\n transform: rotate(145deg);\n right: 0.45rem; } } } }\n\n.excerpt {\n &_header, &_footer {\n padding: 1rem; }\n &_footer {\n padding: 0 1rem 2.25rem 1rem; }\n &_thumbnail {\n min-height: 10rem;\n display: none;\n @media screen and (min-width: $mobile-menu-breakpoint) {\n display: block;\n border-radius: 0.5rem; } }\n &_footer {\n &.partition {\n display: grid;\n @media screen and (min-width: $mobile-menu-breakpoint) {\n grid-template-columns: 2fr 7fr;\n grid-gap: 1rem; } } } }\n.sidebar {\n &_inner {\n position: relative;\n &::before {\n content: \"\";\n padding: 0.5px;\n top: 0;\n bottom: 0;\n // background: var(--light)\n background: linear-gradient(to bottom, var(--haze), var(--light), var(--haze));\n position: absolute;\n left: -2rem {\n } } } } // display: none\n\n.author {\n &_header {\n display: grid;\n grid-template-columns: 3rem 1fr;\n grid-gap: 1rem; }\n &_bio {\n a {\n color: $theme; } } }\n\n.pagination {\n display: flex; }\n\n.page {\n &-item {\n padding: 0.2rem;\n &.disabled {\n opacity: 0.7; }\n &:first-child, &:last-child {\n display: none; }\n &.active a {\n background-color: darken($theme, 20%); } }\n &-link {\n padding: 0.25rem 0.75rem;\n background-color: $theme;\n color: $light;\n border-radius: 1rem; }\n &_only {\n display: none !important; }\n & &_only {\n display: initial !important; } }\n\n.round {\n border-radius: 50%;\n max-width: 100%;\n height: auto;\n padding: 0;\n vertical-align: middle; }\n\n.float {\n &_left {\n float: left;\n margin-right: 1rem;\n + p {\n padding-top: 0; } }\n &_right {\n float: right;\n margin-left: 1rem; }\n &_left, &_right {\n &::after {\n clear: both; } } }\n\n.follow {\n display: flex;\n align-items: center;\n flex: 1;\n justify-content: flex-end;\n svg {\n fill: $haze;\n margin-left: 0.75rem; } }\n\nfigcaption {\n font-style: italic;\n opacity: 0.67;\n font-size: 0.9rem; }\n\n.to {\n &_top {\n background-color: $theme;\n width: 2.75rem;\n height: 2.75rem;\n display: flex;\n justify-content: center;\n align-items: center;\n cursor: pointer;\n border-radius: 50%;\n position: fixed;\n bottom: 1.5rem;\n right: 1.5rem;\n z-index: 99;\n &.ios {\n position: absolute;\n bottom: 0.75rem;\n right: 0; }\n &:hover {\n background-color: $theme; }\n svg {\n fill: $light;\n opacity: 0.5;\n transition: 0.3s opacity var(--ease); }\n &:hover svg {\n opacity: 1; } } }\n\n.color {\n &_mode {\n // width: 3rem\n height: 1.5rem;\n display: grid;\n align-items: center;\n margin: 0 0.5rem;\n @media screen and (min-width: $mobile-menu-breakpoint) {\n margin: 0 1.5rem;\n grid-template-columns: 1fr; } }\n\n &_choice {\n width: 3rem;\n background-color: var(--translucent-light);\n border-radius: 1rem;\n height: 1.5rem;\n outline: none;\n border: none;\n -webkit-appearance: none;\n cursor: pointer;\n position: relative;\n position: relative;\n overflow: hidden;\n box-shadow: 0 0.25rem 1rem rgba(0,0,0,0.15);\n &::after {\n content: \"\";\n position: absolute;\n top: 0.1rem;\n left: 0.1rem;\n width: 1.3rem;\n height: 1.3rem;\n background-image: url(\"#{$imagesPath}sun.svg\");\n background-position: center;\n background-size: cover;\n border-radius: 50%;\n z-index: 2; } }\n &_animate {\n transition: transform 0.5s cubic-bezier(0.075, 0.82, 0.165, 1);\n &::after {\n transition: transform 0.5s cubic-bezier(.19,1,.22,1);\n will-change: transform; } } }\n\n.taxonomy {\n text-transform: capitalize; }\n\n.image {\n &-scale {\n position: fixed;\n z-index: 999999;\n left: 0;\n right: 0;\n height: 100vh;\n top: 0;\n padding: 1.5rem;\n background-color: var(--bg);\n display: grid;\n align-items: center;\n overflow: auto; }\n &-scale &-scalable {\n background-color: var(--text); }\n &-scalable {\n cursor: pointer;\n transition: transform 0.3s var(--ease); }\n &_featured {\n display: block;\n margin-left: auto !important;\n margin-right: auto !important; }\n &_thumbnail {\n margin: 0; } }\n\n.video {\n overflow: hidden;\n padding-bottom: 56.25%;\n position: relative;\n height: 0;\n margin: 1.5rem 0;\n border-radius: 0.6rem;\n background-color: var(--bg);\n box-shadow: 0 1rem 2rem rgba(0,0,0,0.17);\n iframe {\n left: 0;\n top: 0;\n height: 100%;\n width: 100%;\n border: none;\n position: absolute;\n transform: scale(1.02); } }\n\n.notices {\n border-top-width: 2rem;\n border-top-style: solid;\n color: #666;\n margin: 2rem 0;\n padding-bottom: .1px;\n padding-left: 1rem;\n padding-right: 1rem;\n .label {\n color: #fff;\n margin-top: -1.75rem;\n font-weight: bold;\n &:first-child::before {\n font-weight: 900;\n margin-left: -.35rem;\n margin-right: .35rem; } }\n &.info {\n border-color: var(--notice-info-border-color);\n background: var(--notice-info-background); }\n &.warning {\n border-color: var(--notice-warning-border-color);\n background: var(--notice-warning-background); }\n &.image-warning {\n margin: 0; }\n &.note {\n border-color: var(--notice-note-border-color);\n background: var(--notice-note-background); }\n &.tip {\n border-color: var(--notice-tip-border-color);\n background: var(--notice-tip-background); }\n .highlight_wrap {\n background: var(--notice-code-bg) !important; } }\n\n\n// search\n\n.search {\n flex: 1;\n display: flex;\n justify-content: flex-end;\n position: relative;\n max-width: 25rem;\n margin: 0.5rem 0 0;\n --border: transparent;\n &_field {\n padding: 0.5rem 1rem;\n width: 100%;\n outline: none;\n color: var(--text);\n background: var(--post-bg);\n border: 1px solid var(--border);\n border-radius: 8px;\n font-size: 1rem;\n box-shadow: 0 0.25rem 1rem rgba(0,0,0,0.1);\n &:hover, &:focus {\n } } // background: var(--search-bg)\n &_field:focus + &_label {\n opacity: 0; }\n &_label {\n position: absolute;\n z-index: 9;\n opacity: 0.67;\n right: 0.67rem;\n top: 0.25rem;\n width: 1rem;\n height: 1rem;\n svg {\n width: 100%;\n height: 100%;\n fill: #7C849B; } }\n &_result {\n padding: 0.5rem 1rem;\n &:not(.passive):hover {\n background-color: var(--code-bg);\n color: $light; }\n &.passive {\n display: grid; }\n &s {\n width: 100%;\n background-color: var(--choice-bg);\n color: var(--text);\n border-radius: var(--radius);\n box-shadow: 0 1rem 4rem rgba(0,0,0,0.17) !important;\n position: absolute;\n top: 125%;\n display: grid;\n overflow: hidden;\n z-index: 3;\n &:empty {\n display: none; } } }\n &_title {\n padding: 0.25rem 1rem !important;\n background-color: $theme;\n color: var(--light);\n margin: 0;\n font-size: 1.25rem;\n &:empty {\n display: none; } }\n &_submit {\n position: absolute;\n --margin: 3px;\n right: var(--margin);\n top: var(--margin);\n bottom: var(--margin);\n z-index: 9;\n cursor: pointer;\n border-radius: calc(var(--radius) / 2); } }\n\n#results {\n .search {\n &_title, &_result {\n padding: 0.5rem 0; } } }\n\n.openstreetmap {\n\tborder: none; }\n\n", + "@for $i from 1 through 2 {\n $size: $i * 1.5rem;\n $x-size: $size * 0.5;\n .pt-#{$i} {\n padding-top: $size; }\n\n .pb-#{$i} {\n padding-bottom: $size; }\n\n .mt-#{$i} {\n margin-top: $size; }\n\n .mb-#{$i} {\n margin-bottom: $size; } }\n\n.flex {\n display: flex;\n flex-direction: column;\n align-items: center; }\n\n.shadow {\n box-shadow: 0 0 60px rgba(0, 0, 0, 0.17); }\n\n@media screen and (min-width: $single-column-breakpoint) {\n %grid {\n display: grid;\n grid-template-columns: 1fr; }\n\n [class*='grid-'] {\n grid-gap: 2rem; }\n\n .grid-2, .grid-3, .grid-4, .grid-auto, .grid-inverse {\n @extend %grid; }\n .grid-inverse {\n grid-template-columns: 70% 1fr;\n grid-column-gap: 4rem; }\n .grid-2 {\n grid-template-columns: 1fr 1fr; }\n .grid-3 {\n grid-template-columns: repeat(auto-fit, minmax(19rem, 1fr)); }\n .grid-4 {\n grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); } }\n\n$sites: (\"facebook\": #325c94, \"twitter\": #00abdc,\"linkedin\": #007bb6);\n\n@each $item, $color in $sites {\n .#{$item} {\n svg {\n fill: $color; } } }\n\n// 404 page\n.never {\n height: 75vh;\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n padding: 1.5rem;\n text-align: center; }\n\n.inline {\n display: inline;\n margin: 0; }\n\n.hidden {\n display: none; }\n", + "@media screen and (max-width: $mobile-menu-breakpoint) {\n .nav {\n // padding-bottom: 2rem\n &, &_body {\n flex-direction: column; }\n &_body {\n position: fixed;\n width: 90%;\n max-width: 16.5rem;\n top: 0;\n bottom: 0;\n background-color: $bg;\n transition: transform 0.3s var(--easing);\n &_right {\n transform: translateX(100vw);\n right: 0; }\n &_left {\n transform: translateX(-100vw);\n left: 0; } }\n\n &_close {\n width: 3rem;\n position: absolute;\n right: -4rem;\n top: 0;\n bottom: 0;\n height: 100%;\n cursor: pointer;\n z-index: 1000;\n display: flex;\n justify-content: center;\n align-items: center;\n svg {\n width: 1.25rem;\n fill: var(--light);\n height: 1.25rem;\n display: none;\n &:first-child {\n display: initial; }\n &.isopen {\n display: none;\n + svg {\n display: initial; } } } }\n\n &_brand {\n position: relative;\n z-index: 999;\n width: calc(100% - 3rem);\n padding-left: 0; }\n\n &_parent {\n display: grid; }\n &_sub {\n position: relative;\n top: initial;\n padding-top: 0; } }\n\n .jsopen {\n &::after {\n content: \"\";\n position: fixed;\n z-index: 2;\n background-color: rgba(0,0,0,0.3);\n top: 0;\n left: 0;\n right: 0;\n bottom: 0; }\n .nav {\n &_body {\n transform: translateX(0);\n padding-left: 1.5rem;\n padding-right: 1.5rem; }\n &_parent {\n &:first-child {\n margin-top: 4.4rem; } }\n\n .follow {\n justify-content: flex-start;\n flex: initial;\n margin-top: 0.75rem; } } } }\n", + "@keyframes pulse {\n 0% {\n opacity: 1; }\n 75% {\n opacity: 0.1; }\n 100% {\n opacity: 1; } }\n\ncode {\n font-size: 85%;\n font-weight: 400;\n overflow-y: hidden;\n display: block;\n font-family: 'Monaco', monospace;\n word-break: break-all;\n &.noClass {\n --inlineColor: rgb(194, 29, 0);\n color: var(--inlineColor);\n display: inline;\n line-break: anywhere; } }\n.windows .highlight {\n overflow-x: hidden;\n &:hover {\n overflow-x: auto; } }\n\n.highlight {\n display: grid;\n width: 100%;\n border-radius: 0 0.2rem 0.2rem 0;\n overflow-x: auto;\n // @media screen and (min-width: 1240px)\n // overflow-x: hidden\n // &:hover\n // overflow-x: auto\n position: relative;\n &_wrap {\n background: var(--code-bg) !important;\n border-radius: 0.5rem;\n position: relative;\n padding: 0 1rem;\n margin: 1.5rem auto 1rem auto;\n & + & {\n margin-top: 2.25rem; }\n &:hover > div {\n opacity: 1; }\n .lang {\n position: absolute;\n // background-color: var(--bg)\n top: 0;\n right: 0;\n text-align: right;\n width: 7.5rem;\n padding: 0.5rem 1rem;\n font-style: italic;\n text-transform: uppercase;\n font-size: 67%;\n opacity: 0.5;\n color: var(--light); }\n &:hover .lang {\n opacity: 0.1; } }\n & & {\n margin: 0; }\n pre {\n color: var(--light) !important;\n border-radius: 4px;\n font-family: 'Monaco', monospace;\n padding-top: 1.5rem;\n padding-bottom: 2rem; }\n\n table {\n display: grid;\n max-width: 100%;\n margin-bottom: 0;\n background: transparent; }\n td, th {\n padding: 0; }\n\n .lntd {\n width: 100%;\n border: none;\n &:first-child {\n &, pre {\n width: 2.5rem !important;\n padding-left: 0;\n padding-right: 0;\n color: rgba(255,255,255,0.5);\n user-select: none; }\n\n pre {\n width: 100%;\n display: flex;\n align-items: center;\n flex-direction: column; } } } }\n\n.err {\n color: #a61717;\n background-color: #e3d2d2; }\n.hl {\n width: 100%;\n background-color: rgba(255,255,255,0.25); }\n.ln, .lnt {\n margin-right: 0.75rem;\n padding: 0;\n transition: opacity 0.3s var(--ease);\n &, span {\n color: hsla(0,0%,100%,0.5);\n user-select: none; } }\n\n.k, .kc, .kd, .kn, .kp, .kr, .kt, .nt {\n color: #6ab825;\n font-weight: 500; }\n\n.kn, .kp {\n font-weight: 400; }\n\n.nb, .no, .nv {\n color: #24909d; }\n\n.nc, .nf, .nn {\n color: #447fcf; }\n\n.s, .sa, .sb, .sc, .dl, .sd, .s2, .se, .sh, .si, .sx, .sr, .s1, .ss {\n color: #ed9d13; }\n\n.m, .mb, .mf, .mh, .mi, .il, .mo {\n color: #3677a9; }\n\n.ow {\n color: #6ab825;\n font-weight: 500; }\n\n.c, .ch, .cm, .c1 {\n color: #999;\n font-style: italic; }\n\n.cs {\n color: #e50808;\n background-color: #520000;\n font-weight: 500; }\n\n.cp, .cpf {\n color: #cd2828;\n font-weight: 500; }\n\n.gd, .gr {\n color: #d22323; }\n\n.ge {\n font-style: italic; }\n\n.gh, .gu, .nd, .na, .ne {\n color: #ffa500;\n font-weight: 500; }\n\n.gi {\n color: #589819; }\n\n.go {\n color: #ccc; }\n\n.gp {\n color: #aaa; }\n\n.gs {\n font-weight: 500; }\n\n.gt {\n color: #d22323; }\n.w {\n color: #666; }\n\n.hljs {\n &-string {\n color: #6ab825; }\n &-attr {\n color: #ed9d13; }\n .p &-attr {\n color: var(--light); } }\n\n.pre {\n &_wrap {\n white-space: pre-wrap;\n white-space: -moz-pre-wrap;\n white-space: -pre-wrap;\n white-space: -o-pre-wrap;\n word-wrap: break-word; }\n\n &_nolines.line .ln {\n display: none; } }\n\n// crayon-like widget styles\n.panel {\n &_box {\n display: inline-flex;\n // grid-template-columns: repeat(3, 1fr)\n // max-width: 10rem\n perspective: 300px;\n grid-gap: 0.5rem;\n transition: opacity 0.3s var(--easing);\n background: var(--code-bg);\n padding: 0.5rem 1.5rem;\n border-radius: 2rem;\n align-items: center;\n position: absolute;\n right: 0rem;\n top: -2.1rem;\n opacity: 0; }\n &_icon {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n // transition: opacity 0.3s var(--easing)\n padding: 0.1rem;\n transform-origin: 50% 50%;\n // opacity: 0.7\n background-size: 100%;\n background-repeat: no-repeat;\n &.active {\n animation: pulse 0.1s linear; }\n svg {\n fill: var(--light);\n width: 1.5rem;\n height: 1.5rem; } }\n &_hide {\n // hide icon if not needed\n display: none; }\n &_from {\n position: absolute;\n color: var(--theme);\n bottom: 0;\n font-size: 1.5rem;\n font-weight: 500;\n padding: 0.5rem 0;\n cursor: pointer;\n letter-spacing: 0.1px;\n z-index: 19; }\n &_expanded &_from {\n display: none; } }\n", + "// add customs styles and general overrides here\n// due to the cascading nature of css, if you try to override theme css variables in this file, those changes will not apply. Instead, override css variables in the `override.sass` file\n// we recommend not editing this file directly. Instead, create an `assets/sass/_custom.sass` file at the root level of your site.\n// if you edit this file directly, you will have to resolve git conflicts when and if you decide to pull changes we make on the theme\n" + ], + "names": [], + "mappings": "ACwBA,AAAA,IAAI,AAAC,CACH,YAAY,CAAA,MAAC,CACb,OAAO,CAAA,KAAC,CACR,MAAM,CAAA,KAAC,CACP,IAAI,CAAA,QAAC,CACL,MAAM,CAAA,QAAC,CACP,MAAM,CAAA,QAAC,CACP,QAAQ,CAAA,YAAC,CACT,MAAM,CAAA,QAAC,CACP,aAAa,CAAA,YAAC,CACd,MAAM,CAAA,uBAAC,CACP,OAAO,CAAA,QAAC,CACR,MAAM,CAAA,0BAAC,CACP,SAAS,CAAA,UAAC,CACV,UAAU,CAAA,aAAC,CACX,YAAY,CAAA,YAAC,CACb,cAAc,CAAA,QAAC,CACf,WAAW,CAAA,YAAC,CACZ,QAAQ,CAAA,iBAAC,CACT,aAAa,CAAA,iBAAC,CACd,mBAAmB,CAAA,uBAAC,CACpB,SAAS,CAAA,aAAC,CACV,W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AhCzB,AA2BI,WA3BE,AA2BD,OAAO,AAAC,CACP,SAAS,CAAE,iBAAiB,CAAG,AA5BrC,AA6BI,WA7BE,CA6BF,GAAG,AAAC,CACF,IAAI,CAAE,YAAY,CAClB,KAAK,CAAE,MAAM,CACb,MAAM,CAAE,MAAM,CAAG,AAhCvB,AAiCE,WAjCI,AAiCG,CAEL,OAAO,CAAE,IAAI,CAAG,AAnCpB,AAoCE,WApCI,AAoCG,CACL,QAAQ,CAAE,QAAQ,CAClB,KAAK,CAAE,YAAY,CACnB,MAAM,CAAE,CAAC,CACT,SAAS,CAAE,MAAM,CACjB,WAAW,CAAE,GAAG,CAChB,OAAO,CAAE,QAAQ,CACjB,MAAM,CAAE,OAAO,CACf,cAAc,CAAE,KAAK,CACrB,OAAO,CAAE,EAAE,CAAG,AA7ClB,AA8CE,eA9CI,CAAN,WAAM,AA8Cc,CAChB,OAAO,CAAE,IAAI,CAAG" +} \ No newline at end of file diff --git a/en/js/bundle.220c6c0897be5a8c092d22a0d09ad1711747cfcc22dac0db2ceefae2c27772e96e0bc55429f6f43cd6bd9ece6eeeab6a13ecfb4e84898e66c81eade29c9c1457.js b/en/js/bundle.220c6c0897be5a8c092d22a0d09ad1711747cfcc22dac0db2ceefae2c27772e96e0bc55429f6f43cd6bd9ece6eeeab6a13ecfb4e84898e66c81eade29c9c1457.js new file mode 100644 index 0000000..b9e4457 --- /dev/null +++ b/en/js/bundle.220c6c0897be5a8c092d22a0d09ad1711747cfcc22dac0db2ceefae2c27772e96e0bc55429f6f43cd6bd9ece6eeeab6a13ecfb4e84898e66c81eade29c9c1457.js @@ -0,0 +1,1133 @@ +/*! highlight.js v9.17.1 | BSD3 License | git.io/hljslicense */ +!function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"==typeof exports||exports.nodeType?n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs})):e(exports)}(function(a){var f=[],o=Object.keys,N={},g={},_=!0,n=/^(no-?highlight|plain|text)$/i,E=/\blang(?:uage)?-([\w-]+)\b/i,t=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,r={case_insensitive:"cI",lexemes:"l",contains:"c",keywords:"k",subLanguage:"sL",className:"cN",begin:"b",beginKeywords:"bK",end:"e",endsWithParent:"eW",illegal:"i",excludeBegin:"eB",excludeEnd:"eE",returnBegin:"rB",returnEnd:"rE",variants:"v",IDENT_RE:"IR",UNDERSCORE_IDENT_RE:"UIR",NUMBER_RE:"NR",C_NUMBER_RE:"CNR",BINARY_NUMBER_RE:"BNR",RE_STARTERS_RE:"RSR",BACKSLASH_ESCAPE:"BE",APOS_STRING_MODE:"ASM",QUOTE_STRING_MODE:"QSM",PHRASAL_WORDS_MODE:"PWM",C_LINE_COMMENT_MODE:"CLCM",C_BLOCK_COMMENT_MODE:"CBCM",HASH_COMMENT_MODE:"HCM",NUMBER_MODE:"NM",C_NUMBER_MODE:"CNM",BINARY_NUMBER_MODE:"BNM",CSS_NUMBER_MODE:"CSSNM",REGEXP_MODE:"RM",TITLE_MODE:"TM",UNDERSCORE_TITLE_MODE:"UTM",COMMENT:"C",beginRe:"bR",endRe:"eR",illegalRe:"iR",lexemesRe:"lR",terminators:"t",terminator_end:"tE"},C="",m="Could not find the language '{}', did you forget to load/include a language module?",O={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},c="of and for in not or if then".split(" ");function B(e){return e.replace(/&/g,"&").replace(//g,">")}function d(e){return e.nodeName.toLowerCase()}function R(e){return n.test(e)}function i(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function p(e){var a=[];return function e(n,t){for(var r=n.firstChild;r;r=r.nextSibling)3===r.nodeType?t+=r.nodeValue.length:1===r.nodeType&&(a.push({event:"start",offset:t,node:r}),t=e(r,t),d(r).match(/br|hr|img|input/)||a.push({event:"stop",offset:t,node:r}));return t}(e,0),a}function v(e,n,t){var r=0,a="",i=[];function o(){return e.length&&n.length?e[0].offset!==n[0].offset?e[0].offset"}function l(e){a+=""}function u(e){("start"===e.event?c:l)(e.node)}for(;e.length||n.length;){var s=o();if(a+=B(t.substring(r,s[0].offset)),r=s[0].offset,s===e){for(i.reverse().forEach(l);u(s.splice(0,1)[0]),(s=o())===e&&s.length&&s[0].offset===r;);i.reverse().forEach(c)}else"start"===s[0].event?i.push(s[0].node):i.pop(),u(s.splice(0,1)[0])}return a+B(t.substr(r))}function l(n){return n.v&&!n.cached_variants&&(n.cached_variants=n.v.map(function(e){return i(n,{v:null},e)})),n.cached_variants?n.cached_variants:function e(n){return!!n&&(n.eW||e(n.starts))}(n)?[i(n,{starts:n.starts?i(n.starts):null})]:Object.isFrozen(n)?[i(n)]:[n]}function u(e){if(r&&!e.langApiRestored){for(var n in e.langApiRestored=!0,r)e[n]&&(e[r[n]]=e[n]);(e.c||[]).concat(e.v||[]).forEach(u)}}function M(n,t){var i={};return"string"==typeof n?r("keyword",n):o(n).forEach(function(e){r(e,n[e])}),i;function r(a,e){t&&(e=e.toLowerCase()),e.split(" ").forEach(function(e){var n,t,r=e.split("|");i[r[0]]=[a,(n=r[0],(t=r[1])?Number(t):function(e){return-1!=c.indexOf(e.toLowerCase())}(n)?0:1)]})}}function x(r){function s(e){return e&&e.source||e}function f(e,n){return new RegExp(s(e),"m"+(r.cI?"i":"")+(n?"g":""))}function a(a){var i,e,o={},c=[],l={},t=1;function n(e,n){o[t]=e,c.push([e,n]),t+=new RegExp(n.toString()+"|").exec("").length-1+1}for(var r=0;r')+n+(t?"":C)}function o(){R+=null!=E.sL?function(){var e="string"==typeof E.sL;if(e&&!N[E.sL])return B(p);var n=e?S(E.sL,p,!0,d[E.sL]):T(p,E.sL.length?E.sL:void 0);return 0")+'"');if("end"===n.type){var r=s(n);if(null!=r)return r}return p+=t,t.length}var g=D(n);if(!g)throw console.error(m.replace("{}",n)),new Error('Unknown language: "'+n+'"');x(g);var r,E=e||g,d={},R="";for(r=E;r!==g;r=r.parent)r.cN&&(R=c(r.cN,"",!0)+R);var p="",v=0;try{for(var M,b,h=0;E.t.lastIndex=h,M=E.t.exec(i);)b=t(i.substring(h,M.index),M),h=M.index+b;for(t(i.substr(h)),r=E;r.parent;r=r.parent)r.cN&&(R+=C);return{relevance:v,value:R,i:!1,language:n,top:E}}catch(e){if(e.message&&-1!==e.message.indexOf("Illegal"))return{i:!0,relevance:0,value:B(i)};if(_)return{relevance:0,value:B(i),language:n,top:E,errorRaised:e};throw e}}function T(t,e){e=e||O.languages||o(N);var r={relevance:0,value:B(t)},a=r;return e.filter(D).filter(L).forEach(function(e){var n=S(e,t,!1);n.language=e,n.relevance>a.relevance&&(a=n),n.relevance>r.relevance&&(a=r,r=n)}),a.language&&(r.second_best=a),r}function b(e){return O.tabReplace||O.useBR?e.replace(t,function(e,n){return O.useBR&&"\n"===e?"
":O.tabReplace?n.replace(/\t/g,O.tabReplace):""}):e}function s(e){var n,t,r,a,i,o,c,l,u,s,f=function(e){var n,t,r,a,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=E.exec(i)){var o=D(t[1]);return o,o?t[1]:"no-highlight"}for(n=0,r=(i=i.split(/\s+/)).length;n/g,"\n"):n=e,i=n.textContent,r=f?S(f,i,!0):T(i),(t=p(n)).length&&((a=document.createElement("div")).innerHTML=r.value,r.value=v(t,p(a),i)),r.value=b(r.value),e.innerHTML=r.value,e.className=(o=e.className,c=f,l=r.language,u=c?g[c]:l,s=[o.trim()],o.match(/\bhljs\b/)||s.push("hljs"),-1===o.indexOf(u)&&s.push(u),s.join(" ").trim()),e.result={language:r.language,re:r.relevance},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.relevance}))}function h(){if(!h.called){h.called=!0;var e=document.querySelectorAll("pre code");f.forEach.call(e,s)}}var w={disableAutodetect:!0};function D(e){return e=(e||"").toLowerCase(),N[e]||N[g[e]]}function L(e){var n=D(e);return n&&!n.disableAutodetect}return a.highlight=S,a.highlightAuto=T,a.fixMarkup=b,a.highlightBlock=s,a.configure=function(e){O=i(O,e)},a.initHighlighting=h,a.initHighlightingOnLoad=function(){window.addEventListener("DOMContentLoaded",h,!1),window.addEventListener("load",h,!1)},a.registerLanguage=function(n,e){var t;try{t=e(a)}catch(e){if(console.error("Language definition for '{}' could not be registered.".replace("{}",n)),!_)throw e;console.error(e),t=w}u(N[n]=t),t.rawDefinition=e.bind(null,a),t.aliases&&t.aliases.forEach(function(e){g[e]=n})},a.listLanguages=function(){return o(N)},a.getLanguage=D,a.requireLanguage=function(e){var n=D(e);if(n)return n;throw new Error("The '{}' language is required, but not loaded.".replace("{}",e))},a.autoDetection=L,a.inherit=i,a.debugMode=function(){_=!1},a.IR=a.IDENT_RE="[a-zA-Z]\\w*",a.UIR=a.UNDERSCORE_IDENT_RE="[a-zA-Z_]\\w*",a.NR=a.NUMBER_RE="\\b\\d+(\\.\\d+)?",a.CNR=a.C_NUMBER_RE="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",a.BNR=a.BINARY_NUMBER_RE="\\b(0b[01]+)",a.RSR=a.RE_STARTERS_RE="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",a.BE=a.BACKSLASH_ESCAPE={b:"\\\\[\\s\\S]",relevance:0},a.ASM=a.APOS_STRING_MODE={cN:"string",b:"'",e:"'",i:"\\n",c:[a.BE]},a.QSM=a.QUOTE_STRING_MODE={cN:"string",b:'"',e:'"',i:"\\n",c:[a.BE]},a.PWM=a.PHRASAL_WORDS_MODE={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},a.C=a.COMMENT=function(e,n,t){var r=a.inherit({cN:"comment",b:e,e:n,c:[]},t||{});return r.c.push(a.PWM),r.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",relevance:0}),r},a.CLCM=a.C_LINE_COMMENT_MODE=a.C("//","$"),a.CBCM=a.C_BLOCK_COMMENT_MODE=a.C("/\\*","\\*/"),a.HCM=a.HASH_COMMENT_MODE=a.C("#","$"),a.NM=a.NUMBER_MODE={cN:"number",b:a.NR,relevance:0},a.CNM=a.C_NUMBER_MODE={cN:"number",b:a.CNR,relevance:0},a.BNM=a.BINARY_NUMBER_MODE={cN:"number",b:a.BNR,relevance:0},a.CSSNM=a.CSS_NUMBER_MODE={cN:"number",b:a.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},a.RM=a.REGEXP_MODE={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[a.BE,{b:/\[/,e:/\]/,relevance:0,c:[a.BE]}]},a.TM=a.TITLE_MODE={cN:"title",b:a.IR,relevance:0},a.UTM=a.UNDERSCORE_TITLE_MODE={cN:"title",b:a.UIR,relevance:0},a.METHOD_GUARD={b:"\\.\\s*"+a.UIR,relevance:0},[a.BE,a.ASM,a.QSM,a.PWM,a.C,a.CLCM,a.CBCM,a.HCM,a.NM,a.CNM,a.BNM,a.CSSNM,a.RM,a.TM,a.UTM,a.METHOD_GUARD].forEach(function(e){!function n(t){Object.freeze(t);var r="function"==typeof t;Object.getOwnPropertyNames(t).forEach(function(e){!t.hasOwnProperty(e)||null===t[e]||"object"!=typeof t[e]&&"function"!=typeof t[e]||r&&("caller"===e||"callee"===e||"arguments"===e)||Object.isFrozen(t[e])||n(t[e])});return t}(e)}),a});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},a={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,relevance:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],relevance:0},e.HCM,a,{cN:"",b:/\\"/},{cN:"string",b:/'/,e:/'/},t]}});hljs.registerLanguage("shell",function(s){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[/\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}});hljs.registerLanguage("ruby",function(e){var c="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",b={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},r={cN:"doctag",b:"@[A-Za-z]+"},a={b:"#<",e:">"},n=[e.C("#","$",{c:[r]}),e.C("^\\=begin","^\\=end",{c:[r],relevance:10}),e.C("^__END__","\\n$")],s={cN:"subst",b:"#\\{",e:"}",k:b},t={cN:"string",c:[e.BE,s],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<[-~]?'?(\w+)(?:.|\n)*?\n\s*\1\b/,rB:!0,c:[{b:/<<[-~]?'?/},{b:/\w+/,endSameAsBegin:!0,c:[e.BE,s]}]}]},i={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:b},l=[t,a,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(n)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:c}),i].concat(n)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",relevance:0},{cN:"symbol",b:":(?!\\s)",c:[t,{b:c}],relevance:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",relevance:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:b},{b:"("+e.RSR+"|unless)\\s*",k:"unless",c:[a,{cN:"regexp",c:[e.BE,s],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(n),relevance:0}].concat(n);s.c=l;var d=[{b:/^\s*=>/,starts:{e:"$",c:i.c=l}},{cN:"meta",b:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+>|(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>)",starts:{e:"$",c:l}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:b,i:/\/\*/,c:n.concat(d).concat(l)}});hljs.registerLanguage("yaml",function(e){var b="true false yes no null",a={cN:"string",relevance:0,v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/\S+/}],c:[e.BE,{cN:"template-variable",v:[{b:",e:"},{b:"%{",e:"}"}]}]};return{cI:!0,aliases:["yml","YAML","yaml"],c:[{cN:"attr",v:[{b:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{b:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{b:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{cN:"meta",b:"^---s*$",relevance:10},{cN:"string",b:"[\\|>]([0-9]?[+-])?[ ]*\\n( *)[\\S ]+\\n(\\2[\\S ]+\\n?)*"},{b:"<%[%=-]?",e:"[%-]?%>",sL:"ruby",eB:!0,eE:!0,relevance:0},{cN:"type",b:"!"+e.UIR},{cN:"type",b:"!!"+e.UIR},{cN:"meta",b:"&"+e.UIR+"$"},{cN:"meta",b:"\\*"+e.UIR+"$"},{cN:"bullet",b:"\\-(?=[ ]|$)",relevance:0},e.HCM,{bK:b,k:{literal:b}},{cN:"number",b:e.CNR+"\\b"},a]}}); + +; +const featuredImageClass = 'image_featured'; +const imageScalableClass = 'image-scalable'; +const scaleImageClass = 'image-scale'; +const pageHasLoaded = 'DOMContentLoaded'; +const imageAltClass = 'img_alt'; + + +const defaultSiteLanguage = ''; +const baseURL = 'https://mighten.github.io/'; +const searchFieldClass = '.search_field'; +const searchClass = '.search'; +const goBackClass = 'button_back'; +const lineClass = '.line'; + +// defined in i18n / translation files +const quickLinks = 'Results'; +const searchResultsLabel = 'Search Results'; +const shortSearchQuery = 'Query is too short' +const typeToSearch = 'Type to search'; +const noMatchesFound = 'No results found'; + +; +// global variables +const doc = document.documentElement; +const inline = ":inline"; +// variables read from your hugo configuration +let showImagePosition = "false"; + +const showImagePositionLabel = 'Figure'; + +function isObj(obj) { + return (obj && typeof obj === 'object' && obj !== null) ? true : false; +} + +function createEl(element = 'div') { + return document.createElement(element); +} + +function elem(selector, parent = document){ + let elem = parent.querySelector(selector); + return elem != false ? elem : false; +} + +function elems(selector, parent = document) { + let elems = parent.querySelectorAll(selector); + return elems.length ? elems : false; +} + +function pushClass(el, targetClass) { + if (isObj(el) && targetClass) { + elClass = el.classList; + elClass.contains(targetClass) ? false : elClass.add(targetClass); + } +} + +function hasClasses(el) { + if(isObj(el)) { + const classes = el.classList; + return classes.length + } +} + +(function markInlineCodeTags(){ + const codeBlocks = elems('code'); + if(codeBlocks) { + codeBlocks.forEach(function(codeBlock){ + // Fix for orgmode inline code, leave 'verbatim' alone as well + containsClass(codeBlock, 'verbatim') ? pushClass(codeBlock, 'noClass') :false; + hasClasses(codeBlock) ? false: pushClass(codeBlock, 'noClass'); + }); + } +})(); + +function deleteClass(el, targetClass) { + if (isObj(el) && targetClass) { + elClass = el.classList; + elClass.contains(targetClass) ? elClass.remove(targetClass) : false; + } +} + +function modifyClass(el, targetClass) { + if (isObj(el) && targetClass) { + elClass = el.classList; + elClass.contains(targetClass) ? elClass.remove(targetClass) : elClass.add(targetClass); + } +} + +function containsClass(el, targetClass) { + if (isObj(el) && targetClass && el !== document ) { + return el.classList.contains(targetClass) ? true : false; + } +} + +function elemAttribute(elem, attr, value = null) { + if (value) { + elem.setAttribute(attr, value); + } else { + value = elem.getAttribute(attr); + return value ? value : false; + } +} + +function wrapEl(el, wrapper) { + el.parentNode.insertBefore(wrapper, el); + wrapper.appendChild(el); +} + +function deleteChars(str, subs) { + let newStr = str; + if (Array.isArray(subs)) { + for (let i = 0; i < subs.length; i++) { + newStr = newStr.replace(subs[i], ''); + } + } else { + newStr = newStr.replace(subs, ''); + } + return newStr; +} + +function isBlank(str) { + return (!str || str.trim().length === 0); +} + +function isMatch(element, selectors) { + if(isObj(element)) { + if(selectors.isArray) { + let matching = selectors.map(function(selector){ + return element.matches(selector) + }) + return matching.includes(true); + } + return element.matches(selectors) + } +} + +function copyToClipboard(str) { + let copy, selection, selected; + copy = createEl('textarea'); + copy.value = str; + copy.setAttribute('readonly', ''); + copy.style.position = 'absolute'; + copy.style.left = '-9999px'; + selection = document.getSelection(); + doc.appendChild(copy); + // check if there is any selected content + selected = selection.rangeCount > 0 ? selection.getRangeAt(0) : false; + copy.select(); + document.execCommand('copy'); + doc.removeChild(copy); + if (selected) { // if a selection existed before copying + selection.removeAllRanges(); // unselect existing selection + selection.addRange(selected); // restore the original selection + } +} + +const iconsPath = 'favicon/'; + +function getMobileOperatingSystem() { + let userAgent = navigator.userAgent || navigator.vendor || window.opera; + + if (/android/i.test(userAgent)) { + return "Android"; + } + + if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) { + return "iOS"; + } + + return "unknown"; +} + +function horizontalSwipe(element, func, direction) { + // call func if result of swipeDirection() 👇🏻 is equal to direction + let touchstartX = 0; + let touchendX = 0; + let swipeDirection = null; + + function handleGesure() { + return (touchendX + 50 < touchstartX) ? 'left' : (touchendX < touchstartX + 50) ? 'right' : false; + } + + element.addEventListener('touchstart', e => { + touchstartX = e.changedTouches[0].screenX + }); + + element.addEventListener('touchend', e => { + touchendX = e.changedTouches[0].screenX + swipeDirection = handleGesure() + swipeDirection === direction ? func() : false; + }); + +} + +function parseBoolean(string) { + let bool; + string = string.trim().toLowerCase(); + switch (string) { + case 'true': + return true; + case 'false': + return false; + default: + return undefined; + } +}; + +function forEach(node, callback) { + node ? Array.prototype.forEach.call(node.childNodes, callback) : false; +} + +function findQuery(query = 'query') { + const urlParams = new URLSearchParams(window.location.search); + if(urlParams.has(query)){ + let c = urlParams.get(query); + return c; + } + return ""; +} + +function wrapText(text, context, wrapper = 'mark') { + let open = `<${wrapper}>`; + let close = ``; + let escapedOpen = `%3C${wrapper}%3E`; + let escapedClose = `%3C/${wrapper}%3E`; + function wrap(context) { + let c = context.innerHTML; + let pattern = new RegExp(text, "gi"); + let matches = text.length ? c.match(pattern) : null; + + if(matches) { + matches.forEach(function(matchStr){ + c = c.replaceAll(matchStr, `${open}${matchStr}${close}`); + context.innerHTML = c; + }); + + const images = elems('img', context); + + if(images) { + images.forEach(image => { + image.src = image.src.replaceAll(open, '').replaceAll(close, '').replaceAll(escapedOpen, '').replaceAll(escapedClose, ''); + }); + } + } + } + + const contents = ["h1", "h2", "h3", "h4", "h5", "h6", "p", "code", "td"]; + + contents.forEach(function(c){ + const cs = elems(c, context); + if(cs.length) { + cs.forEach(function(cx, index){ + if(cx.children.length >= 1) { + Array.from(cx.children).forEach(function(child){ + wrap(child); + }) + wrap(cx); + } else { + wrap(cx); + } + // sanitize urls and ids + }); + } + }); + + const hyperLinks = elems('a'); + if(hyperLinks) { + hyperLinks.forEach(function(link){ + link.href = link.href.replaceAll(encodeURI(open), "").replaceAll(encodeURI(close), ""); + }); + } +} + +function emptyEl(el) { + while(el.firstChild) + el.removeChild(el.firstChild); +} + +function matchTarget(element, selector) { + if(isObj(element)) { + let matches = false; + const isExactMatch = element.matches(selector); + const exactTarget = element.closest(selector); + matches = isExactMatch ? isExactMatch : exactTarget; + return { + exact: isExactMatch, // is exact target + valid: matches, + actual: exactTarget + }; + } +} + +function goBack(target) { + const matchCriteria = matchTarget(target, `.${goBackClass}`); + + if(matchCriteria.valid) { + history.back(); + } +} + +(function() { + const bodyElement = elem('body'); + const platform = navigator.platform.toLowerCase(); + if(platform.includes("win")) { + pushClass(bodyElement, 'windows'); + } +})(); + +; +const codeActionButtons = [ + { + icon: 'copy', + id: 'copy', + title: 'Copy Code', + show: true + }, + { + icon: 'order', + id: 'lines', + title: 'Toggle Line Numbers', + show: true + }, + { + icon: 'carly', + id: 'wrap', + title: 'Toggle Line Wrap', + show: false + }, + { + icon: 'expand', + id: 'expand', + title: 'Toggle code block expand', + show: false + } +]; + +const body = elem('body'); +const maxLines = parseInt(body.dataset.code); +const copyId = 'panel_copy'; +const wrapId = 'panel_wrap'; +const linesId = 'panel_lines'; +const panelExpand = 'panel_expand'; +const panelExpanded = 'panel_expanded'; +const panelHide = 'panel_hide'; +const panelFrom = 'panel_from'; +const panelBox = 'panel_box'; +const fullHeight = 'initial'; +const highlightWrap = 'highlight_wrap' + +function renderMermaidBeforePreCodeWrapped() { + // Replace mermaid pre.code to div + Array.from(document.getElementsByClassName("language-mermaid")).forEach( + (el) => { + el.parentElement.outerHTML = `
${el.innerText}
`; + } + ); +} + +/** + * preprocessing
 before it is wrapped up with a code fence
+ */
+function renderPlantUmlBeforePreCodeWrapped() {
+    Array.prototype.forEach.call(
+        document.querySelectorAll("[class^=language-plantuml]"), 
+        function(code){
+            // console.log('code class=language-plantuml------old-file: ', code);
+            let image = document.createElement("IMG");
+            image.loading = 'lazy'; // Lazy loading
+            image.decoding = 'async';
+            //  use `title` in plantuml to designate the title for a figure
+            // image.alt = 'UML diagram alternative text';
+            // image.title = "UML diagram title";
+            image.src = 'https://www.plantuml.com/plantuml/svg/' + plantumlEncoder.encode(code.innerText);
+
+            // replace 
 tag with 
tag, before it is wrapped up with a ugly code fence (`highlight_wrapper`) + code.parentElement.outerHTML = `
${image.outerHTML}
`; + } + ); +} + + + +function wrapOrphanedPreElements() { + const pres = elems('pre'); + Array.from(pres).forEach(function(pre){ + const parent = pre.parentNode; + const isOrpaned = !containsClass(parent, 'highlight'); + if(isOrpaned) { + const preWrapper = createEl(); + preWrapper.className = 'highlight'; + const outerWrapper = createEl(); + outerWrapper.className = highlightWrap; + wrapEl(pre, preWrapper); + wrapEl(preWrapper, outerWrapper); + } + }) + /* + @Todo + 1. Add UI control to orphaned blocks + */ +} + + +renderPlantUmlBeforePreCodeWrapped(); +renderMermaidBeforePreCodeWrapped(); + +wrapOrphanedPreElements(); + +function codeBlocks() { + const markedCodeBlocks = elems('code'); + const blocks = Array.from(markedCodeBlocks).filter(function(block){ + return hasClasses(block) && !Array.from(block.classList).includes('noClass'); + }).map(function(block){ + return block + }); + return blocks; +} + +function codeBlockFits(block) { + // return false if codeblock overflows + const blockWidth = block.offsetWidth; + const highlightBlockWidth = block.parentNode.parentNode.offsetWidth; + return blockWidth <= highlightBlockWidth ? true : false; +} + +function maxHeightIsSet(elem) { + let maxHeight = elem.style.maxHeight; + return maxHeight.includes('px') +} + +function restrainCodeBlockHeight(lines) { + const lastLine = lines[maxLines-1]; + let maxCodeBlockHeight = fullHeight; + if(lastLine) { + const lastLinePos = lastLine.offsetTop; + if(lastLinePos !== 0) { + maxCodeBlockHeight = `${lastLinePos}px`; + const codeBlock = lines[0].parentNode; + const outerBlock = codeBlock.closest('.highlight'); + const isExpanded = containsClass(outerBlock, panelExpanded); + if(!isExpanded) { + codeBlock.dataset.height = maxCodeBlockHeight; + codeBlock.style.maxHeight = maxCodeBlockHeight; + } + } + } +} + +const blocks = codeBlocks(); + +function collapseCodeBlock(block) { + const lines = elems(lineClass, block); + const codeLines = lines.length; + if (codeLines > maxLines) { + const expandDot = createEl() + pushClass(expandDot, panelExpand); + pushClass(expandDot, panelFrom); + expandDot.title = "Toggle code block expand"; + expandDot.textContent = "..."; + const outerBlock = block.closest('.highlight'); + window.setTimeout(function(){ + const expandIcon = outerBlock.nextElementSibling.lastElementChild; + deleteClass(expandIcon, panelHide); + }, 150) + + restrainCodeBlockHeight(lines); + const highlightElement = block.parentNode.parentNode; + highlightElement.appendChild(expandDot); + } +} + +blocks.forEach(function(block){ + collapseCodeBlock(block); +}) + +function actionPanel() { + const panel = createEl(); + panel.className = panelBox; + + codeActionButtons.forEach(function(button) { + // create button + const btn = createEl('a'); + btn.href = '#'; + btn.title = button.title; + btn.className = `icon panel_icon panel_${button.id}`; + button.show ? false : pushClass(btn, panelHide); + // load icon inside button + btn.style.backgroundImage = `url(${baseURL}${iconsPath}${button.icon}.svg)`; + // append button on panel + panel.appendChild(btn); + }); + + return panel; +} + +function toggleLineNumbers(elems) { + elems.forEach(function (elem, index) { + // mark the code element when there are no lines + modifyClass(elem, 'pre_nolines') + }); + restrainCodeBlockHeight(elems); +} + +function toggleLineWrap(elem) { + modifyClass(elem, 'pre_wrap'); + // retain max number of code lines on line wrap + const lines = elems(lineClass, elem); + restrainCodeBlockHeight(lines); +} + +function copyCode(codeElement) { + lineNumbers = elems('.ln', codeElement); + // remove line numbers before copying + if(lineNumbers.length) { + lineNumbers.forEach(function(line){ + line.remove(); + }); + } + + const codeToCopy = codeElement.textContent; + // copy code + copyToClipboard(codeToCopy); +} + +function disableCodeLineNumbers(block){ + const lines = elems(lineClass, block) + toggleLineNumbers(lines); +} + +(function codeActions(){ + const blocks = codeBlocks(); + + const highlightWrapId = highlightWrap; + blocks.forEach(function(block){ + // disable line numbers if disabled globally + const showLines = elem('body').dataset.lines; + parseBoolean(showLines) === false ? disableCodeLineNumbers(block) : false; + + const highlightElement = block.parentNode.parentNode; + // wrap code block in a div + const highlightWrapper = createEl(); + highlightWrapper.className = highlightWrapId; + wrapEl(highlightElement, highlightWrapper); + + const panel = actionPanel(); + // show wrap icon only if the code block needs wrapping + const wrapIcon = elem(`.${wrapId}`, panel); + codeBlockFits(block) ? false : deleteClass(wrapIcon, panelHide); + + // append buttons + highlightWrapper.appendChild(panel); + }); + + function isItem(target, id) { + // if is item or within item + return target.matches(`.${id}`) || target.closest(`.${id}`); + } + + function showActive(target, targetClass,activeClass = 'active') { + const active = activeClass; + const targetElement = target.matches(`.${targetClass}`) ? target : target.closest(`.${targetClass}`); + + deleteClass(targetElement, active); + setTimeout(function() { + modifyClass(targetElement, active) + }, 50) + } + + doc.addEventListener('click', function(event){ + // copy code block + const target = event.target; + const isCopyIcon = isItem(target, copyId); + const isWrapIcon = isItem(target, wrapId); + const isLinesIcon = isItem(target, linesId); + const isExpandIcon = isItem(target, panelExpand); + const isActionable = isCopyIcon || isWrapIcon || isLinesIcon || isExpandIcon; + + if(isActionable) { + event.preventDefault(); + showActive(target, 'icon'); + const codeElement = target.closest(`.${highlightWrapId}`).firstElementChild.firstElementChild; + let lineNumbers = elems(lineClass, codeElement); + + isWrapIcon ? toggleLineWrap(codeElement) : false; + + isLinesIcon ? toggleLineNumbers(lineNumbers) : false; + + if (isExpandIcon) { + let thisCodeBlock = codeElement.firstElementChild; + const outerBlock = thisCodeBlock.closest('.highlight'); + if(maxHeightIsSet(thisCodeBlock)) { + thisCodeBlock.style.maxHeight = fullHeight; + // mark code block as expanded + pushClass(outerBlock, panelExpanded) + } else { + thisCodeBlock.style.maxHeight = thisCodeBlock.dataset.height; + // unmark code block as expanded + deleteClass(outerBlock, panelExpanded) + } + } + + if(isCopyIcon) { + // clone code element + const codeElementClone = codeElement.cloneNode(true); + copyCode(codeElementClone); + } + } + }); + + (function addLangLabel() { + const blocks = codeBlocks(); + blocks.forEach(function(block){ + let label = block.dataset.lang; + label = label === 'sh' ? 'bash' : label; + if(label !== "fallback") { + const labelEl = createEl(); + labelEl.textContent = label; + pushClass(labelEl, 'lang'); + block.closest(`.${highlightWrap}`).appendChild(labelEl); + } + }); + })(); +})(); + +; +(function toggleColorModes(){ + const light = 'lit'; + const dark = 'dim'; + const storageKey = 'colorMode'; + const key = '--color-mode'; + const data = 'data-mode'; + const bank = window.localStorage; + + function currentMode() { + let acceptableChars = light + dark; + acceptableChars = [...acceptableChars]; + let mode = getComputedStyle(doc).getPropertyValue(key).replace(/\"/g, '').trim(); + + mode = [...mode].filter(function(letter){ + return acceptableChars.includes(letter); + }); + + return mode.join(''); + } + + function changeMode(isDarkMode) { + if(isDarkMode) { + bank.setItem(storageKey, light) + elemAttribute(doc, data, light); + } else { + bank.setItem(storageKey, dark); + elemAttribute(doc, data, dark); + } + } + + function setUserColorMode(mode = false) { + const isDarkMode = currentMode() == dark; + const storedMode = bank.getItem(storageKey); + if(storedMode) { + if(mode) { + changeMode(isDarkMode); + } else { + elemAttribute(doc, data, storedMode); + } + } else { + if(mode === true) { + changeMode(isDarkMode) + } + } + } + + setUserColorMode(); + + doc.addEventListener('click', function(event) { + let target = event.target; + let modeClass = 'color_choice'; + let animateClass = 'color_animate'; + let isModeToggle = containsClass(target, modeClass); + if(isModeToggle) { + pushClass(target, animateClass); + setUserColorMode(true); + } + }); +})(); + +function fileClosure(){ + + (function updateDate() { + const date = new Date(); + const year = date.getFullYear(); + const yearEl = elem('.year'); + yearEl ? yearEl.innerHTML = `${year}` : false; + })(); + + (function makeExternalLinks(){ + let links = elems('a'); + if(links) { + Array.from(links).forEach(function(link){ + let target, rel, blank, noopener, attr1, attr2, url, isExternal; + url = elemAttribute(link, 'href'); + isExternal = (url && typeof url == 'string' && url.startsWith('http')) && !url.startsWith(baseURL) ? true : false; + if(isExternal) { + target = 'target'; + rel = 'rel'; + blank = '_blank'; + noopener = 'noopener'; + attr1 = elemAttribute(link, target); + attr2 = elemAttribute(link, rel); + + attr1 ? false : elemAttribute(link, target, blank); + attr2 ? false : elemAttribute(link, rel, noopener); + } + }); + } + })(); + + let headingNodes = [], results, link, icon, current, id, + tags = ['h2', 'h3', 'h4', 'h5', 'h6']; + + current = document.URL; + + tags.forEach(function(tag){ + const article = elem('.post_content'); + if (article) { + results = article.getElementsByTagName(tag); + Array.prototype.push.apply(headingNodes, results); + } + }); + + headingNodes.forEach(function(node){ + link = createEl('a'); + link.className = 'link icon'; + id = node.getAttribute('id'); + if(id) { + link.href = `${current}#${id}`; + node.appendChild(link); + pushClass(node, 'link_owner'); + } + }); + + let inlineListItems = elems('ol li'); + if(inlineListItems) { + inlineListItems.forEach(function(listItem){ + let firstChild = listItem.children[0] + let containsHeading = isMatch(firstChild, tags); + containsHeading ? pushClass(listItem, 'align') : false; + }) + } + + function copyFeedback(parent) { + const copyText = document.createElement('div'); + const yanked = 'link_yanked'; + copyText.classList.add(yanked); + copyText.innerText = 'Link Copied'; + if(!elem(`.${yanked}`, parent)) { + parent.appendChild(copyText); + setTimeout(function() { + parent.removeChild(copyText) + }, 3000); + } + } + + (function copyHeadingLink() { + let deeplink, deeplinks, newLink, parent, target; + deeplink = 'link'; + deeplinks = elems(`.${deeplink}`); + if(deeplinks) { + document.addEventListener('click', function(event) + { + target = event.target; + parent = target.parentNode; + if (target && containsClass(target, deeplink) || containsClass(parent, deeplink)) { + event.preventDefault(); + newLink = target.href != undefined ? target.href : target.parentNode.href; + copyToClipboard(newLink); + target.href != undefined ? copyFeedback(target) : copyFeedback(target.parentNode); + } + }); + } + })(); + + (function copyLinkToShare() { + let copy, copied, excerpt, isCopyIcon, isInExcerpt, link, postCopy, postLink, target; + copy = 'copy'; + copied = 'copy_done'; + excerpt = 'excerpt'; + postCopy = 'post_copy'; + postLink = 'post_card'; + + doc.addEventListener('click', function(event) { + target = event.target; + isCopyIcon = containsClass(target, copy); + let isWithinCopyIcon = target.closest(`.${copy}`); + if (isCopyIcon || isWithinCopyIcon) { + let icon = isCopyIcon ? isCopyIcon : isWithinCopyIcon; + isInExcerpt = containsClass(icon, postCopy); + if (isInExcerpt) { + link = target.closest(`.${excerpt}`).previousElementSibling; + link = containsClass(link, postLink)? elemAttribute(link, 'href') : false; + } else { + link = window.location.href; + } + if(link) { + copyToClipboard(link); + pushClass(icon, copied); + } + } + const yankLink = '.link_yank'; + const isCopyLink = target.matches(yankLink); + const isCopyLinkIcon = target.closest(yankLink); + + if(isCopyLink || isCopyLinkIcon) { + event.preventDefault(); + const yankContent = isCopyLinkIcon ? elemAttribute(target.closest(yankLink), 'href') : elemAttribute(target, 'href'); + copyToClipboard(yankContent); + isCopyLink ? copyFeedback(target) : copyFeedback(target.parentNode); + } + }); + })(); + + (function hideAside(){ + let aside, title, posts; + aside = elem('.aside'); + title = aside ? aside.previousElementSibling : null; + if(aside && title.nodeName.toLowerCase() === 'h3') { + posts = Array.from(aside.children); + posts.length < 1 ? title.remove() : false; + } + })(); + + (function goBack() { + let backBtn = elem('.btn_back'); + let history = window.history; + if (backBtn) { + backBtn.addEventListener('click', function(){ + history.back(); + }); + } + })(); + + function showingImagePosition(){ + // whether or not to track image position for non-linear images within the article body element. + const thisPage = document.documentElement; + let showImagePositionOnPage = thisPage.dataset.figures; + + if(showImagePositionOnPage) { + showImagePosition = showImagePositionOnPage; + } + return showImagePosition === "true" ? true : false; + } + + function populateAlt(images) { + let imagePosition = 0; + + images.forEach((image) => { + let alt = image.alt; + const figure = image.parentNode.parentNode; + + // Image classes, including ::round + const altArr = alt.split('::').map(x => x.trim()) + if (altArr.length > 1) { + altArr[1].split(' ').filter(Boolean).forEach(cls =>{ + pushClass(image, cls); + alt = altArr[0] + }) + } + + // Image alignment (floating) + const modifiers = [':left', ':right']; + modifiers.forEach(function(modifier){ + const canModify = alt.includes(modifier); + if(canModify) { + pushClass(figure, `float_${modifier.replace(":", "")}`); + alt = alt.replace(modifier, ""); + } + }); + + // Inline images + const isInline = alt.includes(":inline"); + alt = alt.replace(":inline", ""); + if(isInline) { + modifyClass(figure, 'inline'); + } + + // Image captions + let addCaption = true + let captionText = '' + + if(image.title.trim().length) { + captionText = image.title.trim() + } else { + if(image.title === " ") { + addCaption = false + } else { + captionText = alt + } + } + + // Don't add a caption for featured images, inline images, or empty text + if( + image.matches(`.${featuredImageClass}`) || + containsClass(image, 'alt' && !isInline) || + !captionText.length + ) { + addCaption = false + } + + if (addCaption) { + let desc = document.createElement('figcaption'); + desc.classList.add(imageAltClass); + + // Add figure numbering + imagePosition += 1; + image.dataset.pos = imagePosition; + const showImagePosition = showingImagePosition(); + const thisImgPos = image.dataset.pos; + captionText = showImagePosition ? `${showImagePositionLabel} ${thisImgPos}: ${captionText}` : captionText; + desc.textContent = captionText; + + // If a caption exists, remove it + if(image.nextElementSibling) { + image.nextElementSibling.remove(); + } + + // Insert caption after image + // image.insertAdjacentHTML('afterend', desc.outerHTML); + + // insert caption before image -- modified by Mighten + image.insertAdjacentHTML('beforebegin', desc.outerHTML); + } + + // Persist modified alt to image element + image.alt = alt + }); + + hljs.initHighlightingOnLoad(); + } + + function largeImages(baseParent, images = []) { + if(images) { + images.forEach(function(image) { + window.setTimeout(function(){ + let actualWidth = image.naturalWidth; + let parentWidth = baseParent.offsetWidth; + let actionableRatio = actualWidth / parentWidth; + + if (actionableRatio > 1) { + pushClass(image.parentNode.parentNode, imageScalableClass); + image.parentNode.parentNode.dataset.scale = actionableRatio; + } + }, 100) + }); + } + } + + (function AltImage() { + let post = elem('.post_content'); + let images = post ? post.querySelectorAll('img') : false; + images ? populateAlt(images) : false; + largeImages(post, images); + })(); + + doc.addEventListener('click', function(event) { + let target = event.target; + isClickableImage = target.matches(`.${imageScalableClass}`) || target.closest(`.${imageScalableClass}`) ; + + if(isClickableImage) { + let hasClickableImage = containsClass(target.children[0], imageScalableClass); + if(hasClickableImage) { + modifyClass(target, scaleImageClass); + } + } + + if(isClickableImage) { + let figure = target.closest('figure'); + modifyClass(figure, scaleImageClass); + } + + goBack(target); + }); + + const tables = elems('table'); + if (tables) { + const scrollable = 'scrollable'; + tables.forEach(function(table) { + const wrapper = createEl(); + wrapper.className = scrollable; + wrapEl(table, wrapper); + }); + } + + function toggleTags(target = null) { + const tagsButtonClass = 'post_tags_toggle'; + const tagsButtonClass2 = 'tags_hide'; + const tagsShowClass = 'jswidgetopen'; + const postTagsWrapper = elem(`.${tagsShowClass}`); + target = target === null ? postTagsWrapper : target; + const showingAllTags = target.matches(`.${tagsShowClass}`); + const isExandButton = target.matches(`.${tagsButtonClass}`); + const isCloseButton = target.matches(`.${tagsButtonClass2}`) || target.closest(`.${tagsButtonClass2}`); + const isButton = isExandButton || isCloseButton; + const isActionable = isButton || showingAllTags; + + if(isActionable) { + if(isButton) { + if(isExandButton) { + let allTagsWrapper = target.nextElementSibling + pushClass(allTagsWrapper, tagsShowClass); + } else { + deleteClass(postTagsWrapper, tagsShowClass); + } + } else { + isActionable ? deleteClass(target, tagsShowClass) : false; + } + } + } + + (function showAllPostTags(){ + doc.addEventListener('click', function(event){ + const target = event.target; + toggleTags(target) + }); + + horizontalSwipe(doc, toggleTags, 'left'); + })(); + + (function navToggle() { + doc.addEventListener('click', function(event){ + const target = event.target; + const open = 'jsopen'; + const navCloseIconClass = '.nav_close'; + const navClose = elem(navCloseIconClass); + const isNavToggle = target.matches(navCloseIconClass) || target.closest(navCloseIconClass); + const harmburgerIcon = navClose.firstElementChild.firstElementChild; + if(isNavToggle) { + event.preventDefault(); + modifyClass(doc, open); + modifyClass(harmburgerIcon, 'isopen'); + } + + if(!target.closest('.nav') && elem(`.${open}`)) { + modifyClass(doc, open); + let navIsOpen = containsClass(doc, open); + !navIsOpen ? modifyClass(harmburgerIcon, 'isopen') : false; + } + + const navItem = 'nav_item'; + const navSub = 'nav_sub'; + const showSub = 'nav_open'; + const isNavItem = target.matches(`.${navItem}`); + const isNavItemIcon = target.closest(`.${navItem}`) + + if(isNavItem || isNavItemIcon) { + const thisItem = isNavItem ? target : isNavItemIcon; + const hasNext = thisItem.nextElementSibling + const hasSubNav = hasNext ? hasNext.matches(`.${navSub}`) : null; + if (hasSubNav) { + event.preventDefault(); + Array.from(thisItem.parentNode.parentNode.children).forEach(function(item){ + const targetItem = item.firstElementChild; + targetItem != thisItem ? deleteClass(targetItem, showSub) : false; + }); + modifyClass(thisItem, showSub); + } + } + }); + })(); + + function isMobileDevice() { + const agent = navigator.userAgent.toLowerCase(); + const isMobile = agent.includes('android') || agent.includes('iphone'); + return isMobile; + }; + + (function ifiOS(){ + // modify backto top button + const backToTopButton = elem('.to_top'); + const thisOS = getMobileOperatingSystem(); + const ios = 'ios'; + if(backToTopButton && thisOS === 'iOS') { + pushClass(backToTopButton, ios); + } + // precisely position back to top button on large screens + const buttonParentWidth = backToTopButton.parentNode.offsetWidth; + const docWidth = doc.offsetWidth; + let leftOffset = (docWidth - buttonParentWidth) / 2; + const buttonWidth = backToTopButton.offsetWidth; + leftOffset = leftOffset + buttonParentWidth - buttonWidth; + if(!isMobileDevice()){ + backToTopButton.style.left = `${leftOffset}px`; + } + })(); + + (function sortTags() { + doc.addEventListener('click', function(event){ + const active = 'active'; + const target = event.target; + const isSortButton = target.matches('.tags_sort') || target.matches('.tags_sort span'); + if(isSortButton) { + const tagsList = target.closest('.tags_list'); + const sortButton = elem('.tags_sort', tagsList); + modifyClass(sortButton, 'sorted'); + const tags = elems('.post_tag', tagsList); + Array.from(tags).forEach(function(tag){ + const order = tag.dataset.position; + const reverseSorting = containsClass(tag, active); + tag.style.order = reverseSorting ? 0 : -order; + modifyClass(tag, active); + }) + } + }) + })(); + + (function shareViaLinkedin() { + doc.addEventListener('click', function(event){ + const linkedin = '.linkedin'; + const target = event.target; + if(target.matches(linkedin) || target.closest(linkedin)) { + window.open('http://www.linkedin.com/shareArticle?mini=true&url='+encodeURIComponent(window.location.href), '', 'left=0,top=0,width=650,height=420,personalbar=0,toolbar=0,scrollbars=0,resizable=0'); + } + }); + })(); + + // add new code above this line +} + +window.addEventListener(pageHasLoaded, fileClosure()); + +; +// add custom js in this file \ No newline at end of file diff --git a/favicon/android-chrome-192x192.png b/favicon/android-chrome-192x192.png new file mode 100644 index 0000000..8532973 Binary files /dev/null and b/favicon/android-chrome-192x192.png differ diff --git a/favicon/android-chrome-256x256.png b/favicon/android-chrome-256x256.png new file mode 100644 index 0000000..58b1caf Binary files /dev/null and b/favicon/android-chrome-256x256.png differ diff --git a/favicon/apple-touch-icon.png b/favicon/apple-touch-icon.png new file mode 100644 index 0000000..9f75570 Binary files /dev/null and b/favicon/apple-touch-icon.png differ diff --git a/favicon/browserconfig.xml b/favicon/browserconfig.xml new file mode 100644 index 0000000..70cb989 --- /dev/null +++ b/favicon/browserconfig.xml @@ -0,0 +1,9 @@ + + + + + + #da532c + + + diff --git a/favicon/carly.svg b/favicon/carly.svg new file mode 100644 index 0000000..2b41b2c --- /dev/null +++ b/favicon/carly.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/favicon/copy.svg b/favicon/copy.svg new file mode 100644 index 0000000..93e6e94 --- /dev/null +++ b/favicon/copy.svg @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/favicon/favicon-16x16.png b/favicon/favicon-16x16.png new file mode 100644 index 0000000..e8b7cc9 Binary files /dev/null and b/favicon/favicon-16x16.png differ diff --git a/favicon/favicon-32x32.png b/favicon/favicon-32x32.png new file mode 100644 index 0000000..bc24fe5 Binary files /dev/null and b/favicon/favicon-32x32.png differ diff --git a/favicon/favicon.ico b/favicon/favicon.ico new file mode 100644 index 0000000..94267fc Binary files /dev/null and b/favicon/favicon.ico differ diff --git a/favicon/link.svg b/favicon/link.svg new file mode 100644 index 0000000..6a60d1d --- /dev/null +++ b/favicon/link.svg @@ -0,0 +1 @@ + diff --git a/favicon/logo.png b/favicon/logo.png new file mode 100644 index 0000000..e9dc2e3 Binary files /dev/null and b/favicon/logo.png differ diff --git a/favicon/mstile-150x150.png b/favicon/mstile-150x150.png new file mode 100644 index 0000000..9e91eb1 Binary files /dev/null and b/favicon/mstile-150x150.png differ diff --git a/favicon/order.svg b/favicon/order.svg new file mode 100644 index 0000000..9e9161f --- /dev/null +++ b/favicon/order.svg @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/favicon/safari-pinned-tab.svg b/favicon/safari-pinned-tab.svg new file mode 100644 index 0000000..a3c950e --- /dev/null +++ b/favicon/safari-pinned-tab.svg @@ -0,0 +1,24 @@ + + + + +Created by potrace 1.14, written by Peter Selinger 2001-2017 + + + + + diff --git a/favicon/site.webmanifest b/favicon/site.webmanifest new file mode 100644 index 0000000..855b331 --- /dev/null +++ b/favicon/site.webmanifest @@ -0,0 +1,19 @@ +{ + "name": "", + "short_name": "", + "icons": [ + { + "src": "/favicon/android-chrome-192x192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/favicon/android-chrome-256x256.png", + "sizes": "256x256", + "type": "image/png" + } + ], + "theme_color": "#ffffff", + "background_color": "#ffffff", + "display": "standalone" +} diff --git a/index.html b/index.html new file mode 100644 index 0000000..7de0eb5 --- /dev/null +++ b/index.html @@ -0,0 +1,890 @@ + + + + + +Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
    +
  • +
    +
    +

    + KIA CH01 Introducing Kubernetes +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Spring Framework +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Maven +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Docker +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + PuTTY with OpenSSH +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Security +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Distributed Systems +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Networking +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Operating System +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Linked List +

    + + + +
    + +
    +
  • + + +
  • + +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/index.json b/index.json new file mode 100644 index 0000000..0ae1398 --- /dev/null +++ b/index.json @@ -0,0 +1 @@ +[{"body":"","link":"https://mighten.github.io/","section":"","tags":null,"title":""},{"body":"","link":"https://mighten.github.io/tags/cloud-native/","section":"tags","tags":null,"title":"Cloud-Native"},{"body":"","link":"https://mighten.github.io/tags/k8s/","section":"tags","tags":null,"title":"k8s"},{"body":"","link":"https://mighten.github.io/series/k8s-in-action/","section":"series","tags":null,"title":"k8s-in-action"},{"body":"Hi there.\nToday, let us read the Chapter 01: Introducing Kubernetes of Kubernetes in Action\n the history of software developing isolation by containers how containers and Docker are used by Kubernetes how to simplify works by Kubernetes The software architecture has transitioned from Monolithic to Microservice. Legacy software applications were big monoliths; nowadays, microservices, the small and independently running components, are introduced to decouple from each other, and are therefore easily developed, deployed, updated, and scaled, to meet changing business requirements.\nKubernetes (k8s) is introduced to reduce complexity brought by bigger number of microservices, automating the process of scheduling components to our servers, automatic configuration, supervision, and failure-handling. K8s abstracts the hardware infrastructure as a single enormous computational resource, selects a server for each component, deploys it, and enables it to easily find and communicate with all the other components.\n1.1 Understanding the need for a system like Kubernetes In this section, the book talks about how the development and deployment of applications has changed in recent years, caused by:\n splitting big monolithic apps into smaller microservices the changes in the infrastructure that runs those apps 1.1.1 Moving from monolithic to microservices Monolithic applications: components that are all tightly coupled together and have to be developed, deployed, and managed as one entity, because they all run as a single OS process.\nmicroservices: smaller independently deployable components.\n Monolithic Microservices components tightly coupled together independently deployable scaling vertical scaling (scaling up) horizontal scaling (scaling out) communication function invoking well-defined interfaces (RESTful APIs, AMQP, etc.) changes redeployment of whole system minimal redeployment deployment easy tedious and error-prone debug/ trace easy hard: span multiple processes and machines (requires Zipkin) 1.1.2 Providing a consistent environment to applications The environments on which the apps rely can differ from one machine to another, from one operating system to another, and from one library to another.\nA consistent environment is required, to prevent failures :\n exact same operating system, libraries, system configuration, networking environment, etc. add applications to the same server without affecting any of the existing applications on that server. 1.1.3 Moving to continuous delivery: DevOps and NoOps Nowadays, there are two typical practices that the same team develops the app, deploys it, and takes cares of it over its whole lifetime:\n DevOps: a practice that the developer, QA, and operations teams collaborate throughout the whole process. a better understanding of issues from users and ops team, early feedback streamlining the deployment process, more often of releasing newer versions of applications NoOps: a practice that the developers can deploy applications themselves without knowing hardware infrastructure and without dealing with the ops team. Kubernetes allows developers to configure and deploy their apps independently sysadmins focus on how to keep the underlying infrastructure up and running, rather than on how the apps run on top of the underlying infrastructure. 1.2 Introducing container technologies Kubernetes uses Linux container technologies to provide isolation.\n1.2.1 What are containers Containers are much more lightweight (than VMs), which allows you to run many software components on the same hardware.\n the process in the container is isolated from other processes inside the same host OS containers consume only necessary resources (while VMs require a whole separate operating systems and additional compute resources) Two mechanisms that containers use to isolate processes: Linux Namespaces, and Linux Control Groups(cgroups)\n Linux Namespaces\nLinux Namespaces isolates system resources, and make each process can only see resources that are inside the same namespace.\nThe following table shows kinds of namespace:\n namespace meaning mnt Mount pid Process ID net Network namespace 1 ipc Inter-process communication UTS hostname and domain name 2 user User ID Linux Control Groups (cgroups)\nLinux Control Groups(cgroups) is a Linux kernel feature that can limit the resource usage of a process, or a group of processes.\n 1.2.2 Introducing the Docker container platform Docker is a platform for packaging, distributing, and running applications.\n Image: packaging application and environment, comprised of: isolated filesystem, which is available to the app metadata, which is used to execute the image on running image Registry: a (public or private) repository that stores and shares Docker images. push: uploading the image to a registry pull: downloading the image from a registry Container: a process that is isolated (running) and resource-constrained, running on the host OS, created from a Docker-based container image. @startuml\rstart\r:Docker builds image;\r:Docker pushes image to registry;\r:Docker pulls image from registry;\r:Docker runs container from image;\rstop\r@enduml\rDocker container images are composed of \u0026quot;layers\u0026quot;:\n shared and reused by building a new image on top of an existing parent image speeding up distribution across network reducing the storage footprint (each layer stored only once) readonly for layers in images until a new container is run, and a new writable layer is to be created; until a write request is made to a file located in underlying image layers, the write operation is then applied to the newly created top-most layer that contains a copy of the file. However, Docker uses Linux kernel of the host OS, it therefore does have limitations:\n same version of Linux kernel same kernel modules available 1.2.3 Introducing 'rkt' — an alternative to Docker Just like Docker, rkt is a platform for running containers, but with a strong emphasis on security, composability, and conforming to open standards.\n1.3 Introducing Kubernetes Kubernetes is a software system that allows you to easily deploy and manage containerized applications.\n1.3.1 The origins of Kubernetes Google invented Kubernetes out of its internal systems like 'Borg' and 'Omega':\n Simplification of Development and Management higher utilization of infrastructure 1.3.2 Looking at Kubernetes from the top of a mountain There are 3 features that Kubernetes has:\n easy deployment and management\n Linux containers to run heterogeneous applications without detailed knowledge of their internals without manual deployment on each host containerization to isolate applications, on shared hardware optimal hardware utilization complete isolation of hosted applications abstraction of the underlying infrastructure\n runs applications on thousands of nodes as if all nodes were one single enormous computer easy development, deployment and management for both development and the operations teams Deploying applications in Kubernetes is a consistent process\n cluster nodes represent amount of resources available to the apps number of nodes does not change the process of deployment In practice, Kubernetes exposes the whole data center as a single deployment platform. Kubernetes allows developers to focus on implementing the actual features of the applications. And Kubernetes will handle infrastructure-related services (such as service discovery, scaling, load-balancing, self-healing, and leader election ).\n1.3.3 Architecture of a Kubernetes cluster Kubernetes cluster is composed of 2 types of nodes:\n Control Plane (Master): controls the cluster API Server: communicates with other components Scheduler: schedules apps by assigning a worker node to each deployable component of app Controller Manager: performs cluster-level functions, such as replicating components, keeping track of worker nodes, and handling node failures. etcd: a reliable distributed database that persistently stores the cluster configuration Worker Nodes: runs containerized applications Kubelet: talks to the API server and manages containers on its node kube-proxy (Kubernetes Service Proxy): load-balances network traffic between application components container runtime: runs containers, e.g., Docker rkt @startuml\rtitle \u0026quot;components of Kubernetes cluster\u0026quot;\rnode \u0026quot;Control Plane (master)\u0026quot; {\rdatabase \u0026quot;etcd\u0026quot; as etcd\rrectangle \u0026quot;API server\u0026quot; as apiServer\rrectangle \u0026quot;Scheduler\u0026quot; as scheduler\rrectangle \u0026quot;Controller Manager\u0026quot; as controllerManager\rscheduler --\u0026gt; apiServer\rcontrollerManager --\u0026gt; apiServer\rapiServer --\u0026gt; etcd\r}\rnode \u0026quot;Worker node(s)\u0026quot; {\rrectangle \u0026quot;Container Runtime\u0026quot; as containerRuntime\rrectangle \u0026quot;Kubelet\u0026quot; as kubelet\rrectangle \u0026quot;kube-proxy\u0026quot; as kubeProxy\rkubelet --\u0026gt; containerRuntime\rkubelet --\u0026gt; apiServer\rkubeProxy --\u0026gt; apiServer\r}\r@enduml\r1.3.4 Running an application in Kubernetes When the developer submits App Descriptor(a list of apps) to the master, Kubernetes then chooses worker nodes and deploys apps.\nAnd App Descriptor is used to describe the detail of the running container:\n which container images, or which images that contain your application how many replicas for each component how components are related to each other co-located: run together on the same worker node otherwise, spread around the cluster. whether a service is internal or external The diagram below shows how an App Descriptor works in starting app:\n@startuml\rstart\r:Developer submits App Descriptor to API Server;\r:Scheduler schedules the specified groups of containers onto the available worker nodes;\r:Kubelet on the worker node instruct Container Runtime to pull and run the containers;\rstop\r@enduml\rAfter the application is running, Kubernetes continuously makes sure that the deployed state of the application always matches the description :\n if one instance stopped working, Kubernetes will restart this instance if one worker node dies (becomes inaccessible), Kubernetes will select a new node and run all the previous containers on the newly selected worker node If workload fluctuates, Kubernetes can also automatically scale(increase/decrease) the number of replicas, based on real-time metrics your app exposes, such as CPU load, memory consumption, queries per second, etc.\nHowever, Kubernetes may need to move containers around the cluster, under the following 2 circumstances:\n worker node failure running container evicted to make room for other containers To ensure services remain available to clients during the movement of containers, Kubernetes uses environment variables to expose a single static IP address to all applications running in the cluster. This allows clients to access the containers with a constant IP address, and kube-proxy will also ensure connections to the service are load-balanced across all the containers providing the service.\n1.3.5 benefits of using Kubernetes Simplifying application deployment\n Achieving better utilization of hardware\n Health checking and self-healing\n Automatic scaling\n Simplifying application development\n Each network interface belongs to exactly one namespace, but can be moved from one namespace to another.\u0026#160;\u0026#x21a9;\u0026#xfe0e;\n Different UTS namespaces makes processes see different host names.\u0026#160;\u0026#x21a9;\u0026#xfe0e;\n ","link":"https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/","section":"post","tags":["Cloud-Native","Kubernetes","k8s"],"title":"KIA CH01 Introducing Kubernetes"},{"body":"","link":"https://mighten.github.io/tags/kubernetes/","section":"tags","tags":null,"title":"Kubernetes"},{"body":"","link":"https://mighten.github.io/post/","section":"post","tags":null,"title":"Posts"},{"body":"","link":"https://mighten.github.io/series/","section":"series","tags":null,"title":"Series"},{"body":"","link":"https://mighten.github.io/tags/","section":"tags","tags":null,"title":"Tags"},{"body":"","link":"https://mighten.github.io/tags/java/","section":"tags","tags":null,"title":"Java"},{"body":"","link":"https://mighten.github.io/tags/spring/","section":"tags","tags":null,"title":"Spring"},{"body":"Hi there!\nIn this blog, we talk about Spring Framework, a Java platform that provides comprehensive infrastructure support for developing Java applications. The content of this blog is shown below:\n Architecture Spring IoC Container Spring Beans Dependency Injection (DI) Spring Annotations Aspect Oriented Programming (AOP) 1. ARCHITECTURE The Spring Framework provides about 20 modules which can be used based on an application requirement.\n Test layer supports the testing of Spring components with JUnit or TestNG frameworks.\nCore Container layer consists of the Core, Beans, Context, and Spring Expression Language (SpEL) modules:\n Core provides the fundamental parts of the framework, including the Inversion of Control (IoC) and Dependency Injection (DI). Bean provides BeanFactory, an implementation of the factory pattern. Context is a medium to access any objects defined and configured, e.g., the ApplicationContext interface. SpEL provides Spring Expression Language for querying and manipulating an object graph at runtime. AOP layer provides an aspect-oriented programming implementation, allowing you to define method-interceptors and pointcuts to decouple the code.\nAspects layer provides integration with AspectJ, an AOP framework.\nInstrumentation layer provides class instrumentation support and class loader implementations.\nMessaging layer provides support for STOMP as the WebSocket sub-protocol.\nData Access/Integration layer consists of JDBC, ORM, OXM, JMS and Transaction:\n JDBC provides a JDBC-abstraction layer to simplify JDBC related coding. ORM provides integration layers for object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. OXM provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream. Java Messaging Service (JMS) produces and consumes messages. Transaction supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs. Web layer consists of the Web, MVC, WebSocket, and Portlet:\n MVC provides Model-View-Controller (MVC) implementation for Spring web applications. WebSocket provides support for WebSocket-based, two-way communication between the client and the server in web applications. Web provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context. Portlet provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module. 2. IOC CONTAINER Inversion of Control (IoC) is a design principle where the control of flow and dependencies in a program are inverted, meaning that the control is handed over to a container or framework which can manage dependencies (instead of allowing component to control its dependencies).\nDependency refers to an object that a class relies on to perform its functionality. Dependency Injection (DI) is a specific implementation of the IoC principle. DI injects the dependencies from outside the class (rather than having the class create them itself). Instead of hardcoding within the class, the dependencies are injected into it from an external source, usually a container or framework.\nIn Spring Framework, there are two types of IoC containers: BeanFactory and ApplicationContext. The ApplicationContext container includes all functionality of the BeanFactory container and thus is better; while BeanFactory is mostly used for lightweight applications where data volume and speed is significant.\n2.1 BeanFactory BeanFactory is the simplest container providing the basic support for DI. BeanFactory is defined by the org.springframework.beans.factory.BeanFactory interface.\nCode 1-1 shows how to use BeanFactory:\nCode 1-1(a). \u0026quot;Message.java\u0026quot;\n1package com.example; 2 3public class Message { 4 private String message; 5 6 public void setMessage(String message){ 7 this.message = message; 8 } 9 public void getMessage(){ 10 System.out.println(\u0026#34;Message : \u0026#34; + message); 11 } 12} Code 1-1(a) declares a class named Message, and it has a pair of getter/setter for class member named message.\nCode 1-1(b). \u0026quot;Beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;bean id = \u0026#34;demo\u0026#34; class = \u0026#34;com.example.Message\u0026#34;\u0026gt; 9 \u0026lt;property name = \u0026#34;message\u0026#34; value = \u0026#34;Hello World!\u0026#34;/\u0026gt; 10 \u0026lt;/bean\u0026gt; 11 12\u0026lt;/beans\u0026gt; Code 1-1(b) is a XML configuration file tell that a bean called demo is defined, and its message is set to \u0026quot;Hello World!\u0026quot;.\nCode 1-1(c). \u0026quot;BeanFactoryDemoTest.java\u0026quot;\n1package com.example; 2 3import org.springframework.beans.factory.xml.XmlBeanFactory; 4import org.springframework.core.io.ClassPathResource; 5 6public class BeanFactoryDemoTest { 7 public static void main(String[] args) { 8 XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource(\u0026#34;Beans.xml\u0026#34;)); 9 Message obj = (Message) factory.getBean(\u0026#34;demo\u0026#34;); 10 obj.getMessage(); 11 } 12} Code 1-1(c) is a test program, and it uses ClassPathResource() API to load the bean configuration file, and it uses XmlBeanFactory() to create and initialize beans in the configuration file \u0026quot;Beans.xml\u0026quot;.\nThen, getBean() method uses bean ID (\u0026quot;demo\u0026quot;) to return a generic object, which finally can be casted to the BeanFactoryDemo object. By invoking obj.getMessage(), the code 1-1(a) is executed, and shows:\n1Message : Hello World! Summary: this section uses Code 1-1(a, b, c) to show how to get bean by using BeanFactory.\n2.2 ApplicationContext ApplicationContext is similar to BeanFactory, but it adds enterprise-specific functionality.\nApplicationContext is defined by the org.springframework.context.ApplicationContext interface, with several implementations: FileSystemXmlApplicationContext, ClassPathXmlApplicationContext, and WebXmlApplicationContext.\n FileSystemXmlApplicationContext loads the definitions of the beans, from the XML bean configuration file (full path to file) to the constructor. ClassPathXmlApplicationContext loads the definitions of the beans from an XML file, and we need to set CLASSPATH. WebXmlApplicationContext loads the XML file with definitions of all beans from within a web application. Code 2-1, with Code 1-1(a, b), will show how to use FileSystemXmlApplicationContext of ApplicationContext:\nCode 2-1. \u0026quot;FileSystemXmlApplicationContextDemoTest.java\u0026quot;\n1package com.example; 2 3import org.springframework.context.ApplicationContext; 4import org.springframework.context.support.FileSystemXmlApplicationContext; 5 6public class FileSystemXmlApplicationContextDemoTest { 7 public static void main(String[] args) { 8 ApplicationContext context = new FileSystemXmlApplicationContext 9 (\u0026#34;C:/path/to/Beans.xml\u0026#34;); 10 11 Message obj = (Message) context.getBean(\u0026#34;demo\u0026#34;); 12 obj.getMessage(); 13 } 14} Now we will reuse the codes defined in Code 1-1(a, b), and run the Code 2-1:\n1Message : Hello World! Summary: this section uses Code 1-1(a, b), Code 2-1 to show how to get bean by using ApplicationContext, especially the FileSystemXmlApplicationContext.\n3. BEAN Bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Bean definition contains the information called configuration metadata:\nTable 3-1. Properties of Bean\n Properties Description id the bean identifier(unique) class the bean class to create the bean scope the scope of the objects created constructor-arg to inject the dependencies properties to inject the dependencies autowiring to inject the dependencies lazy-init let IoC container to create a bean instance at first requested init-method executed after properties set by the container destroy-method executed when the container is destroyed 3.1 Scope The scope of a bean defines the life cycle and visibility of that bean in the contexts we use it (singleton, prototype, request, session, global-session). In pratice, we mainly use singleton, prototype:\nsingleton: Spring IoC container creates exactly one instance of the object defined by that bean definition. Shown in Code 3-1, if we execute getBean(\u0026quot;demo\u0026quot;) multiple times, the object will always be the same one.\nCode 3-1. Snippet of \u0026quot;bean.xml\u0026quot;\n1\u0026lt;bean id = \u0026#34;demo\u0026#34; 2 class = \u0026#34;com.example.Message\u0026#34; 3 scope = \u0026#34;singleton\u0026#34;\u0026gt; 4\u0026lt;/bean\u0026gt; prototype: Spring IoC container creates a new bean instance of the object every time a request for that specific bean is made. Shown in Code 3-2, if we execute getBean(\u0026quot;demo\u0026quot;) multiple times, there will be corresponsing multiple quite different objects.\nCode 3-2. Snippet of \u0026quot;bean.xml\u0026quot;\n1\u0026lt;bean id = \u0026#34;demo\u0026#34; 2 class = \u0026#34;com.example.Message\u0026#34; 3 scope = \u0026#34;prototype\u0026#34;\u0026gt; 4\u0026lt;/bean\u0026gt; 3.2 Life Cycle Bean life cycle is managed by the Spring container. The spring container gets started before creating the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed.\nCode 3-3(a). \u0026quot;LifeCycleDemo.java\u0026quot;\n1package com.example; 2 3public class LifeCycleDemo { 4 public void init() { 5 System.out.println(\u0026#34;Bean initialized.\u0026#34;); 6 } 7 8 public void foo() { 9 System.out.println(\u0026#34;foo\u0026#34;); 10 } 11 12 public void destroy() { 13 System.out.println(\u0026#34;Bean destroyed.\u0026#34;); 14 } 15} In Code 3-3(a), a straightforward class named LifeCycleDemo is defined, comprising three methods: init(), foo(), and destroy(). Each of these methods prints out status information to indicate its current stage.\nCode 3-3(b). \u0026quot;beans.java\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;bean id = \u0026#34;life_cycle_demo\u0026#34; 9 class = \u0026#34;com.example.LifeCycleDemo\u0026#34; 10 init-method = \u0026#34;init\u0026#34; 11 destroy-method = \u0026#34;destroy\u0026#34;\u0026gt; 12 \u0026lt;/bean\u0026gt; 13 14\u0026lt;/beans\u0026gt; In Code 3-3(b), it defines a bean named \u0026quot;life_cycle_demo\u0026quot; of the class \u0026quot;com.example.LifeCycleDemo\u0026quot; with initialization(init) and destruction (destroy) methods.\nCode 3-3(c). \u0026quot;LifeCycleDemoTest.java\u0026quot;\n1package com.example; 2 3import org.springframework.context.support.AbstractApplicationContext; 4import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6public class LifeCycleDemoTest { 7 public static void main(String[] args) { 8 AbstractApplicationContext context = new ClassPathXmlApplicationContext(\u0026#34;beans.xml\u0026#34;); 9 10 LifeCycleDemo obj = (LifeCycleDemo) context.getBean(\u0026#34;life_cycle_demo\u0026#34;); 11 obj.foo(); 12 context.registerShutdownHook(); // display destroy info (registers a shutdown hook for the Spring application context) 13 } 14} In Code 3-3(c), it demonstrates how to use the Spring Framework to initialize the Spring container, retrieve a bean from the container, and invoke a method on the bean. Additionally, it ensures that the Spring context is properly closed when the application exits by registering a shutdown hook.\nWhen the Code 3-3(a, b, c) are executed, the following results should appear in the console:\n1Bean initialized. 2foo 3Bean destroyed. 3.3 Postprocessors BeanPostProcessor is an interface defined in org.springframework.beans.factory.config.BeanPostProcessor, and it allows for custom modification of new bean instance.\nCode 3-4 shows how to use Postprocessor.\nCode 3-4(a). \u0026quot;PostprocessorDemo.java\u0026quot;\n1package com.example; 2 3public class PostprocessorDemo { 4 public void init(){ 5 System.out.println(\u0026#34;init\u0026#34;); 6 } 7 8 public void foo() { 9 System.out.println(\u0026#34;foo...\u0026#34;); 10 } 11 12 public void destroy(){ 13 System.out.println(\u0026#34;destroy\u0026#34;); 14 } 15} In Code 3-4(a), just like Code 3-3(a), a straightforward class named PostprocessorDemo is defined, comprising three methods: init(), foo(), and destroy(). Each of these methods prints out status information to indicate its current stage.\nCode 3-4(b). \u0026quot;InitPostprocessorDemo.java\u0026quot;\n1package com.example; 2 3import org.springframework.beans.factory.config.BeanPostProcessor; 4import org.springframework.beans.BeansException; 5 6public class InitPostprocessorDemo implements BeanPostProcessor { 7 public Object postProcessBeforeInitialization(Object bean, String beanName) 8 throws BeansException { 9 10 System.out.println(\u0026#34;Before init of \u0026#34; + beanName); 11 return bean; 12 } 13 public Object postProcessAfterInitialization(Object bean, String beanName) 14 throws BeansException { 15 16 System.out.println(\u0026#34;After init of \u0026#34; + beanName); 17 return bean; 18 } 19} Code 3-4(b) is an example of implementing BeanPostProcessor, which prints a bean name before and after initialization of a bean. Note: the return type of postProcessBeforeInitialization and postProcessAfterInitialization is quite arbitrary, so they do not require bean as return values.\nCode 3-4(c). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;bean id = \u0026#34;demo\u0026#34; 9 class = \u0026#34;com.example.PostprocessorDemo\u0026#34; 10 init-method = \u0026#34;init\u0026#34; 11 destroy-method = \u0026#34;destroy\u0026#34; /\u0026gt; 12 13 \u0026lt;bean class = \u0026#34;com.example.InitPostprocessorDemo\u0026#34; /\u0026gt; 14 15\u0026lt;/beans\u0026gt; Code 3-4(c) defines two beans. The first bean with the ID \u0026quot;demo\u0026quot; associates itself with the class \u0026quot;com.example.PostprocessorDemo\u0026quot;, and it specifies an initialization method called \u0026quot;init\u0026quot; as well as a destruction method called \u0026quot;destroy\u0026quot;; the second bean serves as a custom post-processor for \u0026quot;demo\u0026quot; in the Spring Application Context.\nCode 3-4(d). \u0026quot;PostprocessorDemoTest.java\u0026quot;\n1package com.example; 2 3import org.springframework.context.support.AbstractApplicationContext; 4import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6public class PostprocessorDemoTest { 7 public static void main(String[] args) { 8 AbstractApplicationContext context = new ClassPathXmlApplicationContext(\u0026#34;beans.xml\u0026#34;); 9 10 PostprocessorDemo obj = (PostprocessorDemo) context.getBean(\u0026#34;demo\u0026#34;); 11 obj.foo(); 12 context.registerShutdownHook(); 13 } 14} Code 3-4(d) demonstrates the usage of a Spring Framework postprocessor. It only load the bean with ID \u0026quot;demo\u0026quot; but not the Postprocessor class. And The expected output of Code 3-4 should be:\n1Before init of demo 2init 3After init of demo 4foo... 5destroy 3.4 Definition Inheritance Spring supports bean definition inheritance to promote reusability and minimize development effort.\nCode 3-5 shows the basic usage of Bean definition inheritance:\nCode 3-5(a). \u0026quot;Hello.java\u0026quot;\n1package com.example; 2 3public class Hello { 4 private String name; 5 private String type; 6 7 public void setName(String name){ 8 this.name = name; 9 } 10 public void setType(String type){ 11 this.type = type; 12 } 13 public void sayHello(){ 14 System.out.println(\u0026#34;Hello \u0026#34; + name + \u0026#34;, type = \u0026#34; + type); 15 } 16} Code 3-5(a) shows a basic class called Hello, and Hello has two private instance variables, name and type, along with corresponding setter methods setName and setType to set their values. Additionally, the class contains a method sayHello() that prints a greeting message with the name and type values.\nCode 3-5(b). \u0026quot;HelloStudent.java\u0026quot;\n1package com.example; 2 3public class HelloStudent { 4 private String name; 5 private String type; 6 private String school; 7 8 public void setName(String name) { 9 this.name = name; 10 } 11 12 public void setType(String type) { 13 this.type = type; 14 } 15 16 public void setSchool(String school) { 17 this.school = school; 18 } 19 20 public void sayHello(){ 21 System.out.println(\u0026#34;Hello \u0026#34; + name + \u0026#34;, type = \u0026#34; + type + \u0026#34;, from \u0026#34; + school); 22 } 23} Code 3-5(b) introduces a new class called HelloStudent which extends the functionality of the previous Hello class by adding an additional private instance variable, school, and a corresponding setter method setSchool() to set its value. With this extension, the HelloStudent class now represents a student entity with a name, a type, and the school they attend.\nCode 3-5(c). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;bean id = \u0026#34;hello\u0026#34; class = \u0026#34;com.example.Hello\u0026#34;\u0026gt; 9 \u0026lt;property name = \u0026#34;name\u0026#34; value = \u0026#34;Tom\u0026#34;/\u0026gt; 10 \u0026lt;property name = \u0026#34;type\u0026#34; value = \u0026#34;student\u0026#34;/\u0026gt; 11 \u0026lt;/bean\u0026gt; 12 13 \u0026lt;bean id =\u0026#34;helloStudent\u0026#34; class = \u0026#34;com.example.HelloStudent\u0026#34; parent = \u0026#34;hello\u0026#34;\u0026gt; 14 \u0026lt;property name = \u0026#34;name\u0026#34; value = \u0026#34;Jerry\u0026#34;/\u0026gt; 15 \u0026lt;property name = \u0026#34;school\u0026#34; value = \u0026#34;MIT\u0026#34;/\u0026gt; 16 \u0026lt;/bean\u0026gt; 17\u0026lt;/beans\u0026gt; Code 3-5(c) sets up two beans, hello and helloStudent, and helloStudent inherits bean definition from its parent called hello. Note the parent=\u0026quot;hello\u0026quot; attribute in the \u0026quot;helloStudent\u0026quot; bean definition: This attribute indicates that \u0026quot;helloStudent\u0026quot; is a child bean of \u0026quot;hello,\u0026quot; and it will inherit the properties defined in the \u0026quot;hello\u0026quot; bean (i.e., type is set to student).\nCode 3-5(d). \u0026quot;HelloInheritanceTest.java\u0026quot;\n1package com.example; 2 3import org.springframework.context.ApplicationContext; 4import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6public class HelloInheritanceTest { 7 public static void main(String[] args) { 8 ApplicationContext context = new ClassPathXmlApplicationContext(\u0026#34;beans.xml\u0026#34;); 9 10 Hello tom = (Hello) context.getBean(\u0026#34;hello\u0026#34;); 11 tom.sayHello(); 12 13 HelloStudent jerry = (HelloStudent) context.getBean(\u0026#34;helloStudent\u0026#34;); 14 jerry.sayHello(); 15 } 16} Code 3-5(d) demonstrates how to incorporate beans hello and helloStudent. And the expected output for Code 3-5 should be:\n1Hello Tom, type = student 2Hello Jerry, type = student, from MIT 4. DI Dependency injection (DI) is a pattern we can use to implement IoC. When writing a complex Java application, DI helps in gluing these classes together and keeping them independent at the same time.\nThere are two major variants for DI: Constructor-based DI, and Setter-based DI. It is recommended to use constructor arguments for mandatory dependencies and setters for optional dependencies.\nIn this section, we use two simple examples to show how DI works, and Code 4-1(a, b) are the generic parts for these two examples:\nCode 4-1(a). \u0026quot;MessageService.java\u0026quot;\n1package com.example.di; 2 3public interface MessageService { 4 String getMessage(); 5} Code 4-1(a) defines an interface MessageService that declares a method getMessage().\nCode 4-1(b). \u0026quot;MessageServiceTest.java\u0026quot;\n1package com.example.di; 2 3import org.springframework.context.ApplicationContext; 4import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6public class MessageServiceTest { 7 public static void main(String[] args) { 8 ApplicationContext context = new ClassPathXmlApplicationContext(\u0026#34;beans.xml\u0026#34;); 9 MessageService messageService = (MessageService) context.getBean(\u0026#34;messageService\u0026#34;); 10 String message = messageService.getMessage(); 11 System.out.println(\u0026#34;Message: \u0026#34; + message); 12 } 13} Code 4-1(b) creates a class named MessageServiceTest that will load the Spring application context and retrieve the MessageService bean.\n4.1 Constructor-based DI Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments (each representing a dependency on the other class).\nCode 4-1(a, b) and Code 4-2(a, b) demonstrate how to use Constructor-based DI:\nCode 4-2(a). \u0026quot;MessageServiceImplConstructorBased.java\u0026quot;\n1package com.example.di; 2 3public class MessageServiceImplConstructorBased implements MessageService { 4 private String message; 5 6 // Constructor for DI 7 public MessageServiceImplConstructorBased(String message) { 8 this.message = message; 9 } 10 11 @Override 12 public String getMessage() { 13 return message; 14 } 15} Code 4-2(a) defines the implementation of the MessageService interface as MessageServiceImplConstructorBased.\nCode 4-2(b). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;bean id=\u0026#34;messageService\u0026#34; class=\u0026#34;com.example.di.MessageServiceImplConstructorBased\u0026#34;\u0026gt; 9 \u0026lt;constructor-arg value=\u0026#34;Hello, this is a constructor-based DI example!\u0026#34; /\u0026gt; 10 \u0026lt;/bean\u0026gt; 11 12\u0026lt;/beans\u0026gt; Code 4-2(b) defines a bean with the ID \u0026quot;messageService\u0026quot; and specifies the class com.example.di.MessageServiceImplConstructorBased. It also provides a constructor argument (value = \u0026quot;Hello, this is a constructor-based DI example!\u0026quot;) for DI. This argument will be passed to the constructor of MessageServiceImplConstructorBased when the bean is created.\nThe expected output for Code 4-1(a, b) and Code 4-2(a, b) is:\n1Message: Hello, this is a constructor-based DI example! Now, let's dig it deeper. If we want to pass multiple objects into a constructor:\nCode 4-2-extend(a). \u0026quot;Foo.java\u0026quot;\n1package com.example.di; 2 3public class Foo { 4 private int id; 5 private String name; 6 private Bar bar; 7 private Baz baz; 8 9 //Constructor for DI 10 public Foo(int id, String name, Bar bar, Baz baz) { 11 this.id = id; 12 this.name = name; 13 this.bar = bar; 14 this.baz = baz; 15 } 16 17 public show() { 18 // ... 19 } 20} Code 4-2-extend(a) shows a more complex example of Constructor-based DI. Assuming the Bar and Baz classes in the package com.example.di, we will initialize Foo object with a four-parameter (id, name, bar, and baz) constructor.\nCode 4-2-extend(b). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;!-- Define the bean for the Bar and Baz --\u0026gt; 9 \u0026lt;bean id=\u0026#34;bar\u0026#34; class=\u0026#34;com.example.di.Bar\u0026#34; /\u0026gt; 10 \u0026lt;bean id=\u0026#34;baz\u0026#34; class=\u0026#34;com.example.di.Baz\u0026#34; /\u0026gt; 11 12 \u0026lt;!-- Define the bean for the Foo class with constructor-based Dependency Injection --\u0026gt; 13 \u0026lt;bean id=\u0026#34;foo\u0026#34; class=\u0026#34;com.example.di.Foo\u0026#34;\u0026gt; 14 \u0026lt;constructor-arg value=\u0026#34;1001\u0026#34; /\u0026gt; \u0026lt;!-- id --\u0026gt; 15 \u0026lt;constructor-arg value=\u0026#34;Tommy\u0026#34; /\u0026gt; \u0026lt;!-- name --\u0026gt; 16 \u0026lt;constructor-arg ref=\u0026#34;bar\u0026#34; /\u0026gt; \u0026lt;!-- bar --\u0026gt; 17 \u0026lt;constructor-arg ref=\u0026#34;baz\u0026#34; /\u0026gt; \u0026lt;!-- baz --\u0026gt; 18 \u0026lt;/bean\u0026gt; 19 20\u0026lt;/beans\u0026gt; Code 4-2-extend(b) shows how to pass different parameters into constructor. For simple types like int and String, use value; for complex types like Bar and Baz, define the separate beans and then use ref.\nCode 4-2-extend(c). \u0026quot;FooTest.java\u0026quot;\n1package com.example.di; 2 3import org.springframework.context.ApplicationContext; 4import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6public class FooTest { 7 public static void main(String[] args) { 8 ApplicationContext context = new ClassPathXmlApplicationContext(\u0026#34;beans.xml\u0026#34;); 9 Foo foo = (Foo) context.getBean(\u0026#34;foo\u0026#34;); 10 foo.show(); 11 } 12} So, when passing a reference to an object, use ref attribute of \u0026lt;constructor-arg\u0026gt; tag; when passing a value directly, use value attribute.\n4.2 Setter-based DI Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.\nCode 4-1(a, b) and Code 4-3(a, b) demonstrate how to use Setter-based DI:\nCode 4-3(a). \u0026quot;MessageServiceImplSetterBased.java\u0026quot;\n1package com.example.di; 2 3public class MessageServiceImplSetterBased implements MessageService { 4 private String message; 5 6 // Setter for DI 7 public void setMessage(String message) { 8 this.message = message; 9 } 10 11 @Override 12 public String getMessage() { 13 return message; 14 } 15} Code 4-3(a) defines the implementation of the MessageService interface using Setter setMessage() to pass values into bean.\nCode 4-3(b). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;bean id=\u0026#34;messageService\u0026#34; class=\u0026#34;com.example.di.MessageServiceImplSetterBased\u0026#34;\u0026gt; 9 \u0026lt;property name=\u0026#34;message\u0026#34; value=\u0026#34;Hello, this is a setter-based DI example!\u0026#34; /\u0026gt; 10 \u0026lt;/bean\u0026gt; 11 12\u0026lt;/beans\u0026gt; Code 4-3(b) provides a \u0026lt;property\u0026gt; element with the name \u0026quot;message\u0026quot; and the value \u0026quot;Hello, this is a setter-based DI example!\u0026quot;.\nThe expected output for Code 4-1(a, b) and Code 4-3(a, b) is:\n1Message: Hello, this is a setter-based DI example! Now, let's dig it deeper. If we want to use multiple setters:\nCode 4-3-extend(a). \u0026quot;Foo.java\u0026quot;\n1package com.example.di; 2 3public class Foo { 4 private int id; 5 private String name; 6 private Bar bar; 7 private Baz baz; 8 9 // Setters for DI 10 public void setId(int id) { 11 this.id = id; 12 } 13 14 public void setName(String name) { 15 this.name = name; 16 } 17 18 public void setBar(Bar bar) { 19 this.bar = bar; 20 } 21 22 public void setBaz(Baz baz) { 23 this.baz = baz; 24 } 25 26 // other methods ... 27 public void show() { 28 // ... 29 } 30} Code 4-3-extend(a) shows a more complex example of Constructor-based DI. Assuming the Bar and Baz classes in the package com.example.di, we will initialize Foo object with four setters (setId(), setName(), setBar(), and setBaz()).\nCode 4-3-extend(b). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;!-- Define the bean for the Bar and Baz --\u0026gt; 9 \u0026lt;bean id=\u0026#34;bar\u0026#34; class=\u0026#34;com.example.di.Bar\u0026#34; /\u0026gt; 10 \u0026lt;bean id=\u0026#34;baz\u0026#34; class=\u0026#34;com.example.di.Baz\u0026#34; /\u0026gt; 11 12 \u0026lt;!-- Define the bean for the Foo class with setter-based Dependency Injection --\u0026gt; 13 \u0026lt;bean id=\u0026#34;foo\u0026#34; class=\u0026#34;com.example.di.Foo\u0026#34;\u0026gt; 14 \u0026lt;property name=\u0026#34;id\u0026#34; value=\u0026#34;1001\u0026#34; /\u0026gt; 15 \u0026lt;property name=\u0026#34;name\u0026#34; value=\u0026#34;Tommy\u0026#34; /\u0026gt; 16 \u0026lt;property name=\u0026#34;bar\u0026#34; ref=\u0026#34;bar\u0026#34; /\u0026gt; 17 \u0026lt;property name=\u0026#34;baz\u0026#34; ref=\u0026#34;baz\u0026#34; /\u0026gt; 18 \u0026lt;/bean\u0026gt; 19 20\u0026lt;/beans\u0026gt; Code 4-3-extend(b) shows how to pass different parameters into setters. For simple types like int and String, use value; for complex types like Bar and Baz, define the separate beans and then use ref.\nCode 4-3-extend(c). \u0026quot;FooTest.java\u0026quot;\n1package com.example.di; 2 3import org.springframework.context.ApplicationContext; 4import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6public class FooTest { 7 public static void main(String[] args) { 8 ApplicationContext context = new ClassPathXmlApplicationContext(\u0026#34;beans.xml\u0026#34;); 9 Foo foo = context.getBean(\u0026#34;foo\u0026#34;, Foo.class); 10 foo.show(); 11 } 12} In Setter-based DI, the Spring container will call the appropriate setter methods on the Foo instance after creating it, injecting the Bar and Baz dependencies into the Foo object foo.\n4.3 Injecting Collection Injecting collections refers to the process of providing a collection of objects (array, list, set, map, or properties) to a Spring bean during its initialization.\nCode 4-4(a). \u0026quot;CollectionInjection.java\u0026quot;\n1package com.example.di; 2 3import java.util.List; 4import java.util.Set; 5import java.util.Map; 6import java.util.Properties; 7 8public class CollectionInjection { 9 private int[] array; 10 private List\u0026lt;String\u0026gt; list; 11 private Set\u0026lt;String\u0026gt; set; 12 private Map\u0026lt;String,String\u0026gt; map; 13 private Properties properties; 14 15 // Setters 16 public void setArray(int[] array) { 17 this.array = array; 18 } 19 20 public void setList(List\u0026lt;String\u0026gt; list) { 21 this.list = list; 22 } 23 24 public void setSet(Set\u0026lt;String\u0026gt; set) { 25 this.set = set; 26 } 27 28 public void setMap(Map\u0026lt;String, String\u0026gt; map) { 29 this.map = map; 30 } 31 32 public void setProperties(Properties properties) { 33 this.properties = properties; 34 } 35} Code 4-4(a) shows the target class for Collection Injection.\nCode 4-4(b). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version=\u0026#34;1.0\u0026#34; encoding=\u0026#34;UTF-8\u0026#34;?\u0026gt; 2\u0026lt;beans xmlns=\u0026#34;http://www.springframework.org/schema/beans\u0026#34; 3 xmlns:xsi=\u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 4 xsi:schemaLocation=\u0026#34;http://www.springframework.org/schema/beans 5http://www.springframework.org/schema/beans/spring-beans.xsd\u0026#34;\u0026gt; 6 7 \u0026lt;!-- Define the CollectionInjection bean --\u0026gt; 8 \u0026lt;bean id=\u0026#34;collectionInjection\u0026#34; class=\u0026#34;com.example.di.CollectionInjection\u0026#34;\u0026gt; 9 \u0026lt;!-- Inject an array --\u0026gt; 10 \u0026lt;property name=\u0026#34;array\u0026#34;\u0026gt; 11 \u0026lt;array\u0026gt; 12 \u0026lt;value\u0026gt;1\u0026lt;/value\u0026gt; 13 \u0026lt;value\u0026gt;2\u0026lt;/value\u0026gt; 14 \u0026lt;value\u0026gt;3\u0026lt;/value\u0026gt; 15 \u0026lt;/array\u0026gt; 16 \u0026lt;/property\u0026gt; 17 18 \u0026lt;!-- Inject a list --\u0026gt; 19 \u0026lt;property name=\u0026#34;list\u0026#34;\u0026gt; 20 \u0026lt;list\u0026gt; 21 \u0026lt;value\u0026gt;First element\u0026lt;/value\u0026gt; 22 \u0026lt;value\u0026gt;Second element\u0026lt;/value\u0026gt; 23 \u0026lt;value\u0026gt;Third element\u0026lt;/value\u0026gt; 24 \u0026lt;/list\u0026gt; 25 \u0026lt;/property\u0026gt; 26 27 \u0026lt;!-- Inject a set --\u0026gt; 28 \u0026lt;property name=\u0026#34;set\u0026#34;\u0026gt; 29 \u0026lt;set\u0026gt; 30 \u0026lt;value\u0026gt;Set element 1\u0026lt;/value\u0026gt; 31 \u0026lt;value\u0026gt;Set element 2\u0026lt;/value\u0026gt; 32 \u0026lt;value\u0026gt;Set element 3\u0026lt;/value\u0026gt; 33 \u0026lt;/set\u0026gt; 34 \u0026lt;/property\u0026gt; 35 36 \u0026lt;!-- Inject a map --\u0026gt; 37 \u0026lt;property name=\u0026#34;map\u0026#34;\u0026gt; 38 \u0026lt;map\u0026gt; 39 \u0026lt;entry key=\u0026#34;id\u0026#34; value=\u0026#34;404\u0026#34;/\u0026gt; 40 \u0026lt;entry key=\u0026#34;msg\u0026#34; value=\u0026#34;Page Not Found\u0026#34;/\u0026gt; 41 \u0026lt;/map\u0026gt; 42 \u0026lt;/property\u0026gt; 43 44 \u0026lt;!-- Inject properties --\u0026gt; 45 \u0026lt;property name=\u0026#34;properties\u0026#34;\u0026gt; 46 \u0026lt;props\u0026gt; 47 \u0026lt;prop key=\u0026#34;property1\u0026#34;\u0026gt;Property Value 1\u0026lt;/prop\u0026gt; 48 \u0026lt;prop key=\u0026#34;property2\u0026#34;\u0026gt;Property Value 2\u0026lt;/prop\u0026gt; 49 \u0026lt;prop key=\u0026#34;property3\u0026#34;\u0026gt;Property Value 3\u0026lt;/prop\u0026gt; 50 \u0026lt;/props\u0026gt; 51 \u0026lt;/property\u0026gt; 52 \u0026lt;/bean\u0026gt; 53\u0026lt;/beans\u0026gt; Code 4-4(b) shows how to use XML file to inject array, list, set, map, and properties.\n4.4 Autowire Autowire is a specific feature of Spring DI that simplifies the process of injecting dependencies by automatically wiring beans together (without explicit configuration).\nThere are five autowiring modes:\nTable 4-1. Autowiring Modes\n Mode Description no No autowiring (default mode) byName Autowiring by property name byType Autowiring by property data type, match exactly one constructor Autowiring by constructor, match exactly one autodetect first autowire by constructor, then autowire by byType Note: to wire arrays and other typed-collections, use byType or constructor autowiring mode.\nNow we will use the spell checker textEditor.spellCheck() to demonstrate autowiring modes, and partial codes are shown in Code 4-5(a, b, c):\nCode 4-5(a). \u0026quot;TextEditorTest.java\u0026quot;\n1package com.example.di; 2 3import org.springframework.context.ApplicationContext; 4import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6public class TextEditorTest { 7 public static void main(String[] args) { 8 ApplicationContext context = new ClassPathXmlApplicationContext(\u0026#34;beans.xml\u0026#34;); 9 TextEditor textEditor = (TextEditor) context.getBean(\u0026#34;textEditor\u0026#34;); 10 textEditor.spellCheck(); 11 } 12} Code 4-5(a) is a test class to demonstrate how various autowire modes work.\nCode 4-5(b). \u0026quot;SpellChecker.java\u0026quot;\n1package com.example.di; 2 3public class SpellChecker { 4 public void checkSpelling() { 5 System.out.println(\u0026#34;check Spelling...\u0026#34;); 6 } 7} Code 4-5(b) defines a class named SpellChecker, which is a simple Java class responsible for checking spellings. The SpellChecker class has a single method called checkSpelling() that prints the message \u0026quot;check Spelling...\u0026quot; to the console.\nCode 4-5(c). \u0026quot;TextEditor.java\u0026quot;\n1package com.example.di; 2 3public class TextEditor { 4 // autowire the `spellChecker` from Spring Container 5 private SpellChecker spellChecker; 6 7 public void setSpellChecker( SpellChecker spellChecker ) { 8 this.spellChecker = spellChecker; 9 } 10 11 public SpellChecker getSpellChecker() { 12 return spellChecker; 13 } 14 15 public void spellCheck() { 16 spellChecker.checkSpelling(); 17 } 18} Code 4-5(c) defines a class named TextEditor, which is used to perform spell checking through the use of the SpellChecker defined in Code 4-5(b).\nWith Code 4-5(d, e, or f), the expected output for Code 4-5(a, b, c) should be:\n1check Spelling... 4.4.1 Autowire byName In XML configuration file, Spring container looks at the beans on which autowire attribute is set to byName, Spring container will then look for other beans with names that match the properties of the bean (the bean set to byName-autowiring). If matches are found, Spring will automatically inject those matching beans into the properties of the specified bean; otherwise, the bean's properties will remain unwired.\nCode 4-5(a, b, c) and Code 4-5(d) demonstrate how autowire byName works:\nCode 4-5(d) \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;!-- Definition for spellChecker bean --\u0026gt; 9 \u0026lt;bean id = \u0026#34;spellChecker\u0026#34; class = \u0026#34;com.example.di.SpellChecker\u0026#34; /\u0026gt; 10 11 \u0026lt;!-- Definition for textEditor bean --\u0026gt; 12 \u0026lt;bean id = \u0026#34;textEditor\u0026#34; 13 class = \u0026#34;com.example.di.TextEditor\u0026#34; 14 autowire = \u0026#34;byName\u0026#34; /\u0026gt; 15\u0026lt;/beans\u0026gt; In Code 4-5(d), Spring will look for a bean with the name spellChecker in the Spring Container and inject it into spellChecker property of textEditor bean, due to autowire = \u0026quot;byName\u0026quot; on textEditor. And to enable the byName autowiring, TextEditor must have a class member whose type is SpellChecker.\n4.4.2 Autowire byType In the XML configuration file, when the autowire attribute is set to byType for a particular bean, the Spring container will attempt to find other beans in its context whose types match the property types of the bean being configured.\nCode 4-5(a, b, c) and Code 4-5(e) demonstrate how autowire byType works:\nCode 4-5(e). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;!-- Definition for spellChecker bean --\u0026gt; 9 \u0026lt;bean id = \u0026#34;spellChecker\u0026#34; class = \u0026#34;com.example.di.SpellChecker\u0026#34; /\u0026gt; 10 11 \u0026lt;!-- Definition for textEditor bean --\u0026gt; 12 \u0026lt;bean id = \u0026#34;textEditor\u0026#34; 13 class = \u0026#34;com.example.di.TextEditor\u0026#34; 14 autowire = \u0026#34;byType\u0026#34; /\u0026gt; 15\u0026lt;/beans\u0026gt; In Code 4-5(e), Spring will automatically inject the spellChecker into spellChecker property of textEditor bean, because the SpellChecker class is defined as a Spring bean with the id spellChecker, and it matches the type of the spellChecker property in the TextEditor class.\n4.4.3 Autowire constructor In the XML configuration file, Spring container looks at the beans on which autowire attribute is set constructor. It then tries to match and wire its constructor's argument with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans; otherwise, bean(s) will remain unwired.\nCode 4-5(f). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;!-- Definition for spellChecker bean --\u0026gt; 9 \u0026lt;bean id = \u0026#34;spellChecker\u0026#34; class = \u0026#34;com.example.di.SpellChecker\u0026#34; /\u0026gt; 10 11 \u0026lt;!-- Definition for textEditor bean --\u0026gt; 12 \u0026lt;bean id = \u0026#34;textEditor\u0026#34; 13 class = \u0026#34;com.example.di.TextEditor\u0026#34; 14 autowire = \u0026#34;constructor\u0026#34; /\u0026gt; 15\u0026lt;/beans\u0026gt; 5. ANNOTATIONS Annotations are a form of metadata, that applies to the Java classes, methods, or fields, to provide additional information and instructions to the Spring container. Annotations offer a straightforward alternative to XML files for efficient configuration and management of components and their dependencies.\n5.1 Configuration Annotations Below are some configuration annotations used to configure the Spring container, manage properties, and activate specific profiles.\n5.1.1 @Bean @Bean indicates that the return value of the annotated method should be registered as a bean in the Spring application context.\nCode 5-1. Snippet of \u0026quot;Address.java\u0026quot;\n1 @Bean 2 public Address getAddress(){ 3 return new Address(); 4 } In Code 5-1, getAddress() is annotated with @Bean, meaning that Spring will register the Address object returned by that method as a bean.\n5.1.2 @Configuration @Configuration annotation is used to declare a class as a configuration class in Spring.\nCode 5-2. Snippet of \u0026quot;DataConfig.java\u0026quot;\n1@Configuration 2public class DataConfig{ 3 @Bean 4 public DataSource source(){ 5 DataSource source = new OracleDataSource(); 6 source.setURL(); 7 source.setUser(); 8 return source; 9 } 10} In Code 5-2, @Configuration annotation declares the class DataConfig as a configuration class in Spring.\n5.1.3 @ComponentScan @ComponentScan annotation is used to enable component scanning in Spring.\nCode 5-3(a). \u0026quot;AppConfig.java\u0026quot;\n1package com.example.annotation; 2 3import org.springframework.context.annotation.ComponentScan; 4import org.springframework.context.annotation.Configuration; 5 6@Configuration 7@ComponentScan(basePackages = \u0026#34;com.example.annotation\u0026#34;) 8public class AppConfig { 9 10} In Code 5-3(a): AppConfig uses @ComponentScan to specify the base package for component scanning. When Spring performs component scanning, it looks for classes annotated with stereotypes like @Component, within the specified package and its sub-packages. Spring will then automatically create Spring beans for these classes and add them to the application context.\nCode 5-3(b). \u0026quot;HelloService.java\u0026quot;\n1package com.example.annotation; 2 3import org.springframework.stereotype.Component; 4 5@Component 6public class HelloService { 7 public void sayHello() { 8 System.out.println(\u0026#34;Hello World\u0026#34;); 9 } 10} In Code 5-3(b): HelloService is annotated with @Component, indicating that it is a Spring bean that will be managed by the Spring container.\nCode 5-3(c). \u0026quot;AppTest.java\u0026quot;\n1package com.example.annotation; 2 3import org.springframework.context.annotation.AnnotationConfigApplicationContext; 4 5public class AppTest { 6 public static void main(String[] args) { 7 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 8 HelloService helloService = context.getBean(HelloService.class); 9 helloService.sayHello(); 10 context.close(); // !!! it is important to close the Annotation Config Application Context 11 } 12} Code 5-3(c) creates an AnnotationConfigApplicationContext using AppConfig.class as the configuration class, retrieves the HelloService bean from the context, and then calls the sayHello() method.\nThe expected output for Code 5-3(a, b, c) is:\n1Hello World 5.1.4 @PropertySource @PropertySource annotation is used to specify the location of properties files containing configuration settings for the Spring application.\nCode 5-4(a). \u0026quot;AppConfig.java\u0026quot;\n1package com.example.annotation.propertysource; 2 3import org.springframework.context.annotation.Configuration; 4import org.springframework.context.annotation.PropertySource; 5 6@Configuration 7@ComponentScan(basePackages = \u0026#34;com.example.annotation.propertysource\u0026#34;) 8@PropertySource(\u0026#34;classpath:application.yml\u0026#34;) 9public class AppConfig { 10 11} Code 5-4(a) is a Java configuration class, and it specifies that it will define Spring beans and loads properties from the \u0026quot;application.yml\u0026quot; file.\nCode 5-4(b). \u0026quot;application.yml\u0026quot;\n1greeting:2message:\u0026#34;Hello, World!\u0026#34;Code 5-4(b) is a YAML file that sets the property \u0026quot;greeting.message\u0026quot; with the value \u0026quot;Hello, World!\u0026quot; for the Spring application.\nCode 5-4(c). \u0026quot;GreetingService.java\u0026quot;\n1package com.example.annotation.propertysource; 2 3import org.springframework.beans.factory.annotation.Value; 4import org.springframework.stereotype.Component; 5 6@Component 7public class GreetingService { 8 @Value(\u0026#34;${greeting.message}\u0026#34;) 9 private String message; 10 11 public void sayGreeting() { 12 System.out.println(message); 13 } 14} Code 5-4(c) is a Spring component class, and it injects the value of the property \u0026quot;greeting.message\u0026quot; into the private field greetingMessage and provides a method to print the greeting message.\nCode 5-4(d). \u0026quot;AppTest.java\u0026quot;\n1import org.springframework.context.annotation.AnnotationConfigApplicationContext; 2 3public class AppTest { 4 public static void main(String[] args) { 5 // Create the application context using AppConfig 6 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 7 8 // Get the GreetingService bean from the context 9 GreetingService greetingService = context.getBean(GreetingService.class); 10 11 // Call the sayGreeting() method to print \u0026#34;Hello, World!\u0026#34; on the console 12 greetingService.sayGreeting(); 13 14 // Close the context 15 context.close(); 16 } 17} The expected output for Code 5-4(a, b, c, d) should be:\n1Hello, World! 5.1.5 @Profile @Profile annotation is used to define specific configurations for different application environments or scenarios.\nCode 5-5(a). \u0026quot;DatabaseConfig.java\u0026quot;\n1package com.example.annotation.profile; 2 3import org.springframework.context.annotation.Bean; 4import org.springframework.context.annotation.Configuration; 5import org.springframework.context.annotation.Profile; 6 7@Configuration 8public class DatabaseConfig { 9 10 @Bean 11 @Profile(\u0026#34;development\u0026#34;) 12 public DataSource developmentDataSource() { 13 // Create and configure the H2 data source for development 14 return new H2DataSource(); 15 } 16 17 @Bean 18 @Profile(\u0026#34;production\u0026#34;) 19 public DataSource productionDataSource() { 20 // Create and configure the MySQL data source for production 21 return new MySQLDataSource(); 22 } 23} Code 5-5(b). \u0026quot;DataSource.java\u0026quot;\n1package com.example.annotation.profile; 2 3public interface DataSource { 4 // Define common data source methods here 5} 6 7public class H2DataSource implements DataSource { 8 // H2 data source implementation 9} 10 11public class MySQLDataSource implements DataSource { 12 // MySQL data source implementation 13} Code 5-5(c). \u0026quot;application.yml\u0026quot;\n1spring:2profiles:3active:developmentThis will activate the @Profile(\u0026quot;development\u0026quot;) part of DataSource bean.\n5.1.6 @Import @Import annotation is used to import one or more configuration classes into the current configuration.\nCode 5-6(a). \u0026quot;AppConfig.java\u0026quot;\n1import org.springframework.context.annotation.Bean; 2import org.springframework.context.annotation.Configuration; 3 4@Configuration 5public class AppConfig { 6 7 @Bean 8 public MyBean myBean() { 9 return new MyBean(); 10 } 11} Code 5-6(b). \u0026quot;AnotherAppConfig.java\u0026quot;\n1import org.springframework.context.annotation.Configuration; 2import org.springframework.context.annotation.Import; 3 4@Configuration 5@Import(AppConfig.class) 6public class AnotherConfig { 7 // Additional configuration or beans can be defined here 8} 9 Code 5-6(b) makes all the beans defined in AppConfig (in this case, just MyBean) available in the current application context, when AnotherConfig is used.\n5.1.7 @ImportResource @ImportResource annotation is used to import XML-based Spring configurations into the current Java-based configuration class.\nCode 5-7(a). \u0026quot;AppConfig.java\u0026quot;\n1package com.example.annotation.config; 2 3import org.springframework.context.annotation.Configuration; 4import org.springframework.context.annotation.ImportResource; 5 6@Configuration 7@ImportResource(\u0026#34;classpath:config.xml\u0026#34;) // Load the XML configuration file 8public class AppConfig { 9 // Java-based configuration can also be defined here if needed 10} Code 5-7(a) indicates that it contains Spring bean definitions. It also uses @ImportResource to load the XML configuration file \u0026quot;config.xml.\u0026quot;\nCode 5-7(b). \u0026quot;config.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2 3\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 4 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\u0026#34;\u0026gt; 7 8 \u0026lt;!-- Define a bean in the XML configuration --\u0026gt; 9 \u0026lt;bean id=\u0026#34;messageService\u0026#34; class=\u0026#34;com.example.MessageService\u0026#34;\u0026gt; 10 \u0026lt;property name=\u0026#34;message\u0026#34; value=\u0026#34;Hello, Spring!\u0026#34;/\u0026gt; 11 \u0026lt;/bean\u0026gt; 12\u0026lt;/beans\u0026gt; Code 5-7(c). \u0026quot;MessageService.java\u0026quot;\n1package com.example.annotation.config; 2 3public class MessageService { 4 private String message; 5 6 public String getMessage() { 7 return message; 8 } 9 10 public void setMessage(String message) { 11 this.message = message; 12 } 13} Code 5-7(d). \u0026quot;AppTest.java\u0026quot;\n1package com.example.annotation.config; 2 3import org.springframework.context.annotation.AnnotationConfigApplicationContext; 4 5public class Main { 6 public static void main(String[] args) { 7 // Load the Java configuration class 8 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 9 10 // Get the bean from the Spring context 11 MessageService messageService = context.getBean(\u0026#34;messageService\u0026#34;, MessageService.class); 12 13 // Use the bean 14 System.out.println(messageService.getMessage()); 15 16 // Close the context 17 context.close(); 18 } 19} The expected output of running Code 5-7(a, b, c, d) should be:\n1Hello, Spring! 5.2 Bean Annotations Below are some bean annotations that are commonly used in Spring applications:\n5.2.1 @Component, @Controller, @Repository, @Service These are used to automatically detect and register beans with the Spring container during component scanning.\n @Component indicates that the class is a general-purpose Spring component @Controller marks the class as a Spring MVC controller @Repository indicates that the class is a data repository (database operations) @Servicemarks the class as a service bean dealing with business logic For the reason of simplicity, I will reuse the Code 5-3(b) as the demo.\n5.2.2 @Autowired @Autowired annotation is used to automatically inject dependent beans into the target bean.\n@Autowired can be applied on fields, setter methods, and constructors.\nCode 5-8. \u0026quot;AutowiredField.java\u0026quot;\n1package com.example.autowired.field; 2 3import org.springframework.beans.factory.annotation.Autowired; 4 5public class Customer { 6 @Autowired 7 private Person person; 8 9 // ... 10} Code 5-8 shows how to use the @Autowired annotation to automatically inject a bean into the person field of Customer class.\nCode 5-9. \u0026quot;AutowiredSetter.java\u0026quot;\n1package com.example.autowired.setter; 2 3import org.springframework.beans.factory.annotation.Autowired; 4 5public class Customer { 6 private Person person; 7 8 @Autowired 9 public void setPerson(Person person) { 10 this.person = person; 11 } 12 13 // ... 14} Code 5-9 shows how to use the @Autowired annotation to automatically inject a bean into the setter setPerson() of the Customer class. Spring tries to perform the byType autowiring on the method.\nCode 5-10. \u0026quot;AutowiredConstructor.java\u0026quot;\n1package com.example.autowired.constructor; 2 3import org.springframework.beans.factory.annotation.Autowired; 4 5public class Customer { 6 private Person person; 7 8 @Autowired 9 public Customer(Person person) { 10 this.person = person; 11 } 12 13 // ... 14} Code 5-10 shows how to use the @Autowired annotation to automatically inject a bean into the constructor of the Customer class. Note: only one constructor of any bean class can carry the @Autowired annotation.\n5.2.3 @Qualifier The @Qualifier annotation is used in conjunction with @Autowired to resolve ambiguity when multiple beans of the same type are available for injection.\nCode 5-11(a). \u0026quot;MessageService.java\u0026quot;\n1package com.example.annotation.qualifier; 2 3public interface MessageService { 4 public void sendMessage(); 5} 6 7@Component 8public class MailService implements MessageService { 9 @Override 10 public void sendMessage() { 11 System.out.println(\u0026#34;Mail sent.\u0026#34;); 12 } 13} 14 15@Component 16public class SmsService implements MessageService { 17 @Override 18 public void sendMessage() { 19 System.out.println(\u0026#34;SMS sent.\u0026#34;); 20 } 21} Code 5-11(a) defines an interface MessageService, which declares a single method sendMessage(). The interface is then implemented by two classes, MailService and SmsService. These classes provide their own implementations of the sendMessage() method.\nCode 5-11(b). \u0026quot;App.java\u0026quot;\n1package com.example.annotation.qualifier; 2 3import org.springframework.beans.factory.annotation.Autowired; 4import org.springframework.beans.factory.annotation.Qualifier; 5import org.springframework.stereotype.Component; 6 7@Component 8public class App { 9 10 @Autowired 11 @Qualifier(\u0026#34;mailService\u0026#34;) 12 private MessageService messageService; 13 14 public void action() { 15 messageService.sendMessage(); 16 } 17} Code 5-11(b) injects mailService into messageService by @Qualifier annotation. Note: the MailService class is annotated with @Component, which makes it a Spring bean. So the default bean name for MailService class would be mailService (with the first letter converted to lowercase).\n5.2.4 @Value @Value annotation is used to inject values from properties files, environment variables, or other sources directly into bean fields or constructor parameters.\nCode 5-12. \u0026quot;HelloService.java\u0026quot;\n1import org.springframework.beans.factory.annotation.Value; 2import org.springframework.stereotype.Component; 3 4@Component 5public class HelloService { 6 @Value(\u0026#34;Hello Spring Framework\u0026#34;) 7 private String message; 8 9 public void sayHello() { 10 System.out.println(message); 11 } 12} Code 5-12 defines a Spring component class named HelloService with a field message that is initialized with the value \u0026quot;Hello Spring Framework\u0026quot; using the @Value annotation, and a method sayHello() to print the message to the console when called.\n5.2.5 @Scope @Scope annotation is used to specify the the scope of a @Component class or a @Bean definition (just like scope field in \u0026lt;bean\u0026gt; tag), defining the lifecycle and visibility of the bean instance.\nThe default scope for a bean is Singleton, and we can define the scope of a bean as a Prototype using the scope=\u0026quot;prototype\u0026quot; attribute of the \u0026lt;bean\u0026gt; tag in the XML file or using @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) annotation, shown in Code 5-13.\nCode 5-13. Snippet of \u0026quot;AppConfig.java\u0026quot;\n1@Configuration 2public class AppConfig { 3 @Bean 4 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) 5 public MessageService messageService() { 6 return new EmailMessageService(); 7 } 8} 5.2.6 @PostConstructand @PreDestroy @PostConstruct annotation is used to indicate a method (init-method field in \u0026lt;bean\u0026gt; tag) that should be executed after the bean has been initialized by the Spring container.\n@PreDestroy annotation is used to indicate a method (destroy-method field in \u0026lt;bean\u0026gt; tag) that should be executed just before the bean is destroyed by the Spring container.\nCode 5-14(a). \u0026quot;\u0026quot;\n1package com.example.ctordtor; 2 3import javax.annotation.PostConstruct; 4import javax.annotation.PreDestroy; 5 6import org.springframework.stereotype.Component; 7 8@Component 9public class ExampleBean { 10 11 @PostConstruct 12 public void init() { 13 System.out.println(\u0026#34;Initializing bean...\u0026#34;); 14 } 15 16 @PreDestroy 17 public void cleanup() { 18 System.out.println(\u0026#34;Destroying bean...\u0026#34;); 19 } 20} Code 5-14(b). \u0026quot;AppConfig.java\u0026quot;\n1package com.example.ctordtor; 2 3import org.springframework.context.annotation.ComponentScan; 4import org.springframework.context.annotation.Configuration; 5 6@Configuration 7@ComponentScan(basePackages = \u0026#34;com.example.springdemo\u0026#34;) 8public class AppConfig { 9 10} 5.2.7 @Lazy The @Lazy annotation is used to delay the initialization of a bean until the first time it is requested.\nCode 5-15. \u0026quot;AppConfig.java\u0026quot;\n1package com.example.annotation.lazy; 2 3import org.springframework.context.annotation.Bean; 4import org.springframework.context.annotation.Configuration; 5import org.springframework.context.annotation.Lazy; 6 7@Configuration 8public class AppConfig { 9 10 @Lazy(value = true) 11 @Bean 12 public FirstBean firstBeanLazy() { 13 return new FirstBean(); 14 } 15 16 @Lazy 17 @Bean 18 public SecondBean secondBeanLazy() { 19 return new SecondBean(); 20 } 21 22 @Lazy(value = false) 23 @Bean 24 public ThirdBean thirdBeanNotLazy() { 25 return new ThirdBean(); 26 } 27 28 @Bean 29 public FourthBean fourthBeanNotLazy() { 30 return new FourthBean(); 31 } 32} Code 5-15 defines 4 beans: firstBeanLazy and secondBeanLazy will be lazily initialized, while thirdBeanNotLazy and fourthBeanNotLazy will be eagerly initialized during the application startup.\n5.2.8 @Primary @Primary annotation is used to indicate a preferred bean when multiple beans of the same type are available for injection with @Autowired.\nCode 5-16(a). Snippet of \u0026quot;AppConfig.java\u0026quot;\n1@Configuration 2public class AppConfig { 3 4 @Bean 5 public MessageService getEmailService() { 6 return new MessageService(\u0026#34;Email\u0026#34;); 7 } 8 9 @Bean 10 @Primary 11 public MessageService getSmsService() { 12 return new MessageService(\u0026#34;SMS\u0026#34;); 13 } 14} Code 5-16(a) defines two beans (MessageService instances) with different type names (\u0026quot;Email\u0026quot; and \u0026quot;SMS\u0026quot;) and marks the return value of getSmsService() as the primary bean using the @Primary annotation.\nCode 5-16(b). Snippet of \u0026quot;MessageService.java\u0026quot;\n1public class MessageService { 2 private String type; 3 4 public MessageService(String type) { 5 this.type = type; 6 } 7 8 // ... 9} Code 5-16(b) declares the MessageService class with a constructor to set the type of MessageService when creating an instance.\n6. AOP Aspect-Oriented Programming (AOP) is a framework in Spring that allows breaking down program logic into separate concerns, which are conceptually independent from core business logic of the application, providing a way to decouple cross-cutting concerns from the objects they affect.\n6.1 AOP Concepts The concepts shown in the table below are general terms that are related to AOP in a broader sense beyond Spring Framework.\nTable 6-1. General Terms of AOP\n Terms Description Aspect a module which has a set of APIs providing cross-cutting requirements Target object The object being advised by one or more aspects Join point a point in your application where you can plugin the AOP aspect Pointcut a set of one or more join points where an advice should be executed Advice the actual action to be taken either before or after the method execution Introduction allows you to add new methods or attributes to the existing classes. Weaving the process of linking aspects with other application types or objects to create an advised object Spring AOP is a technique that modularizes cross-cutting concerns using aspects, which consist of advice and pointcuts. Aspects define specific behaviors, and pointcuts specify where these behaviors should be applied (e.g., method invocations).\nDuring runtime weaving, the advice is applied to the target objects at the designated join points, effectively incorporating the desired functionalities into the application and improving code modularity.\nSpring aspects can work with five kinds of advice mentioned:\nTable 6-2. Types of Advice\n Types of Advice Description before run advice before the execution of the method after run advice after the execution of the method after-returning run advice after the a method only if its execution is completed successfully after-throwing run advice after the a method only if its execution throws exception around run advice before and after the advised method is invoked 6.2 XML Schema based AOP Aspects can be implemented using the regular classes along with XML Schema based configuration. The basic structure for XML to config AOP looks like Code 6-0:\nCode 6-0. Skeleton of AOP config in \u0026quot;beans.xml\u0026quot;\n1\u0026lt;aop:config\u0026gt; 2 \u0026lt;aop:aspect id = \u0026#34;{AOP_ID}\u0026#34; ref = \u0026#34;{CONFIG_CLASS_lowerCammelNotation}\u0026#34;\u0026gt; 3 \u0026lt;aop:pointcut id = \u0026#34;{POINTCUT_ID}\u0026#34; expression = \u0026#34;{POINTCUT_EXPRESSION}\u0026#34;/\u0026gt; 4 \u0026lt;aop:{ADVICE_NAME} pointcut-ref = \u0026#34;{POINTCUT_ID}\u0026#34; method = \u0026#34;{CONFIG_CLASS_CERTAIN_METHOD}\u0026#34;/\u0026gt; 5 \u0026lt;aop:after-returning pointcut-ref = \u0026#34;{POINTCUT_ID}\u0026#34; returning = \u0026#34;{RETURN_VAR_NAME}\u0026#34; method = \u0026#34;{CONFIG_CLASS_CERTAIN_METHOD}\u0026#34;/\u0026gt; 6 \u0026lt;aop:after-throwing pointcut-ref = \u0026#34;{POINTCUT_ID}\u0026#34; throwing = \u0026#34;{EXCEPTION_NAME}\u0026#34; method = \u0026#34;{CONFIG_CLASS_CERTAIN_METHOD}\u0026#34;/\u0026gt; 7 \u0026lt;/aop:aspect\u0026gt; 8\u0026lt;/aop:config\u0026gt; Code 6-0 shows how to config AOP:\n An aspect is declared using the \u0026lt;aop:aspect\u0026gt; element, and the backing bean is referenced using the ref attribute. A pointcut is declared using the \u0026lt;aop:pointcut\u0026gt; element to determine the join points (i.e., methods) of interest to be executed with different advices. Advices can be declared inside \u0026lt;aop:aspect\u0026gt; tag using the element \u0026lt;aop:{ADVICE_NAME}\u0026gt;, such as \u0026lt;aop:before\u0026gt;, \u0026lt;aop:after\u0026gt;, \u0026lt;aop:after-returning\u0026gt;, \u0026lt;aop:after-throwing\u0026gt; and \u0026lt;aop:around\u0026gt;. (Please refer to Table 6-1). PointCut Designator (PCD) is a keyword telling Spring AOP what to match.\n execution(primary Spring PCD): matches method execution join points within: limits matching to join points of certain types this: limits matching to join points where the bean reference is an instance of the given type (when Spring AOP creates a CGLIB-based proxy). target: limits matching to join points where the target object is an instance of the given type (when a JDK-based proxy is created). args: matches particular method arguments Pointcut Expression looks like expression = \u0026quot;execution(* com.example.aop.*.*(..))\u0026quot;, in expression field of \u0026lt;aop:pointcut\u0026gt; tag:\n the execution is a Spring PCD the first Asterisk Sign (*) in execution(* is a wildcard character that matches any return type of the intercepted method, e.g., void, Integer, String, etc. the second asterisk (*) in com.example.aop.* is a wildcard character that matches any class in the com.example.aop package. the dot and asterisk (.*) in com.example.aop.*.* is a wildcard character that matches any method with any name in the specified class. (..)is another wildcard that matches any number of arguments in the method. (..) means the method can take zero or more arguments. Code 6-1(a). \u0026quot;Logging.java\u0026quot;\n1package com.example.aop; 2 3public class Logging { 4 5 public void beforeAdvice(){ 6 System.out.println(\u0026#34;`beforeAdvice()` invoked.\u0026#34;); 7 } 8 9 public void afterAdvice(){ 10 System.out.println(\u0026#34;`afterAdvice()` invoked.\u0026#34;); 11 } 12 13 public void afterReturningAdvice(Object retVal) { 14 System.out.println(\u0026#34;[Success] `afterReturningAdvice()` reads return value: \u0026#34; + retVal.toString() ); 15 System.out.println(\u0026#34;------\u0026#34;); 16 } 17 18 public void afterThrowingAdvice(Exception exception){ 19 System.out.println(\u0026#34;[FAILURE] `afterThrowingAdvice()` detects Exception: \u0026#34; + exception.toString()); 20 System.out.println(\u0026#34;------\u0026#34;); 21 } 22} Code 6-1(a) represents an aspect in an AOP context, and it contains various advice methods that will be executed at specific points during the execution of the target methods in the application:\n beforeAdvice() method will be executed before the target method is invoked. afterAdvice() method will be executed after the target method has been invoked, regardless of whether it completed successfully or threw an exception. afterReturningAdvice(Object retVal) method will be executed after the target method has successfully completed and returned a value. (The retVal parameter contains the value returned by the target method.) afterThrowingAdvice(Exception exception) method will be executed if the target method throws an exception. (The exception parameter contains the exception thrown by the target method.) Code 6-1(b). \u0026quot;Student.java\u0026quot;\n1package com.example.aop; 2 3public class Student { 4 private Integer age; 5 private String name; 6 7 public void setAge(Integer age) { 8 this.age = age; 9 } 10 public Integer getAge() { 11 System.out.println(\u0026#34;Class method `getAge()` gets `age` = \u0026#34; + age ); 12 return age; 13 } 14 public void setName(String name) { 15 this.name = name; 16 } 17 public String getName() { 18 System.out.println(\u0026#34;Class method `getName()` gets `name` = \u0026#34; + name ); 19 return name; 20 } 21 public void throwsException(){ 22 System.out.println(\u0026#34;Class method `throwsException()` will throw \u0026#39;IllegalArgumentException\u0026#39;\u0026#34;); 23 if (true) 24 throw new IllegalArgumentException(); // For Test 25 } 26} In Code 6-1(b), Student class has getters/setters for age and name properties, and also has the throwsException() method, which will throw an IllegalArgumentException to demonstrate how AOP and exception handling work together.\nCode 6-1(c). \u0026quot;AopDemoTest.java\u0026quot;\n1package com.example.aop; 2 3import org.springframework.context.ApplicationContext; 4import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6public class AopDemoTest { 7 public static void main(String[] args) { 8 ApplicationContext context = new ClassPathXmlApplicationContext(\u0026#34;beans.xml\u0026#34;); 9 10 Student student = (Student) context.getBean(\u0026#34;student\u0026#34;); 11 student.getName(); 12 student.getAge(); 13 student.throwsException(); 14 } 15} Code 6-1(c) contains the main method that demonstrates the usage of AOP.\nCode 6-1(d). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 3 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 4 xmlns:aop = \u0026#34;http://www.springframework.org/schema/aop\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 7http://www.springframework.org/schema/aop 8http://www.springframework.org/schema/aop/spring-aop-3.0.xsd \u0026#34;\u0026gt; 9 10 \u0026lt;!-- Bean definition for student --\u0026gt; 11 \u0026lt;bean id = \u0026#34;student\u0026#34; class = \u0026#34;com.example.aop.Student\u0026#34;\u0026gt; 12 \u0026lt;property name = \u0026#34;name\u0026#34; value = \u0026#34;Tom\u0026#34; /\u0026gt; 13 \u0026lt;property name = \u0026#34;age\u0026#34; value = \u0026#34;83\u0026#34;/\u0026gt; 14 \u0026lt;/bean\u0026gt; 15 16 \u0026lt;!-- Bean definition for logging aspect --\u0026gt; 17 \u0026lt;bean id = \u0026#34;logging\u0026#34; class = \u0026#34;com.example.aop.Logging\u0026#34;/\u0026gt; 18 19 \u0026lt;!-- AOP Configurations --\u0026gt; 20 \u0026lt;aop:config\u0026gt; 21 \u0026lt;!-- 22`\u0026lt;aop:aspect id = \u0026#34;log\u0026#34;\u0026gt;`: defines an aspect named \u0026#34;log\u0026#34; 23`ref = \u0026#34;logging\u0026#34;`: refer to the bean named \u0026#34;logging\u0026#34;, 24representing the \u0026#34;Logging.java\u0026#34; aspect 25--\u0026gt; 26 \u0026lt;aop:aspect id = \u0026#34;log\u0026#34; ref = \u0026#34;logging\u0026#34;\u0026gt; 27 \u0026lt;!-- 28A pointcut named \u0026#34;selectAll\u0026#34; is defined using an `expression` 29to target *all methods* 30within the package \u0026#34;com.example.aop\u0026#34; and its sub-packages. 31--\u0026gt; 32 \u0026lt;aop:pointcut id = \u0026#34;selectAll\u0026#34; 33 expression = \u0026#34;execution(* com.example.aop.*.*(..))\u0026#34;/\u0026gt; 34 35 \u0026lt;!-- 36Associates the \u0026#34;beforeAdvice()\u0026#34; method 37with the \u0026#34;selectAll\u0026#34; pointcut 38to be executed **before** the target methods 39--\u0026gt; 40 \u0026lt;aop:before pointcut-ref = \u0026#34;selectAll\u0026#34; method = \u0026#34;beforeAdvice\u0026#34;/\u0026gt; 41 42 \u0026lt;!-- 43Associates the \u0026#34;afterAdvice()\u0026#34; method 44with the \u0026#34;selectAll\u0026#34; pointcut 45to be executed **after** the target methods. 46--\u0026gt; 47 \u0026lt;aop:after pointcut-ref = \u0026#34;selectAll\u0026#34; method = \u0026#34;afterAdvice\u0026#34;/\u0026gt; 48 49 \u0026lt;!-- 50Associates the \u0026#34;afterReturningAdvice()\u0026#34; method 51with the \u0026#34;selectAll\u0026#34; pointcut 52to be executed after the **successful return** of the target methods. 5354The returning value will be the parameter for `afterReturningAdvice()`. 55--\u0026gt; 56 \u0026lt;aop:after-returning pointcut-ref = \u0026#34;selectAll\u0026#34; 57 returning = \u0026#34;retVal\u0026#34; method = \u0026#34;afterReturningAdvice\u0026#34;/\u0026gt; 58 59 \u0026lt;!-- 60Associates the \u0026#34;afterThrowingAdvice()\u0026#34; method 61with the \u0026#34;selectAll\u0026#34; pointcut 62to be executed if the target methods throw an exception. 63The Exception object will be the parameter for `afterThrowingAdvice()`. 64--\u0026gt; 65 \u0026lt;aop:after-throwing pointcut-ref = \u0026#34;selectAll\u0026#34; 66 throwing = \u0026#34;exception\u0026#34; method = \u0026#34;afterThrowingAdvice\u0026#34;/\u0026gt; 67 68 \u0026lt;/aop:aspect\u0026gt; 69 \u0026lt;/aop:config\u0026gt; 70 71\u0026lt;/beans\u0026gt; Code 6-1(d) shows how to config Spring AOP.\nThe expected output for Code 6-1(a, b, c, d) is:\n1`beforeAdvice()` invoked. 2Class method `getName()` gets `name` = Tom 3`afterAdvice()` invoked. 4[Success] `afterReturningAdvice()` reads return value: Tom 5------ 6`beforeAdvice()` invoked. 7Class method `getAge()` gets `age` = 83 8`afterAdvice()` invoked. 9[Success] `afterReturningAdvice()` reads return value: 83 10------ 11`beforeAdvice()` invoked. 12Class method `throwsException()` will throw \u0026#39;IllegalArgumentException\u0026#39; 13`afterAdvice()` invoked. 14[FAILURE] `afterThrowingAdvice()` detects Exception: java.lang.IllegalArgumentException 15------ 16Exception in thread \u0026#34;main\u0026#34; java.lang.IllegalArgumentException 17\tat com.example.aop.Student.throwsException(Student.java:23) 18\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 19\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) 20 (Omit the rest 22-line-long Exception message...) Code 6-1(e). \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 3 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 4 xmlns:aop = \u0026#34;http://www.springframework.org/schema/aop\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 7http://www.springframework.org/schema/aop 8http://www.springframework.org/schema/aop/spring-aop-3.0.xsd \u0026#34;\u0026gt; 9 10 \u0026lt;!-- Definition for student bean --\u0026gt; 11 \u0026lt;bean id = \u0026#34;student\u0026#34; class = \u0026#34;com.example.aop.Student\u0026#34;\u0026gt; 12 \u0026lt;property name = \u0026#34;name\u0026#34; value = \u0026#34;Jerry\u0026#34; /\u0026gt; 13 \u0026lt;property name = \u0026#34;age\u0026#34; value = \u0026#34;83\u0026#34;/\u0026gt; 14 \u0026lt;/bean\u0026gt; 15 16 \u0026lt;!-- Definition for logging aspect --\u0026gt; 17 \u0026lt;bean id = \u0026#34;logging\u0026#34; class = \u0026#34;com.example.aop.Logging\u0026#34;/\u0026gt; 18 19 \u0026lt;!-- AOP Configurations --\u0026gt; 20 \u0026lt;aop:config\u0026gt; 21 \u0026lt;aop:aspect id = \u0026#34;log\u0026#34; ref = \u0026#34;logging\u0026#34;\u0026gt; 22 23 \u0026lt;!-- 24A pointcut named \u0026#34;selectGetName\u0026#34; using an expression 25to target the `getName()` method of the `Student` class. 2627Note: `(..)` is a wildcard that 28represents zero or more arguments of any type. 29--\u0026gt; 30 \u0026lt;aop:pointcut id = \u0026#34;selectGetName\u0026#34; 31 expression = \u0026#34;execution(* com.example.aop.Student.getName(..))\u0026#34;/\u0026gt; 32 33 \u0026lt;aop:before pointcut-ref = \u0026#34;selectGetName\u0026#34; method = \u0026#34;beforeAdvice\u0026#34;/\u0026gt; 34 \u0026lt;aop:after pointcut-ref = \u0026#34;selectGetName\u0026#34; method = \u0026#34;afterAdvice\u0026#34;/\u0026gt; 35 \u0026lt;aop:after-returning pointcut-ref = \u0026#34;selectGetName\u0026#34; 36 returning = \u0026#34;retVal\u0026#34; method = \u0026#34;afterReturningAdvice\u0026#34;/\u0026gt; 37 \u0026lt;aop:after-throwing pointcut-ref = \u0026#34;selectGetName\u0026#34; 38 throwing = \u0026#34;exception\u0026#34; method = \u0026#34;afterThrowingAdvice\u0026#34;/\u0026gt; 39 40 \u0026lt;/aop:aspect\u0026gt; 41 \u0026lt;/aop:config\u0026gt; 42 43\u0026lt;/beans\u0026gt; Code 6-1(e) looks like Code 6-1(d), except for the element \u0026lt;aop:pointcut id = \u0026quot;selectGetName\u0026quot; expression = \u0026quot;execution(* com.example.aop.Student.getName(..))\u0026quot;/\u0026gt;, which targets only on the method Student.getName() rather than all methods in the Student class.\nThe expected output for Code 6-1(a, b, c, e) is:\n1`beforeAdvice()` invoked. 2Class method `getName()` gets `name` = Tom 3[Success] `afterReturningAdvice()` reads return value: Tom 4------ 5`afterAdvice()` invoked. 6Class method `getAge()` gets `age` = 83 7Class method `throwsException()` will throw \u0026#39;IllegalArgumentException\u0026#39; 8Exception in thread \u0026#34;main\u0026#34; java.lang.IllegalArgumentException 9\tat com.example.aop.Student.throwsException(Student.java:23) 10\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 11\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) 12\t(Omit the rest 10-line-long Exception message...) 6.3 AspectJ based AOP AspectJ refers declaring aspects as regular Java classes with Java 5 annotations.\nFirst, the \u0026quot;beans.xml\u0026quot; need to be modified with \u0026lt;aop:aspectj-autoproxy/\u0026gt; tag, shown in Code 6-2.\nCode 6-2. \u0026quot;beans.xml\u0026quot;\n1\u0026lt;?xml version = \u0026#34;1.0\u0026#34; encoding = \u0026#34;UTF-8\u0026#34;?\u0026gt; 2\u0026lt;beans xmlns = \u0026#34;http://www.springframework.org/schema/beans\u0026#34; 3 xmlns:xsi = \u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 4 xmlns:aop = \u0026#34;http://www.springframework.org/schema/aop\u0026#34; 5 xsi:schemaLocation = \u0026#34;http://www.springframework.org/schema/beans 6http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 7http://www.springframework.org/schema/aop 8http://www.springframework.org/schema/aop/spring-aop-3.0.xsd \u0026#34;\u0026gt; 9 10 \u0026lt;!-- AOP Configurations --\u0026gt; 11 \u0026lt;aop:aspectj-autoproxy/\u0026gt; 12 13 \u0026lt;!-- Bean definition for student --\u0026gt; 14 \u0026lt;bean id = \u0026#34;student\u0026#34; class = \u0026#34;com.example.aop.Student\u0026#34;\u0026gt; 15 \u0026lt;property name = \u0026#34;name\u0026#34; value = \u0026#34;Tom\u0026#34; /\u0026gt; 16 \u0026lt;property name = \u0026#34;age\u0026#34; value = \u0026#34;83\u0026#34;/\u0026gt; 17 \u0026lt;/bean\u0026gt; 18 19 \u0026lt;!-- Bean definition for logging aspect --\u0026gt; 20 \u0026lt;bean id = \u0026#34;logging\u0026#34; class = \u0026#34;com.example.aop.Logging\u0026#34;/\u0026gt; 21 22\u0026lt;/beans\u0026gt; Code 6-2 shows how to use \u0026lt;aop:aspectj-autoproxy/\u0026gt; tag to simplify AOP configuration.\nThen I will rewrite the Code 6-1(a, c) to show how to use AspectJ. To declare Pointcuts and Advices, rewrite Code 6-1(a) to Code 6-1-AOP(a):\nCode 6-1-AOP(a). \u0026quot;Logging.java\u0026quot;\n1package com.example.aop; 2 3import org.aspectj.lang.annotation.Aspect; 4import org.aspectj.lang.annotation.Pointcut; 5import org.aspectj.lang.annotation.Before; 6import org.aspectj.lang.annotation.After; 7import org.aspectj.lang.annotation.AfterThrowing; 8import org.aspectj.lang.annotation.AfterReturning; 9// import org.aspectj.lang.annotation.Around; 10 11@Aspect 12public class Logging { 13 14 /* 15A pointcut named \u0026#34;selectAll\u0026#34; is defined using `@Pointcut` 16to target *all methods* 17within the package \u0026#34;com.example.aop\u0026#34; and its sub-packages. 18the method `selectAll()` is just a signature 19*/ 20 @Pointcut(\u0026#34;execution(* com.example.aop.*.*(..))\u0026#34;) 21 private void selectAll(){} 22 23 @Before(\u0026#34;selectAll()\u0026#34;) 24 public void beforeAdvice(){ 25 System.out.println(\u0026#34;`beforeAdvice()` invoked.\u0026#34;); 26 } 27 28 @After(\u0026#34;selectAll()\u0026#34;) 29 public void afterAdvice(){ 30 System.out.println(\u0026#34;`afterAdvice()` invoked.\u0026#34;); 31 } 32 33 @AfterReturning(pointcut = \u0026#34;selectAll()\u0026#34;, returning = \u0026#34;retVal\u0026#34;) 34 public void afterReturningAdvice(Object retVal) { 35 System.out.println(\u0026#34;[Success] `afterReturningAdvice()` reads return value: \u0026#34; + retVal.toString() ); 36 System.out.println(\u0026#34;------\u0026#34;); 37 } 38 39 @AfterThrowing(pointcut = \u0026#34;selectAll()\u0026#34;, throwing = \u0026#34;exception\u0026#34;) 40 public void afterThrowingAdvice(Exception exception){ 41 System.out.println(\u0026#34;[FAILURE] `afterThrowingAdvice()` detects Exception: \u0026#34; + exception.toString()); 42 System.out.println(\u0026#34;------\u0026#34;); 43 } 44} Code 6-1-AOP(a) defines an AspectJ aspect named Logging, which contains advice methods (@Before, @After, @AfterReturning, @AfterThrowing) to log messages before and after the execution of all methods in the package \u0026quot;com.example.aop\u0026quot; and its sub-packages, as well as handling method return values and exceptions.\nNote: in XML Schema based AOP, we use \u0026lt;aop:pointcut id = \u0026quot;POINTCUT_NAME\u0026quot; expression = \u0026quot;POINTCUT_EXPRESSION\u0026quot;; in AspectJ based AOP, we use @Pointcut(\u0026quot;POINTCUT_EXPRESSION\u0026quot;) annotation on an empty method called private void POINTCUT_NAME(){}.\nThe expected output for Code 6-1-AOP(a), Code 6-1(b, c), and Code 6-2 should be:\n1`beforeAdvice()` invoked. 2Class method `getName()` gets `name` = Tom 3[Success] `afterReturningAdvice()` reads return value: Tom 4------ 5`afterAdvice()` invoked. 6`beforeAdvice()` invoked. 7Class method `getAge()` gets `age` = 83 8[Success] `afterReturningAdvice()` reads return value: 83 9------ 10`afterAdvice()` invoked. 11`beforeAdvice()` invoked. 12Class method `throwsException()` will throw \u0026#39;IllegalArgumentException\u0026#39; 13[FAILURE] `afterThrowingAdvice()` detects Exception: java.lang.IllegalArgumentException 14------ 15`afterAdvice()` invoked. 16Exception in thread \u0026#34;main\u0026#34; java.lang.IllegalArgumentException 17\tat com.example.aop.Student.throwsException(Student.java:26) 18 (Omit the rest Exception message...) And if we want to target the Pointcut to Student.getName() method only, we can modify Code 6-1-AOP(a) to Code 6-1-AOP-selectGetName(a):\nCode 6-1-AOP-selectGetName(a). \u0026quot;Logging.java\u0026quot;\n1package com.example.aop; 2 3import org.aspectj.lang.annotation.Aspect; 4import org.aspectj.lang.annotation.Pointcut; 5import org.aspectj.lang.annotation.Before; 6import org.aspectj.lang.annotation.After; 7import org.aspectj.lang.annotation.AfterThrowing; 8import org.aspectj.lang.annotation.AfterReturning; 9// import org.aspectj.lang.annotation.Around; 10 11@Aspect 12public class Logging { 13 14 /* 15A pointcut named \u0026#34;selectGetName\u0026#34; using an expression 16to target the `getName()` method of the `Student` class. 1718Note: `(..)` is a wildcard that 19represents zero or more arguments of any type. 20*/ 21 @Pointcut(\u0026#34;execution(* com.example.aop.Student.getName(..))\u0026#34;) 22 private void selectGetName(){} 23 24 @Before(\u0026#34;selectGetName()\u0026#34;) 25 public void beforeAdvice(){ 26 System.out.println(\u0026#34;`beforeAdvice()` invoked.\u0026#34;); 27 } 28 29 @After(\u0026#34;selectGetName()\u0026#34;) 30 public void afterAdvice(){ 31 System.out.println(\u0026#34;`afterAdvice()` invoked.\u0026#34;); 32 } 33 34 @AfterReturning(pointcut = \u0026#34;selectGetName()\u0026#34;, returning = \u0026#34;retVal\u0026#34;) 35 public void afterReturningAdvice(Object retVal) { 36 System.out.println(\u0026#34;[Success] `afterReturningAdvice()` reads return value: \u0026#34; + retVal.toString() ); 37 System.out.println(\u0026#34;------\u0026#34;); 38 } 39 40 @AfterThrowing(pointcut = \u0026#34;selectGetName()\u0026#34;, throwing = \u0026#34;exception\u0026#34;) 41 public void afterThrowingAdvice(Exception exception){ 42 System.out.println(\u0026#34;[FAILURE] `afterThrowingAdvice()` detects Exception: \u0026#34; + exception.toString()); 43 System.out.println(\u0026#34;------\u0026#34;); 44 } 45} Code 6-1-AOP-selectGetName(a) changes pointcut to target only on method Student.getName().\nThe expected output for Code 6-1-AOP-selectGetName(a), Code 6-1(b, c), and Code 6-2 should be:\n1`beforeAdvice()` invoked. 2Class method `getName()` gets `name` = Tom 3[Success] `afterReturningAdvice()` reads return value: Tom 4------ 5`afterAdvice()` invoked. 6Class method `getAge()` gets `age` = 83 7Class method `throwsException()` will throw \u0026#39;IllegalArgumentException\u0026#39; 8Exception in thread \u0026#34;main\u0026#34; java.lang.IllegalArgumentException 9\tat com.example.aop.Student.throwsException(Student.java:24) 10\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 11\t(Omit the rest message...) ","link":"https://mighten.github.io/2023/07/spring-framework/","section":"post","tags":["Java","Spring"],"title":"Spring Framework"},{"body":"","link":"https://mighten.github.io/series/web/","section":"series","tags":null,"title":"Web"},{"body":"","link":"https://mighten.github.io/tags/devops/","section":"tags","tags":null,"title":"DevOps"},{"body":"Maven is a project management tool that is based on POM (project object model). It is used for projects build, dependency and documentation.\nThis blog is built on Windows 10 (x64-based):\n Maven: 3.8.7 JDK 1.8 CONFIGURATION settings.xml In C:\\Program Files\\Java\\apache-maven-3.8.7\\conf\\settings.xml:\n to make C:\\maven-repo a local Maven Repository, add the following to C:\\Program Files\\Java\\apache-maven-3.8.7\\conf\\settings.xml: 1\u0026lt;localRepository\u0026gt;C:\\maven-repo\u0026lt;/localRepository\u0026gt; JDK Version C:\\Program Files\\Java\\apache-maven-3.8.7\\conf\\settings.xml: 1\u0026lt;profile\u0026gt; 2 \u0026lt;id\u0026gt;jdk-1.8\u0026lt;/id\u0026gt; 3 \u0026lt;activation\u0026gt; 4 \u0026lt;activeByDefault\u0026gt;true\u0026lt;/activeByDefault\u0026gt; 5 \u0026lt;jdk\u0026gt;1.8\u0026lt;/jdk\u0026gt; 6 \u0026lt;/activation\u0026gt; 7 \u0026lt;properties\u0026gt; 8 \u0026lt;maven.compiler.source\u0026gt;1.8\u0026lt;/maven.compiler.source\u0026gt; 9 \u0026lt;maven.compiler.target\u0026gt;1.8\u0026lt;/maven.compiler.target\u0026gt; 10 \u0026lt;maven.compiler.compilerVersion\u0026gt;1.8\u0026lt;/maven.compiler.compilerVersion\u0026gt; 11 \u0026lt;/properties\u0026gt; 12\u0026lt;/profile\u0026gt; Environment Variables First, check the version of current Java compiler by:\n1$ java -version Second, add JDK-related environment variables:\n set/new JAVA_HOME to C:\\Program Files\\Java\\jdk1.8.0_231 append %JAVA_HONE%\\bin to %PATH% set/new JAVA_TOOL_OPTIONS to -Dfile.encoding=UTF-8 Third, add Maven-related environment variables:\n set/new MAVEN_HOME to C:\\Program Files\\Java\\apache-maven-3.8.7 set/new M2_HOME to %MAVEN_HOME% append %MAVEN_HOME%\\bin to %PATH% set/new MAVEN_OPTS to -Xms256m -Xmx512m -Dfile.encoding=UTF-8 Fourth, open a new termianal and test Maven with command:\n1$ mvn --version BEGINNER PRACTICE Maven uses 3 vectors to locate a *.jar package:\n groupId: company/organization domain name in reverse order artifactId: project name, or module name in a project version: SNAPSHOT or RELEASE Quick and Simple In this section, I will create a quick and simple Maven Java project, which will serve as a template in the late project.\nConsidering my Blog address is https://mighten.github.io, and this is a learning practice for Maven, so my group id will be io.github.mighten.learn-maven, and artifact id will be maven-java.\n1$ mkdir C:\\maven-workspace\\learn-maven 2$ cd C:\\maven-workspace\\learn-maven 3 4$ mvn archetype:generate Note:\n Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 7: (Press Enter to confirm default value) Define value for property 'groupId': io.github.mighten.learn-maven Define value for property 'artifactId': maven-java Define value for property 'version' 1.0-SNAPSHOT: : (Press Enter to confirm default value) Define value for property 'package' io.github.mighten.learn-maven: : (Press Enter to confirm default value) Y: : (Press Enter to confirm default value) And the BUILD SUCCESS is shown.\nChange Dependencies First, in path learn-maven/maven-jave/src, delete the default Java files:\n src/main/java/io/github/mighten/learn-maven/App.java src/test/java/io/github/mighten/learn-maven/AppTest.java Second, modify the version of JUnit (in learn-maven/maven-jave/pom.xml) from 3.8.1 to 4.12\nMAVEN COMMANDS change working directory to the directory of the current pom.xml.\n clean 1$ mvn clean delete the target folder\ncompile the main 1$ mvn compile target file in target/classes\ntest 1$ mvn test-compile 2$ mvn test target file in target/test-classes\npack to *.jar 1$ mvn package install into local Maven Repository 1$ mvn install Trick:\n1$ mvn clean install DEPENDENCY MANAGEMENT Dependency management is a core feature of Maven.\nScope Scope is used to define the dependencies of a project, e.g., JUnit in pom.xml has \u0026lt;scope\u0026gt;test\u0026lt;/scope\u0026gt;:\n1\u0026lt;dependency\u0026gt; 2 \u0026lt;groupId\u0026gt;junit\u0026lt;/groupId\u0026gt; 3 \u0026lt;artifactId\u0026gt;junit\u0026lt;/artifactId\u0026gt; 4 \u0026lt;version\u0026gt;4.12\u0026lt;/version\u0026gt; 5 \u0026lt;scope\u0026gt;test\u0026lt;/scope\u0026gt; 6\u0026lt;/dependency\u0026gt; And we should notice:\n compile (default scope): used for both the compilation and the runtime of the project. But the Compile Scope does not use the classes in Test Scope test: used for testing, but not required for the runtime provided: used for dependencies that are part of the Java EE or other container environments. But the Provided Scope will not be packed into *.jar. Scope Name /main /test Develop Deploy compile valid valid valid valid test N/A valid valid N/A provided valid valid valid N/A These scopes help manage the classpath and control which dependencies are included at different stages of the build process.\nPropagation In the Maven tree, if the dependency of a child is compile-scope, then it can propagate to the parent; otherwise, if dependency of a child is test-scope or provided-scope, then it can not propagate to the parent.\nFor example, if I write a project_1.jar, which adds a dependency to JUnit with test scope. Then I create project_2 which uses a dependency to project_1.jar. The JUnit dependency will not be available for project_2 because JUnit is in test scope; if I want to use JUnit in project_2, I have to explicitly declare JUnit in pom.xml of project_2.\nIn addition, Maven can create an ASCII-styled dependency-tree graph, with the following command:\n1$ mvn dependency:tree Exclusion Dependency Exclusions are used to fix *.jar confrontations.\nFor example, if I create a project_3 will add dependencies on project_1.jar (uses package A version 1.1) and project_2.jar (uses package A version 1.6), then certainly the package A will have confrontation with two version. To fix this issue, we usually choose the higher version (1.6) and exclude the lower version 1.1. So I will exclude package A in dependency of project_1.jar (in pom.xml of project_3):\n1\u0026lt;dependency\u0026gt; 2\t\u0026lt;groupId\u0026gt;io.github.mighten.learn_maven\u0026lt;/groupId\u0026gt; 3\t\u0026lt;artifactId\u0026gt;project_1\u0026lt;/artifactId\u0026gt; 4\t\u0026lt;version\u0026gt;1.0-SNAPSHOT\u0026lt;/version\u0026gt; 5\t\u0026lt;scope\u0026gt;compile\u0026lt;/scope\u0026gt; 6 7\t\u0026lt;exclusions\u0026gt; 8\t\u0026lt;!-- 9to exclude package `A`, 10(no need to specify version) 11--\u0026gt; 12\t\u0026lt;exclusion\u0026gt; 13\t\u0026lt;groupId\u0026gt;A\u0026lt;/groupId\u0026gt; 14\t\u0026lt;artifactId\u0026gt;A\u0026lt;/artifactId\u0026gt; 15\t\u0026lt;/exclusion\u0026gt; 16 17 \u0026lt;!-- 18to exclude other packages 19\u0026lt;exclusion\u0026gt; 20\u0026lt;groupId\u0026gt;\u0026lt;/groupId\u0026gt; 21\u0026lt;artifactId\u0026gt;\u0026lt;/artifactId\u0026gt; 22\u0026lt;/exclusion\u0026gt; 23--\u0026gt; 24\t\u0026lt;/exclusions\u0026gt; 25\u0026lt;/dependency\u0026gt; Inheritance Dependency Inheritance allows child POM to inherit dependency from a parent POM. It is typically used to prevent version confrontations. In pom.xml of parent project:\n set parent project parent to pack into POM file \u0026lt;packaging\u0026gt;pom\u0026lt;/packaging\u0026gt;, which will allow the parent to manage all the child projects.\n add tag \u0026lt;dependencyManagement\u0026gt; in pom.xml of parent, to manage all the dependencies:\n 1\u0026lt;dependencyManagement\u0026gt; 2\t\u0026lt;dependencies\u0026gt; 3\t\u0026lt;dependency\u0026gt; 4\t\u0026lt;groupId\u0026gt;org.springframework\u0026lt;/groupId\u0026gt; 5\t\u0026lt;artifactId\u0026gt;spring-core\u0026lt;/artifactId\u0026gt; 6\t\u0026lt;version\u0026gt;4.0.0.RELEASE\u0026lt;/version\u0026gt; 7\t\u0026lt;/dependency\u0026gt; 8 \u0026lt;!-- other dependencies --\u0026gt; 9\t\u0026lt;/dependencies\u0026gt; 10\u0026lt;/dependencyManagement\u0026gt; Note: the packages are not really import into the parent project\nadd tag \u0026lt;parent\u0026gt; to pom.xml of every children: 1\u0026lt;parent\u0026gt; 2\t\u0026lt;groupId\u0026gt;com.atguigu.maven\u0026lt;/groupId\u0026gt; 3\t\u0026lt;artifactId\u0026gt;pro03-maven-parent\u0026lt;/artifactId\u0026gt; 4\t\u0026lt;version\u0026gt;1.0-SNAPSHOT\u0026lt;/version\u0026gt; 5\u0026lt;/parent\u0026gt; add dependencies into children pom.xml, and since the version is declared in parental pom.xml, the version in the children pom.xml can be omitted. Aggregation If we want to aggregate all of the children projects into one, we can config in parent.xml (similar to inheritance):\n1\u0026lt;modules\u0026gt; 2 \u0026lt;module\u0026gt;child_1\u0026lt;/module\u0026gt; 3 \u0026lt;module\u0026gt;child_2\u0026lt;/module\u0026gt; 4 \u0026lt;module\u0026gt;child_3\u0026lt;/module\u0026gt; 5\u0026lt;/modules\u0026gt; Note: DO NOT use cyclic reference.\n","link":"https://mighten.github.io/2023/06/maven/","section":"post","tags":["DevOps"],"title":"Maven"},{"body":"Docker is a platform for developing, shipping, and deploying applications quickly in portable, self-sufficient containers, and is used in the Continuous Deployment (CD) stage of the DevOps ecosystem.\nINSTALLATION Environment: CentOS 7 Minimal on VMware Player 17\n1$ yun update 2$ yum install -y \\ 3 yum-utils \\ 4 device-mapper-persistent-data \\ 5 lvm2 6$ yum-config-manager \\ 7 --add-repo https://download.docker.com/linux/centos/docker-ce.repo 8$ yum install -y docker-ce 9$ docker -v DOCKER COMMANDS DAEMON Daemon is a special process of Docker, To start/stop/restart Docker, or to get the status of Docker:\n1$ systemctl start docker 2$ systemctl stop docker 3$ systemctl restart docker 4$ systemctl status docker To enable autostart:\n1$ systemctl enable docker IMAGE List Images To list local images, type:\n1$ docker images and it will return a table like:\n REPOSITORY TAG IMAGE ID CREATED SIZE Note:\n REPOSITORY: the software or service name TAG: version number If we just need Docker Image ID, we can add a parameter -q\n1$ docker images -q Search Images 1$ docker search redis and it will return a table like:\n NAME DESCRIPTION STARS OFFICIAL AUTOMATED redis Redis is an open source key-value store that… 12156 [OK] Note: OFFICIAL is [OK] meaning that this image is maintained by Redis team.\nPull Images If we want to pull Redis, we just type:\n1$ docker pull redis And the latest Redis (i.e., TAG \u0026quot;redis:latest\u0026quot;) will be pulled into local machine. However, if we want to pull Redis 5.0, open Docker Hub to verify if it is available, and then:\n1$ docker pull redis:5.0 Remove Images to remove a Docker Image (called redis:5.0 or Image ID is c5da061a611a), we can type any one of them:\n1$ docker rmi redis:5.0 2$ docker rmi c5da061a611a Trick: If we want to remove all the images, we can use:\n1$ docker rmi `docker images -q` CONTAINER A Container is built out of Docker Image.\nContainer Status and Inspection The status for a container can be UP or Exited.\n1$ docker ps # List all the running container 2$ docker ps --all # List all the history container(s) 3$ docker ps -a # Also List all the history container(s) Or, we can inspect a container for more details:\n1$ docker inspect CONTAINER_NAME Create Container To create a docker container out of an image, we will first pull image centos:7 from remote repository:\n1$ docker pull centos:7 Interactive Container: create docker image container with centos:7, and then enter the container. These three docker run commands are equivalent: 1$ docker run --interactive --tty --name=test_container centos:7 /bin/bash 2$ docker run -i -t --name=test_container centos:7 /bin/bash 3$ docker run -it --name=test_container centos:7 /bin/bash Note:\n --interactive or -i: keeps STDIN open even if not attached --tty or -t: allocates a pseudo-TTY --name=test_container: assigns a name \u0026quot;test_container\u0026quot; to this container centos:7: this container is built on the image called 'centos:7' /bin/bash: docker will run /bin/bash of container. the terminal identidy will switch from root@localhost to root@9b7d0441909b, meaning the container (9b7d0441909b) is now started. Detached Container: Detached Container will not be executed once created, and will not be terminated after $ exit. These three commands are equivalent: 1$ docker run --interactive --detach --name=test_container2 centos:7 2$ docker run -i -d --name=test_container2 centos:7 3$ docker run -id --name=test_container2 centos:7 Enter Container In the last section, we created a container but not enter into it, and we can enter by these 3 equivalent docker exec commands:\n1$ docker exec --interactive --tty test_container2 /bin/bash 2$ docker exec -i -t test_container2 /bin/bash 3$ docker exec -it test_container2 /bin/bash Stop or Start Container 1$ docker stop CONTAINER_NAME 2$ docker start CONTAINER_NAME where CONTAINER_NAME is set accordingly by command $ docker ps --all.\nRemove Container 1$ docker rm CONTAINER_NAME Note:\n An UP-status docker container cannot be removed, we have to bring it to Exited before removal Note the difference between the removal of image and container: to remove image, we type: docker rmi, and to remove container, we type: docker rm. VOLUMES Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.\nVolume Mapping To persist data, we can use volume to map the folders. These two commands are equivalent:\n1$ docker run -it \\ 2 --name=testVol1 \\ 3 --volume ~/data1:/root/container_data1 \\ 4 --volume ~/data2:/root/container_data2 \\ 5 centos:7 \\ 6 /bin/bash 7 8$ docker run -it \\ 9 --name=testVol1 \\ 10 -v ~/data1:/root/container_data1 \\ 11 -v ~/data2:/root/container_data2 \\ 12 centos:7 \\ 13 /bin/bash Note:\n --volume or -v: map the folder to the container with synchronization. Outside container, we use folders ~/data1/ and ~/data2/; Inside container, we use /root/container_data1 and /root/container_data2 we can only explicitlly use the path /root/* (not ~/*) inside container Volume Container We first create a container called c3, and this will be our Volume Container: (Note the parameter -v /Volume)\n1$ docker run -it \\ 2 --name=c3 \\ 3 -v /Volume \\ 4 centos:7 \\ 5 /bin/bash Then, we will create two containers, and mount them onto c3 in two separate SSH sessions:\n1$ docker run -it --name=c1 \\ 2 --volumes-from c3 \\ 3 centos:7 /bin/bash 4$ docker run -it --name=c2 \\ 5 --volumes-from c3 \\ 6 centos:7 /bin/bash you can use $ docker inspect c3 to find out where where c3 is mounted, and snippet of docker inspect response shown below:\n1...... 2\u0026#34;Mounts\u0026#34;: [ 3 { 4 \u0026#34;Type\u0026#34;: \u0026#34;volume\u0026#34;, 5 \u0026#34;Name\u0026#34;: \u0026#34;266**298fb7\u0026#34;, 6 \u0026#34;Source\u0026#34;: \u0026#34;/var/lib/docker/volumes/266**298fb7/_data\u0026#34;, 7 ...... 8 } 9 ...... 10] 11...... so, we can see that /var/lib/docker/volumes/266**298fb7/_data outside of container c3 is mapped into /Volume folder in Docker containers c1, c2 and c3.\nDEPLOYMENT MySQL Deploy MySQL 5.6 into container, and map its port from 3306 (inside container) to port 3307 (outside container).\nFirst, we need to pull MySQL 5.6\n1$ docker search mysql 2$ docker pull mysql:5.6 Second, we need to create container:\n1$ mkdir ~/mysql 2$ docker run -id \\ 3 -p 3307:3306 \\ 4 --name=c_mysql \\ 5 -v ~/mysql/conf:/etc/mysql/conf.d \\ 6 -v ~/mysql/logs:/logs \\ 7 -v ~/mysql/data:/var/lib/mysql \\ 8 -e MYSQL_ROOT_PASSWORD=toor \\ 9 mysql:5.6 Note:\n -p 3307:3306 or --expose 3307:3306: map the port 3307 (outside container) to the container's port 3306. -e or --env: set the environment variable MYSQL_ROOT_PASSWORD as toor, which is the root password set for MySQL. Third, we start and enter the container and test it:\n1$ docker exec -it c_mysql /bin/bash 2$ mysql -uroot -p toor Fourth, open MySQL with visual tool such as SQLyog Community\nTomcat Map the port 8081 (outside container) to port 8080 (inside container):\n1$ docker search tomcat 2$ docker pull tomcat 3$ mkdir ~/tomcat 4$ docker run -id \\ 5 --name=c_tomcat \\ 6 -p 8081:8080 \\ 7 -v ~/tomcat:/usr/local/tomcat/webapps \\ 8 tomcat Now we can publish Servlet to folder ~/tomcat/ (outside container), and Tomcat inside container will find it in path /usr/local/tomcat/webapps. For demo, I just put a simple HTML ~/tomcat/test/index.html:\n1$ mkdir ~/tomcat/test 2$ echo \u0026#34;Hello Tomcat in Container\u0026#34; \u0026gt; ~/tomcat/test/index.html Now that the IP address outside container is 192.168.109.128, I open http://192.168.109.128:8081/test/index.html, and it will display \u0026quot;Hello Tomcat in Container\u0026quot;.\nNGINX First, search and pull NGINX image.\n1$ docker search nginx 2$ docker pull nginx 3$ mkdir ~/nginx 4$ mkdir ~/nginx/conf Second, Copy the nginx.conf at /etc/conf/nginx.conf (inside contanier), and paste into ~/nginx/conf/nginx.conf (inside container):\nuser nginx;\rworker_processes auto;\rerror_log /var/log/nginx/error.log notice;\rpid /var/run/nginx.pid;\revents {\rworker_connections 1024;\r}\rhttp {\rinclude /etc/nginx/mime.types;\rdefault_type application/octet-stream;\rlog_format main '$remote_addr - $remote_user [$time_local] \u0026quot;$request\u0026quot; '\r'$status $body_bytes_sent \u0026quot;$http_referer\u0026quot; '\r'\u0026quot;$http_user_agent\u0026quot; \u0026quot;$http_x_forwarded_for\u0026quot;';\raccess_log /var/log/nginx/access.log main;\rsendfile on;\r#tcp_nopush on;\rkeepalive_timeout 65;\r#gzip on;\rinclude /etc/nginx/conf.d/*.conf;\r}\rThird, start container:\n1$ docker run -id \\ 2 --name=c_nginx \\ 3 -p 80:80 \\ 4 -v ~/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \\ 5 -v ~/nginx/logs:/var/log/nginx \\ 6 -v ~/nginx/html:/usr/share/nginx/html \\ 7 nginx Now that the IP address outside container is 192.168.109.128, I open http://192.168.109.128:80, and it will display \u0026quot;Hello NGINX in Container\u0026quot;.\nRedis 1$ docker search redis 2$ docker pull redis:5.0 3$ docker run -id \\ 4 --name=c_redis \\ 5 -p 6379:6379 \\ 6 redis:5.0 DOCKERFILE A Dockerfile is a text document that contains all the instructions a user could call on the command line to build an image. And Docker runs instructions in a Dockerfile in order.\nExamples Deploy Spring Boot Frist, prepare the Spring Boot project. In this case, we will @RequestMapping(\u0026quot;/helloworld\u0026quot;) to print \u0026quot;Hello World\u0026quot; on http://localhost:8080/hello.\nSecond, pack the project to single *.jar file. In tab Maven Projects - \u0026lt;Your Spring Boot Project Name\u0026gt; - Lifecycle - package, and test *.jar file with: (the complete path is shown in Console))\n1$ java -jar /path/to/springboot-hello.jar Third, upload to CentOS 7 with SFTP command:\n1sftp\u0026gt; PUT /path/to/springboot-hello.jar And springboot-hello.jar will be uploaded as springboot-hello.jar (outside container). Later this file will be moved into ~/springboot-docker/springboot-hello.jar (also outside container).\nFourth, write springboot_dockerfile in path ~/springboot-docker/ (outside container):\n1# 1. Require Parent Docker Image: `java:8`2FROMjava:834# 2. Add `springboot-hello.jar` into container as `app.jar`5ADD springboot-hello.jar app.jar67# 3. command to execute Spring Boot app8CMD java -jar app.jarFifth, build the Docker;\n1$ docker build \\ 2 --file ./springboot_dockerfile \\ 3 --tag springboot-hello-app \\ 4 ~/springboot-docker Note:\n --file or -f: specifies the Dockerfile named springboot_dockerfile. --tag or -t: tags the image as springboot-hello-app Sixth, start the image springboot-hello-app\n1$ docker run -id -p 9090:8080 springboot-hello-app Now that the IP address outside container is 192.168.109.128, we can display the Spring Boot app at http://192.168.109.128:9090/hello\nTailored CentOS In path ~/tailored_centos/, create Dockerfile called centos_tailored_dockerfile:\n1# 1. Specify the parent Docker Image: `centos:7`2FROMcentos:734# 2. Specify the software to be installed5RUN yum install -y tomcat67# 3. Change to directory8WORKDIR/usr/local/tomcat/webapps910# 4. Set command to be executed11CMD /bin/bash1213# 5. Expose port14EXPOSE8080/tcp15EXPOSE8080/udp16## this also can be done with shell:17## $ docker run \\18## -p 8080:8080/tcp \\19## -p 8080:8080/udp \\20## \u0026lt;the rest parameters...\u0026gt;Then we will build the docker:\n1$ docker build \\ 2 -f ./centos_tailored_dockerfile \\ 3 -t tailored_centos:1 4 ~/tailored_centos Next, we will run the container out of the docker image:\n1$ docker run -it \\ 2 --name=c_tailored_centos \\ 3 tailored_centos:1 Syntax Syntax of Dockerfile:\n Name Description FROM specifies the Parent Image from which you are building RUN execute commands in a new layer on top of the current image and commit the results CMD sets the command to be executed when running the image. LABEL adds metadata (key-value pairs) to a docker image EXPOSE informs Docker that the container listens on the specified network ports at runtime (tcp by default) ENV sets the environment variable ADD copies new files, directories or remote file URLs from \u0026lt;src\u0026gt; and adds them to the filesystem of the image at the path \u0026lt;dest\u0026gt; COPY copies new files or directories from \u0026lt;src\u0026gt; and adds them to the filesystem of the container at the path \u0026lt;dest\u0026gt; ENTRYPOINT allows you to configure a container that will run as an executable VOLUME creates a mount point and marks it as holding externally mounted volumes from native host or other containers USER sets the user name (UID) and optionally the user group (GID) to use as the default user and group for the remainder of the current stage WORKDIR sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile ARG defines a variable that users can pass at build-time to the builder with the $ docker build command ONBUILD adds to the image a trigger instruction to be executed at a later time, when the image is used as the base for another build STOPSIGNAL sets the system call signal that will be sent to the container to exit HEALTHCHECK tells Docker how to test a container to check that it is still working SHELL allows the default shell used for the shell form of commands to be overridden ","link":"https://mighten.github.io/2023/06/docker/","section":"post","tags":["DevOps"],"title":"Docker"},{"body":"Hi!\nToday we use OpenSSH and PuTTY to log in remote computers.\n OpenSSH is an open-source version of the Secure Shell (SSH) tools used by administrators of remote systems PuTTY is a free implementation of SSH This blog is built on the following environment:\n Host Machine: OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2, and PuTTY Release 0.78 on Windows 10 x64. Virtual Machine (Server): CentOS 7 Minimal on VMware Player 17 (Intel-VT Virtualization: ON) Generate Key Pair SSH requires public/private key pair. The public key is stored on server to authenticate the user who has the corresponding private key. For simplicity, I will use PuTTY to generate public/private key pair:\n Open PUTTYGEN.EXE of PuTTY installation directory. Click \u0026quot;Generate\u0026quot; to generate public/private key pair Set Key passphase and Confirm the passphase. Click \u0026quot;Save private key\u0026quot;, and export to a putty_private_key.ppk file Copy the content of \u0026quot;Public key for pasting into OpenSSH authorized_keys file\u0026quot; (begin with ssh-rsa ...), and paste it in server file (~/.ssh/authorized_keys of CentOS 7). Open PUTTY.EXE of PuTTY installation directory In the left menu, unfold category to find Connection/SSH/Auth/Credentials, and \u0026quot;Browse\u0026quot; to find putty_private_key.ppk In the left menu, click Session, type in the IP address and \u0026quot;Save\u0026quot; this session with a name, like \u0026quot;CentOS7_VM\u0026quot; Config Server If we want to log in without password, we will config the server:\n (Optional) Allow SSH login as root: (find the following item and change its property in /etc/ssh/sshd_config to yes) 1PermitRootLogin yes Ensure the Public key authentication is enabled: (find the following items and change their properties in /etc/ssh/sshd_config to yes) 1RSAAuthentication yes 2PubkeyAuthentication yes Restrict to use the authorized public keys only: (to disallow password, find the following item and change its property in /etc/ssh/sshd_config to no) 1PasswordAuthentication no Restart SSH service to validate changes: (in terminal) 1$ service sshd restart Connect Open PUTTY.EXE, \u0026quot;Load\u0026quot; the saved session called CentOS7_VM, and \u0026quot;Open\u0026quot;\n1login as: \u0026lt;Your User Name\u0026gt; 2Authenticating with public key \u0026#34;rsa-key-YYYYMMDD\u0026#34; 3Passphrase for key \u0026#34;rsa-key-YYYYMMDD\u0026#34;: \u0026lt;Your Passphrase For private key\u0026gt; So now we can log in with no passwords in transmission.\nHowever, if you do not want to protect the private key (putty_private_key.ppk) with passphrase at all, you can load your private key with PUTTYGEN.EXE and then override the private key with no passphrase. (Highly unrecommended)\n","link":"https://mighten.github.io/2023/06/putty-with-openssh/","section":"post","tags":["DevOps"],"title":"PuTTY with OpenSSH"},{"body":"","link":"https://mighten.github.io/series/mit-6.033/","section":"series","tags":null,"title":"MIT 6.033"},{"body":"MIT 6.033 (Computer System Engineering) covers 4 parts: Operating Systems, Networking, Distributed Systems, and Security.\nThis is the course note for Part IV: Security. And in this section, we mainly focus on common pitfalls in the security of computer systems, and how to combat them.\nTo build a secure system, we need to be clear about two aspects:\n security policy (goal) threat model (assumptions on adversaries) Authentication In this section, we authenticate users through username and password.\n Security Policy: provide authentication for users Threat Model: adversary has access to the entire stored username-password table and get password. One solution is to use hash functions $H$, which take an input string of arbitary size and output a fixed-length string:\n $H$ is deterministic: if $x_1 = x_2$, then $H(x_1) = H(x_2)$ $H$ is collision-resistant: if $x_1 \\neq x_2$, then the probability of $H(x_1)=H(x_2)$ is virtually $0$. $H$ is one-way: given $x$, it is easy to compute $H(x)$; given $H(x)$ without knowing $x$, it is virtually impossible to determine $x$. But the adversary can still use Rainbow Table to precompute hashes to determine password. This issue can be mitigated by slow hash functions with salt (a random info stored in plaintext), making it infeasible to determine password, especially without knowing salt.\nAnother solution is to limit transmission of passwords, because transmitting password frequently opens a user up to other attacks outside our current threat model.\n Session Cookies allow users to authenticate themselves for a period of time, without repeatedly transmitting their passwords. sequenceDiagram\rtitle: Figure 1. Session Cookies\ractor User\rparticipant Server\rUser-\u0026gt;\u0026gt;+Server: username/password\rServer--\u0026gt;\u0026gt;-User: cookie\rUser-\u0026gt;\u0026gt;Server: cookie\r Challenge-Response Protocols authenticate users without ever transmitting passwords. sequenceDiagram\rtitle: Figure 2. Challenge-Response Protocols\ractor User\rparticipant Server\rServer-\u0026gt;\u0026gt;User: 658427(random number)\rUser--\u0026gt;\u0026gt;Server: H(password | 658427)\rHowever, there are always trade-offs, many other measures do add security, but often add complexity and decrease usability.\nLow-Level Exploits In this section, our threat model is that the adversary has the ability to run code on that machine, and the goal of adversary is to input a string that overwrites the saved instruction pointer so that the code jumps to the target function to open a shell.\nThere is no perfect solution for this issue. Modern Linux has protections(NX, ASLR, etc.) to prevent attacks, but there are also some counter-attacks(return-to-libc, heap-smashing, pointer-subterfuge, etc.) to those protections. And Bound-checking is also a solution, but it ruins the ability to generate compact C code.(Note the trade-offs of security vs. performance)\nThe Ken Thompson Hack (in essay Reflections on Trusting Trust, Thompson hacked compiler, so that it will bring backdoors to UNIX system and all subsequent versions of the C compiler) tells us that, to some extents, we cannot trust the code we didn't write ourselves. It also advocates policy-based solutions, rather than technology-based.\nSecure Channels Secure Channels protect packet data from an adversary observing data on the network.\n Security Policy: to provide confidentiality (adversary cannot learn message contents) and integrity (adversary cannot tamper with packets and go undetected). Threat Model: adversary can observe and tamper with packet data. sequenceDiagram\rtitle: Figure 3. TLS handshake\rparticipant Client\rparticipant Server\rClient-\u0026gt;\u0026gt;Server: ClientHello\rServer--\u0026gt;\u0026gt;Client: ServerHello\rServer--\u0026gt;\u0026gt;Client: {Server Certificate, CA Certificates}\rServer--\u0026gt;\u0026gt;Client: ServerHelloDone\rNote over Client: Verifies authenticity of server\rClient-\u0026gt;\u0026gt;Server: ClientKeyExchange\rNote over Server: computes keys\rClient-\u0026gt;\u0026gt;Server: Finished\rServer--\u0026gt;\u0026gt;Client: Finished\rEncrypting with symmetric keys provides secrecy, and using Message Authentication Code (MAC) provides integrity. Diffie-Hellman key exchange lets us exchange the symmetric key securely. (The reason we use symmetric key to encrypt/decrypt data is that it is faster.)\nTo verify identities, we use public-key cryptography and cryptographic signatures. We often distribute public keys with certificate authorities (CA).\nNote that the secure channel alone only provides confidentiality and integrity of packet data, but not for packet header.\nTor Tor provides some level of anonymity for users, preventing an adversary from linking senders and receivers.\n Security Policy: provide anonymity (only the client should know that it is communicating with the server) Threat Model: packet header exposes to the adversary that is A is communicating with B. However, there are still ways to attack Tor, e.g., correlating traffic analysis from various points in the network.\nDDoS Distributed Denial of Service (DDoS) is a type of cyber attack that prevents legitimate access to the Internet.\n Security Policy: maintain availability of the service. Threat Model: adversary controlls a botnet (large collection of compromised machines), and prevents access to a legitimate service via DDoS attacks. Network-Intrusion Detection Systems (NIDS) may help to mitigate DDoS attacks, but are not perfect, because DDoS attacks are sophisticated and can miminc legitimate traffic.\n","link":"https://mighten.github.io/2023/06/mit-6.033-cse-security/","section":"post","tags":["System Design"],"title":"MIT 6.033 CSE Security"},{"body":"","link":"https://mighten.github.io/tags/system-design/","section":"tags","tags":null,"title":"System Design"},{"body":"MIT 6.033 (Computer System Engineering) covers 4 parts: Operating Systems, Networking, Distributed Systems, and Security.\nThis is the course note for Part III: Distributed Systems. And in this section, we mainly focus on: How reliable, usable distributed systems are able to be built on top of an unreliable network.\nReliability via Replication In this section, we talk about how to achieve reliability via replication, especially RAID(Redundant Array of Independent Disks) that tolerates disk faults. And we assume that the entire machine could fail.\nGenerally, there are 3 steps to build reliable systems:\n identify all possible faults detect and contain the faults handle faults (\u0026quot;recover\u0026quot;) To quantify the reliability, we use availability: $$ Availability = \\frac{MTTF}{MTTF+MTTR} \\tag{1.1}$$ where MTTF (Mean Time To Failure) is the average time between non-repairable failures, and MTTR (Mean Time To Recovery) is the average time it takes to repair a system.\nRAID replicates data across disks so that it can tolerate disk failures.\n RAID-1: mirrors a single disk, but requires $2n$ disks. RAID-4: has a dedicated parity disk, requires $n+1$ disks, but all writes go to the parity disk (\u0026quot;bottleneck\u0026quot;). RAID-5: spreads out the parity (stripes a single file across multiple disks), spreads out the write requests (better performance), requires $n+1$ disks. Single-Machine Transactions In this section, we talk about abstractions to make fault-tolerance achievable: transactions. And we assume that the entire machine works fine, but some operations may fail.\nTransactions provide atomicity and isolation - make the reasoning about failures (and concurrency) easier.\nAtomicity Atomicity refers to an action either happens completely or does not happen at all.\nFor one user and one file, we implement atomicity by shadow copies (write to a temporary file, and then rename it to bank_file, for example), but they perform poorly.\nWe keep logs in cell storage on disk to record operations, so that uncommitted operations before crash can be reverted. There are two kinds of records: UPDATE and COMMIT:\n UPDATE records have the old and new values COMMIT records indicate that a transaction has been commited. To speed up the recovery process, we write checkpoints and truncate the log.\nIsolation via 2PL In this section, we use Two-Phase Locking (2PL) to run transactions ($T_1, T_2, ..., T_n$) concurrently, but to produce a schedule that is conflict serializable.\nIsolation refers to how and when the effects of one action (A1) are visible to another (A2). As a result, A1 and A2 appear to have executed serially, even though they are actually executed in parallel.\nTwo operations are conflict if they operate on the same object and at least one of them is a write. A schedule is conflict serializable if the order of all its conflicts is the same as the order of the conflicts in sequential schedule.\nWe use conflict graph to express the order of conflicts succinctly, so a schedule is conflict-serializable $\\Leftrightarrow$ it has an acyclic conflict graph. E.g., consider the following schedule:\n1T1: read(x) 2T2: write(x) 3T1: write(x) 4T3: write(x) Explanation: Start from $T1$ reading x, we find $T2$ and $T3$ want to write to x. And then $T2$ is writing to x, we find $T1$ and $T3$ want to wirte to x. And then $T1$ is writing to x, we find $T3$ want to write to x.\n---\rtitle: Figure 1. Conflict Graph\r---\rgraph LR\rT1 --\u0026gt; T2\rT1 --\u0026gt; T3\rT2 --\u0026gt; T1\rT2 --\u0026gt; T3\rSo, the conflict graph has cycle, so this schedule is not conflict-serializable.\nTwo-Phase Locking (2PL) is a concurrency control protocol used in database management systems (DBMS) to ensure the serializability of transactions. It consists of two distinct phases: the growing phase (transaction acquires locks and increases its hold on resources) and the shrinking phase (transaction releases all the locks and reduces its hold on resources).\nA valid Two-Phase Locking schedule has the following rules:\n each shared variable has a lock before any operation on a variable, the transaction must acquire the corresponding lock after a transaction releases a lock, it may not acquire any other lock However, 2PL can result in deadlock. Normal solution is to global ordering on locks. But a more elegant solution is to take advantage of the atomicity (of transactions) and abort one of the transactions.\nIf we want better performance, we use the 2PL with reader/writer locks:\n each variable has two locks: one for reading, one for writing before any operation on a variable, the transaction must acquire the appropriate lock. multiple transaction can hold reader locks for the same variable at once; a transaction can only hold a writer lock for a variable if there are no other locks held for that variable. after a transaction releases a lock, it may not acquire any other lock. Distributed Transactions When it comes to the distributed systems, the transactions are different.\nMultisite Atomicity via 2PC In this section, we use Two-Phase Commit (2PC) to get multisite atomicity, in the face of failures.\nTwo-Phase Commit (2PC) is a distributed transaction protocol to ensure the consistency of transactions across multiple nodes. 2PC consists of 2 phases:\n Prepare Phase: Coordinator uses Prepare message to check if participants are ready to finish this transaction. Commit Phase: Coordinator sends a Commit request to participants, waits for their OK response, and informs the client of the committed transaction. sequenceDiagram\rtitle: Figure 2. Two-Phase Commit (no failure)\rparticipant CL as Client\rparticipant CO as Coordinator\rparticipant AM as A-M Server\rparticipant NZ as N-Z Server\rCL-\u0026gt;\u0026gt;CO: Commit Request\rCO-\u0026gt;\u0026gt;AM: Prepare\rAM--\u0026gt;\u0026gt;CO: CO-\u0026gt;\u0026gt;NZ: Prepare\rNZ--\u0026gt;\u0026gt;CO: CO--\u0026gt;\u0026gt;CL: OK\rCO-\u0026gt;\u0026gt;AM: Commit\rAM--\u0026gt;\u0026gt;CO: CO-\u0026gt;\u0026gt;NZ: Commit\rNZ--\u0026gt;\u0026gt;CO: CO--\u0026gt;\u0026gt;CL: OK\rHowever, 3 types of failures may happen:\n Message Loss(at any stage) or Message Reordering: solved by reliable transport protocol, such as TCP (with sequence number and ACKs).\n Failures before commit point that can be aborted:\n Worker Failure BEFORE Prepare Phase: coordinator can saftly abort the transaction without additional communication to workers. (coordinator uses HELLO to detect failure of workers) sequenceDiagram\rtitle: Figure 3. Worker Failure BEFORE Prepare Phase\rparticipant CL as Client\rparticipant CO as Coordinator\rparticipant A-M Server\rparticipant N-Z Server\rCL-\u0026gt;\u0026gt;CO: Commit Request\rCO--\u0026gt;\u0026gt;CL: Abort\r Worker Failure or Coordinator Failure DURING Prepare Phase: coordinator can saftly abort the transaction, will send explicit abort message to live workers. sequenceDiagram\rtitle: Figure 4. Worker Fails DURING Prepare Phase\rparticipant CL as Client\rparticipant CO as Coordinator\rparticipant AM as A-M Server\rparticipant NZ as N-Z Server\rCL-\u0026gt;\u0026gt;CO: Commit Request\rCO-\u0026gt;\u0026gt;AM: Prepare\rAM--\u0026gt;\u0026gt;CO: CO-\u0026gt;\u0026gt;NZ: Prepare\rNote over NZ: worker fails\rCO-\u0026gt;\u0026gt;AM: Abort\rAM--\u0026gt;\u0026gt;CO: CO--\u0026gt;\u0026gt;CL: Abort\rsequenceDiagram\rtitle: Figure 5. Coordinator Fails DURING Prepare Phase\rparticipant CL as Client\rparticipant CO as Coordinator\rparticipant AM as A-M Server\rparticipant NZ as N-Z Server\rCL-\u0026gt;\u0026gt;CO: Commit Request\rCO-\u0026gt;\u0026gt;AM: Prepare\rAM--\u0026gt;\u0026gt;CO: Note over CO: coordinator fails and recovers\rCO-\u0026gt;\u0026gt;AM: Abort\rAM--\u0026gt;\u0026gt;CO: CO-\u0026gt;\u0026gt;NZ: Abort\rNZ--\u0026gt;\u0026gt;CO: CO--\u0026gt;\u0026gt;CL: Abort\rWorker Failure or Coordinator Failure during Commit Phase (after commit point): coordinator cannot abort the transaction; machines must commit the transaction during recovery. sequenceDiagram\rtitle: Figure 6. Worker Fails during Commit Phase\rparticipant CL as Client\rparticipant CO as Coordinator\rparticipant AM as A-M Server\rparticipant NZ as N-Z Server\rCL-\u0026gt;\u0026gt;CO: Commit Request\rCO-\u0026gt;\u0026gt;AM: Prepare\rAM--\u0026gt;\u0026gt;CO: CO-\u0026gt;\u0026gt;NZ: Prepare\rNZ--\u0026gt;\u0026gt;CO: CO--\u0026gt;\u0026gt;CL: OK\rCO-\u0026gt;\u0026gt;AM: Commit\rAM--\u0026gt;\u0026gt;CO: CO-\u0026gt;\u0026gt;NZ: Commit\rNote over NZ: worker fails and recovers\rNZ--\u0026gt;\u0026gt;CO: should I commit?\rCO-\u0026gt;\u0026gt;NZ: Commit\rNZ--\u0026gt;\u0026gt;CO: CO--\u0026gt;\u0026gt;CL: OK\rsequenceDiagram\rtitle: Figure 7. Coordinator Fails during Commit Phase\rparticipant CL as Client\rparticipant CO as Coordinator\rparticipant AM as A-M Server\rparticipant NZ as N-Z Server\rCL-\u0026gt;\u0026gt;CO: Commit Request\rCO-\u0026gt;\u0026gt;AM: Prepare\rAM--\u0026gt;\u0026gt;CO: CO-\u0026gt;\u0026gt;NZ: Prepare\rNZ--\u0026gt;\u0026gt;CO: CO--\u0026gt;\u0026gt;CL: OK\rCO-\u0026gt;\u0026gt;AM: Commit\rAM--\u0026gt;\u0026gt;CO: Note over CO: coordinator fails and recovers\rCO-\u0026gt;\u0026gt;AM: Commit\rAM--\u0026gt;\u0026gt;CO: CO-\u0026gt;\u0026gt;NZ: Commit\rNZ--\u0026gt;\u0026gt;CO: CO--\u0026gt;\u0026gt;CL: OK\rReplicate State Machines In this section, we replicate on multiple machines, so that the availability is increased.\nReplicate State Machines (RSM) use primary/backup mechanism for replication:\n Coordinators make requests to View Server, to find out which replica is primary, and contact the primary. View Server ensures that only one replica acts as primary, and can recruit new backups if servers fail. It keeps a table that maintains a sequence of views, and receives pings from primary and backups. Primary pings View Server, and gets contacts from coordinator, and then sends updates to backups. Primary must get an ACK from its backups before completing the update. Backups ping View Server, and receive update requests from primary. (Note: Backups will reject any requests that they get directly from Coordinator) ","link":"https://mighten.github.io/2023/06/mit-6.033-cse-distributed-systems/","section":"post","tags":["System Design"],"title":"MIT 6.033 CSE Distributed Systems"},{"body":"MIT 6.033 (Computer System Engineering) covers 4 parts: Operating Systems, Networking, Distributed Systems, and Security.\nThis is the course note for Part II: Networking. And in this section, we mainly focus on: how the Internet is designed to scale and its various applications.\nNetwork Topology A network is a graph of many nodes: endpoints and switches. Endpoints are physical devices that connect to and exchange information with network. Switches deal with many incoming and outgoing connections on links, and help forward data to destinations that are far away.\n On the network, we have to solve various difficult problems, such as addressing, routing, and transport. For each node, it has a name and thus is addressable by the routing protocol. And between any two reachable nodes, they exchange packets, each of which is some data with a header (information for packet delivery, especially the source and destination). Switches have queues in case more packets arrive than it can handle. If the queue is full when a new packet arrives, the packet is to be dropped.\nTo mitigate complexity, A layered model called TCP/IP Model was presented, with 4 layers:\n Application Layer: acutal traffic generation Transport Layer: sharing the network, efficiency, reliability Network Layer: naming, addressing, routing Link Layer: communicates between two directly-connected nodes. Not every node in the network has the whole four layers. Some nodes in the network, such as our laptops, have full 4 layers; while others like routers, only have Link Layer and Network Layer.\nRouting Firstly, we need to distinguish two concepts: path and route.\n Path: the full path the packets will travel Route: only the first hop of that path So, routing means that, in the Network Layer, for every node, its routing table should contain a minimum-cost route to every other reachable node after running routing protocol.\n Differentiate between route and path: Once a routing table is set up, when a switch gets a packet, it can check the packet header for the destination address, and add the packet to the queue for that outgoing link. Routing protocols can be divided into two categories: distributed routing protocols and the centralized routing protocols. And distributed routing protocols scale better than the centralized ones. There are two types of distributed routing protocols for an IP network:\n Link-State (LS) Routing, like OSPF, forwards link costs to neighbors via advertisement, and uses Dijkstra algorithm to calculate the full shortest path. (Fast convergence, but high overhead due to flooding. Good for middle-sized network, but not scale up to the Internet) Distance-Vector (DV) Routing, like RIP, it only advertises to the nodes that each node knows about. (Low overhead, but convergence time is proportional to longest path. Good for small networks, but not scale up to the Internet.) Scale and Policy In this section, we talk about a routing protocol that can scale up to the Internet with policy routing: Border Gateway Protocol (BGP) .\nFirst thing we need to do is scale. The whole Internet is divided into several autonomous systems (AS), e.g., a university, an ISP, etc. To route across the Internet, the scalable routing is introduced, with 3 types:\n hierarchy of routing: first between ASes, then within AS. path-vector routing: like BGP, advertise the path to better detect loop. topological addressing: CIDR, to make advertisement smaller. Next thing we need to do is policy. We use export policies and import policies to reflect two common autonomous-system relationships:\n Transit: customer pays provider Peer: two ASes agree to share routing tables at no cost. The export policies decide which routes to advertise, and to whom:\n A provider wants its customers to send and receive as much traffic through the provider as possible Peers only tell each other about their customers (A peer does not tell each other about its own providers; because it will lose money providing that transit) Note: there is a path from AS7 to AS1, but this policy just does not present it to us. To fix this issue in the real world, we make all top-tier(tier-1) ISPs peer, to provide global connectivity:\n The import policies decide which route to use. If the AS hears about multiple routes to a destination, it will prefer to use: first its customers, then peers, then providers.\nAnd finally, let's talk about BGP. BGP works at the Application Layer, and it runs on top of a reliable transport protocol called TCP (Transport Layer). BGP doesn’t have to do periodic advertisements to handle failure, instead, it pushs advertisements to neighbors when routes change.\nFailures: Routes can be explicitly withdrawn in BGP when they fail. Routing loops avoided because BGP is path-vector.\nDoes the BGP scale? Yes, but the following 4 factors will cause scaling issues: the size of routing table, route instability, multihoming, iBGP(internal BGP).\nIs BGP secure? No, BGP basically relies on the honor system. And also, BGP relies on human, meaning network outages may happen due to human errors.\nReliable Transport In this section, we talk about how to do reliable transport while keeping things efficient and fair.\nFirst, the reliable transport protocol is a protocol that delivers each byte of data exactly once, in-order, to the receiving application. And we use the sliding-window protocol to guarantee reliability.\n Sender uses sequence numbers to order and send the packets. There are main two steps on how it works. Receiver replies acknowledgment(ACK) to sender if a packet is received successfully. Otherwise, a timeout is to be detected, the sender then retransmits the corresponding packet. Now that a packet will be delivered reliably, next we need to do congestion control.\n Our goal for network is efficiency and fairness. Considering both A and B are sending data to R1, and R1 is forwarding to R2, so the bottleneck link is the link between R1 and R2. When the bottleneck link is \u0026quot;full\u0026quot;, we call the network is fully utilized (efficient). When A and B are sending at the same rate, we call the network is fair.\n The red line(A + B = bandwidth) is the efficiency line, and the blue line(A = B) is the fairness line. Initially, the dot is below the red line, meaning network is underutilized. And eventually, A and B will come to oscillate around the fixed point, shown as purple point, which means the network is both efficient and fair.\nWe use slow-start, AIMD (Additive Increase Multiplicative Decrease), and fast retransmit/fast recovery algorithms to dynamically adjust the window size to deal with congestion. At the start of the connection, slow-start algorithm will double the windows size on every RTT. Upon reaching the threshold, the AIDM algorithm will increase the congestion window (cwnd) by one segment per RTT, and decrease cwnd by half upon detecting timeout. However, if a single packet is lost, fast retransmit/fast recovery algorithm will send three duplicate ACKs to the receiver before RTO expires.\nIn-network Resource Management In this section, we talk about how to react to congestion before it happens.\nQueues are transient (not persistent) buffers and are used to absorb packet bursts. If the queues were to be full, the network delay would have been very long. So, TCP senders need to drop packets before the queues are full.\n Application Layer In this section, we talk about how to deliver content on the Internet.\nThere are three models on how we sharing a file (deliver content) on the Internet: Client-Server, CDN(Content Distribution Network), and P2P(Peer to Peer).\n Client-Server: if client request a file, the server will just respond with the file content. (simple, but, single-node failure and not scalable) CDN: to prevent single-node failure, we add more servers that are linked with persistent TCP, and thus every time a client requests, the DNS dynamically choose the nearest CDN server to respond. (requires coordination among the edge servers) P2P: to improve scalability, a client will discover peers and exchange blocks of data. (scalability is limited by end-users' upload constraints) ","link":"https://mighten.github.io/2023/05/mit-6.033-cse-networking/","section":"post","tags":["System Design"],"title":"MIT 6.033 CSE Networking"},{"body":"MIT 6.033 (Computer System Engineering) covers 4 parts: Operating Systems, Networking, Distributed Systems, and Security.\nThis is the course note for Part I: Operating Systems. And in this section, we mainly focus on:\n How common design patterns in computer system — such as abstraction and modularity — are used to limit complexity. How operating systems use virtualization and abstraction to enforce modularity. Complexity In this section, we talk about what is complexity in computer systems, and how to mitigate it.\nA system is a set of interconnected components that has an expected behavior observed at the interface with its environment.\nSo we say that a system has complexity, which limits what we can build. However, complexity can be mitigated with design patterns, such as modularity and abstration.\nNowadays, we usually enforce modularity by Client/Server Model, or C/S Model, where two modules reside on different machines and communicate with RPCs.\nNaming Schemes In this section, we talk about naming, which allows modules to communicate.\nNaming is that a name can be resolved to the entity it refers to. Therefore, it allows modules to interact, and can help to achieve goals such as indirection, user-friendliness, etc.\nThe design of a naming scheme has 3 parts: name, value, and look-up algorithm.\nOne great case of naming scheme is Domain Name System (DNS), which illustrates principles such as hierarchy, scalability, delegation and decentralization. Especially, the hierarchical design of DNS let us scale up to the Internet.\nVirtual Memory Virtual Memory is a primary technique that uses Memory Management Unit (MMU) to translate virtual address into physical address by using page tables.\nTo enforce modularity, the operating system(OS) kernel checks the following 3 bits:\n Name Description User/Supervisor (U/S) bit if the program allowed to access the address Present (P) bit if the page currently in memory User/Kernel (U/K) bit whether the operation is in user mode or kernel mode These 3 bits let the OS know when to trigger page faults, and if the access triggers an exception, the OS kernel will first switch to kernel mode and then execute the corresponding exception handler before switching back to user mode.\nTo deal with performance issues, the Operating Systems introduce two mechanisms: hierarchical page table and cache. The hierarchical(multilevel) page table reduces the memory overhead associated with the page table, at the expense of more table look-ups. And cache, also known as Translation Lookaside Buffer (TLB), stores recent translations of virtual memory to physical addresses to enable faster retrieval.\nOS enforces modularity by virtualization and abstraction. On resources that can be virtualized, such as memory, OS uses virtualization. And for those components that are difficult to virtualize such as disk and network, OS presents abstration.\nBounded Buffer with Lock Let's virtualize communication links - the bouded buffers.\nBut first, we need Lock, which is a protecting mechanism that allows only one CPU to execute a piece of code at a time to implement atomic actions. If two CPUs try to acquire the same lock at the same time, only one of them will succeed and the other will block until the first CPU releases the lock.\nImplementing locks is possible by the support of a special hardware called controller that manages access to memory.\n1acquire(lock): 2 do: 3 r = 1 4 XCHG r, lock 5 while r == 1 6 7release(lock): 8 lock = 0 A bounded buffer is a buffer that has (up to) N slots and allows concurrent programs to send/receive messages.\nA bounded buffer with lock may deal with race condition, therefore, we need to decide where to put locks:\n coarse-grained locking is easy to maintain correctness, but it will lead to bad performance; fine-grained locking improves performance, but it may cause inconsistent state; multiple locking requires that locks are acquired in the same order, otherwise the dead lock may happen. In addition, bounded buffer with lock is yet another example of virtualization, which means any of senders/receivers think it has full access to the whole buffer.\nConcurrent Threads Let's virtualize processors - the threads.\nThread Thread is a virtual processor and has 3 states:\n RUNNING (actively running) RUNNABLE (ready to go, but not running) WAITING (waiting for a particular event) To change the states of a thread, we often use 2 APIs:\n suspend(): save state of current thread to memory. resume(): restore state from memory. In reality, most threads spend most of the time waiting for events to occur. So we use yield() to let the current thread voluntarily suspend itself, and then let the kernel choose a new thread to resume execution.\nIn particular, we maintain a processor table and a thread table.\n The processor table (cpus) keeps track of which processor is currently running which thread; The thread table (threads) keeps track of thread states. 1yield_(): 2 acquire(t_lock) 3 # 1. Suspend the running thread 4 id = cpus[CPU].thread # thread #id is on #CPU 5 threads[id].state = RUNNABLE 6 threads[id].sp = SP # stack pointer 7 threads[id].ptr = PTR # page table register 8 9 # 2. Choose the new thread to run 10 do: 11 id = (id + 1) mod N 12 while threads[id].state != RUNNABLE 13 14 # 3. Resume the new thread 15 SP = threads[id].sp 16 PTR = threads[id].ptr 17 threads[id].state = RUNNING 18 cpus[CPU].thread = id 19 20 release(t_lock) 21 22# send a `message` into `bb`(N-slot buffer) 23send(bb, message ): 24 acquire(bb.lock) 25 # when the buffer is full 26 while bb.in_num - bb.out_num \u0026gt;= N: 27 release(bb.lock) 28 yield_() 29 acquire(bb.lock) 30 bb.buf[bb.in_num % N] \u0026lt;- message 31 bb.in_num += 1 32 release(bb.lock) 33 34# reveive a message from bb 35receive(bb): 36 acquire(bb.lock) 37 # while the buffer is empty 38 while bb.out_num \u0026gt;= bb.in_num: 39 release(bb.lock) 40 yield_() 41 acquire(bb.lock) 42 message \u0026lt;- bb.buf[bb.out_num % N] 43 bb.out_num += 1 44 release(bb.lock) 45 return message However, the sender may get resumed in the meantime, even if there is no room in buffer. One solution to fix that is to use condition variables\nCondition Variable Condition variable is simply a synchronization primitive that allow kernel to notify threads instead of having threads constantly make checks. And it has 2 APIs:\n wait(cv): yield processor and wait to be notified of cv, a condition variable. notify(cv): notify threads that are waiting for cv. However, condition variables without lock may cause \u0026quot;Lost notify\u0026quot; problem:\n1# send a `message` into `bb`(N-slot buffer) 2send(bb, message ): 3 acquire(bb.lock) 4 # while the buffer is full 5 while bb.in_num - bb.out_num \u0026gt;= N: 6 release(bb.lock) 7 wait(bb.has_space) ### ! 8 acquire(bb.lock) 9 bb.buf[bb.in_num % N] \u0026lt;- message 10 bb.in_num += 1 11 release(bb.lock) 12 notify(bb.has_message) 13 return 14 15# reveive a message from bb 16receive(bb): 17 acquire(bb.lock) 18 # while the buffer is empty 19 while bb.out_num \u0026gt;= bb.in_num: 20 release(bb.lock) 21 wait(bb.has_message) 22 acquire(bb.lock) 23 message \u0026lt;- bb.buf[bb.out_num % N] 24 bb.out_num += 1 25 release(bb.lock) 26 notify(bb.has_space) ### ! 27 return message Considering there are two threads: T1(sender), and T2(receiver).\n T1 acquires bb.lock on buffer, finding it full, so T1 releases bb.lock Prior to T1 calling wait(bb.has_space), T2 just acquires bb.lock to read messages, notifying the T1 that the buffer now has space(s). but T1 is actually not yet waiting for bb.has_space (Bacause T1 was interrupted by OS before it could call wait(bb.has_space)). So, as you can see, it cause the \u0026quot;lost notify\u0026quot; problem. And the solution to fix that is use a lock.\n wait(cv, lock): yield processor, release lock, wait to be notified of cv notify(cv): notify waiting threads of cv 1yield_wait(): 2 id = cpus[CPU].thread 3 threads[id].sp = SP 4 threads[id].ptr = PTR 5 SP = cpus[CPU].stack # avoid stack corruption 6 7 do: 8 id = (id + 1) mod N 9 release(t_lock) # ! 10 acquire(t_lock) # ! 11 while threads[id].state != RUNNABLE 12 13 SP = threads[id].sp 14 PTR = threads[id].ptr 15 threads[id].state = RUNNING 16 cpus[CPU].thread = id 17 18 19wait(cv, lock): 20 acquire(t_lock) 21 release(lock) # let others access what `lock` protects 22 # mark the current thread: wait for `cv` 23 id = cpus[CPU].thread 24 threads[id].cv = cv 25 threads[id].state = WAITING 26 27 # different from `yield_()` mentioned above! 28 yield_wait() 29 30 release(t_lock) 31 acquire(lock) # disallow others to access what `lock` protects 32 33 34notify(cv): 35 acquire(t_lock) 36 # Find all threads waiting for `cv`, 37 # and change states: WAITING -\u0026gt; RUNNABLE 38 for id = 0 to N-1: 39 if threads[id].cv == cv \u0026amp;\u0026amp; 40 threads[id].state == WAITING: 41 threads[id].state = RUNNABLE 42 release(t_lock) 43 44# send `message` into N-slot buffer `bb` 45send(bb, message): 46 acquire(bb.lock) 47 while bb.in_num - bb.out_num \u0026gt;= N: 48 wait(bb.has_space, bb.lock) 49 bb.buf[bb.in_num % N] \u0026lt;- message 50 bb.in_num += 1 51 release(bb.lock) 52 notify(bb.has_message) 53 return 54 55# reveive a message from bb 56receive(bb): 57 acquire(bb.lock) 58 # while the buffer is empty 59 while bb.out_num \u0026gt;= bb.in_num: 60 wait(bb.has_message, bb.lock) 61 message \u0026lt;- bb.buf[bb.out_num % N] 62 bb.out_num += 1 63 release(bb.lock) 64 notify(bb.has_space) 65 return message Note:\n Why yield_wait(), rather than yield_()? Because yield_() will cause Deadlock. At the beginning of wait(cv, lock), we acquire and hold t_lock. So if we invoke yield_(), it will try to acquire t_lock again, causing deadlock problem. Why yield_wait() releases and then immediately acquires t_lock? Because it guarantee other threads can access the buffer. Considering there are 5 senders writing into buffer and only 1 receiver reading the buffer. If all 5 senders find the buffer full, it is important to release t_lock to let the only 1 receiver acquire the t_lock and read the buffer. Why do we need to SP = cpus[CPU].stack? To avoid stack corruption when this thread is scheduled to a different CPU. And the new problem arises, what if the thread never yield CPU? Use preemption.\nPreemption Preemption forcibly interrupts a thread so that we don’t have to rely on programmers correctly using yield(). In this case, if a thread never calls yield() or wait(), it’s okay; special hardware will periodically generate an interrupt and forcibly call yield().\nBut what if this interrupt occurs while running yield() or yield_wait(): Deadlock. And the solution is to require hardware mechanism to disable interrupts.\nKernel The kernel is a non-interruptible, trusted program that runs system code.\nKernel errors are fatal, so we try to limit the size of kernel code. There are two models for kernels.\n The monolithic kernel implements most of the OS in the kernel, and everything sharing The microkernel implements different features as client-servers. They enforce modularity by putting subsystems in user programs. Virtual Machine Virtual Machine (VM) allows us to run multiple isolated operating systems on a single physical machine. VMs must handle the challenges of virtualizing the hardware.\n The Virtual Machine Monitor (VMM) deals with privileged instructions, allocates resources, and dispatches events.\nThe guest OS runs in user mode. Privileged instructions throw exceptions, and VMM will trap and emulate. In modern hardware, the physical hardware knows of both page tables, and it directly translates from guest virtual address to host physical address.\nHowever, there are still some cases in which we cannot trap exceptions. There are several solutions:\n Para-virtualization is where the guest OS changes a bit, which defeats the purpose of a VM Binary translation is also a method (VMWare used to use this), but it is slightly messy Hardware support for virtualization means that hardware has VMM capabilities built-in. The guest OS can directly manipulate page tables, etc. Most VMMs today have hardware support. Performance There are 3 metrics to measure performance:\n latency: how long does it take to complete a single task? Throughput: the rate of useful work, or how many requests per unit of time. Utilization: what fraction of resources are being utilized ","link":"https://mighten.github.io/2023/04/mit-6.033-cse-operating-system/","section":"post","tags":["System Design"],"title":"MIT 6.033 CSE Operating System"},{"body":"","link":"https://mighten.github.io/tags/algorithm/","section":"tags","tags":null,"title":"Algorithm"},{"body":"","link":"https://mighten.github.io/series/algorithms/","section":"series","tags":null,"title":"Algorithms"},{"body":"Today, let's talk about Linked List algorithms that are frequently used.\nA Linked List is a data structure that stores data into a series of connected nodes, and thus it can be dynamically allocated. For each node, it contains 2 fields: the val that stores data, and the next that points to the next node.\nIn LeetCode, the Linked List is often defined below, using C++:\n1struct ListNode { 2 int val; 3 ListNode *next; 4}; The content of this blog is shown below:\nmindmap\rroot)Linked List(\rA1(Node Removal)\rA2(Inplace Reversal)\rA3(Merge)\rA4(Insertion Sort)\rA5(Two Pointer)\rNode Removal LeetCode 203: Remove Linked List Elements\nGiven the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.\n1ListNode* removeElements(ListNode* head, int val){ 2 ListNode newHead; 3 ListNode *pre = \u0026amp;newHead; 4 newHead.next = head; 5 6 while (pre-\u0026gt;next != nullptr ) { 7 ListNode *cur = pre-\u0026gt;next; 8 if (cur-\u0026gt;val == val ) { 9 pre-\u0026gt;next = cur-\u0026gt;next; 10 delete cur; 11 }else 12 pre = pre-\u0026gt;next; 13 } 14 return newHead.next; 15} In-place Reversal LeetCode 206. Reverse Linked List\nGiven the head of a singly linked list, reverse the list, and return the reversed list.\n1ListNode* reverseList(ListNode* head) { 2 ListNode *pre = nullptr, *cur = head; 3 while (cur != nullptr ) { 4 ListNode *next = cur-\u0026gt;next; 5 cur-\u0026gt;next = pre; 6 pre = cur, cur = next; 7 } 8 return pre; 9} Merge LeetCode 21. Merge Two Sorted Lists\nYou are given the heads of two sorted linked lists list1 and list2.\nMerge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.\nReturn the head of the merged linked list.\n1ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { 2 ListNode head; 3 ListNode *pre = \u0026amp;head; 4 5 while (list1 != nullptr \u0026amp;\u0026amp; list2 != nullptr ) { 6 if (list1-\u0026gt;val \u0026lt; list2-\u0026gt;val ) { 7 pre-\u0026gt;next = list1; 8 list1 = list1-\u0026gt;next; 9 } else { 10 pre-\u0026gt;next = list2; 11 list2 = list2-\u0026gt;next; 12 } 13 pre = pre-\u0026gt;next; 14 } 15 16 while (list1 != nullptr ) { 17 pre-\u0026gt;next = list1; 18 pre = pre-\u0026gt;next; 19 list1 = list1-\u0026gt;next; 20 } 21 22 while (list2 != nullptr ) { 23 pre-\u0026gt;next = list2; 24 pre = pre-\u0026gt;next; 25 list2 = list2-\u0026gt;next; 26 } 27 pre-\u0026gt;next = nullptr; 28 return head.next; 29} Insertion Sort LeetCode 147. Insertion Sort List\nGiven the head of a linked list, return the list after sorting it in ascending order.\nGiven the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.\nThe steps of the insertion sort algorithm:\n Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. It repeats until no input elements remain. 1ListNode* insertionSortList(ListNode* head) { 2 if (head == nullptr) return head; 3 ListNode tmpHead; 4 ListNode *cur = head, *pre = \u0026amp;tmpHead; 5 6 while (cur != nullptr) { 7 while (pre-\u0026gt;next != nullptr \u0026amp;\u0026amp; pre-\u0026gt;next-\u0026gt;val \u0026lt; cur-\u0026gt;val) 8 pre = pre-\u0026gt;next; 9 10 ListNode* next = cur-\u0026gt;next; 11 cur-\u0026gt;next = pre-\u0026gt;next; 12 pre-\u0026gt;next = cur; 13 pre = \u0026amp;tmpHead; 14 cur = next; 15 } 16 return tmpHead.next; 17} Two Pointer We often use fast and slow to solve Linked List problems in $O(n)$-time complexity.\nMiddle Node LeetCode 876. Middle of the Linked List\nGiven the head of a singly linked list, return the middle node of the linked list.\nIf there are two middle nodes, return the second middle node.\n1ListNode* middleNode(ListNode* head) { 2 ListNode *fast = head, *slow = head; 3 while (fast != nullptr \u0026amp;\u0026amp; fast-\u0026gt;next != nullptr) { 4 fast = fast-\u0026gt;next-\u0026gt;next; 5 slow = slow-\u0026gt;next; 6 } 7 return slow; 8} Cycle Detection LeetCode 142. Linked List Cycle II\nGiven the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.\nDo not modify the linked list.\n1ListNode *detectCycle(ListNode *head) { 2 ListNode *fast = head, *slow = head; 3 4 // Judge if cycle exists 5 while ( true ) { 6 if (fast == nullptr || fast-\u0026gt;next == nullptr ) 7 return nullptr; 8 fast = fast-\u0026gt;next-\u0026gt;next; 9 slow = slow-\u0026gt;next; 10 if (fast == slow) break; // Cycle detect 11 } 12 13 // yes there is a cycle, and find the entry of cycle 14 ListNode *ptr = head; 15 while (ptr != slow ) { 16 ptr = ptr-\u0026gt;next; 17 slow = slow-\u0026gt;next; 18 } 19 return ptr; 20} ","link":"https://mighten.github.io/2023/04/linked-list/","section":"post","tags":["Algorithm"],"title":"Linked List"},{"body":"Hi there, todaly let's talk about Servlet in a nutshell.\nA Servlet is a Java programming language class, which is executed in Web Server and responsible for dynamic content generation in a portable way.\nServlet extends the capabilities of servers that host applications accessed by means of a request-response programming model.\nThis blog talks about several topics, shown below:\nmindmap\rroot(Servlet)\rLife Cycle\rConfiguration\rRequest and Response\rCookies and Sessions\rEvent Listener and Filter\rBut first, let's talk about the hierarchy of Servlet:\nThe javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets.\njavax.servlet is a generic interface, and the javax.servlet.http.HttpServlet is an extension of that interface – adding HTTP specific support – such as doGet and doPost.\nWhen it comes to writing a Servlet, we usually choose to extend HttpServlet and override doGet and doPost.\nLife Cycle The web container maintains the life cycle of a servlet instance:\n Load\nwhen the first request is received, Web Container loads the servlet class and initialize an instance\n Initialize\nThe web container then creates one single servlet instance, to handle all incoming requests on that servlet, even there are concurrent requests.\n init()\nThe web container calls the init() method only once after creating the servlet instance, to initialize the servlet.\n service()\nFor every request, servlet creates a separate thread to execute service()\n destoy()\nThe web container asks servlet to release all the resources associated with it, before removing the servlet instance from the service.\n A typical Servlet demo:\nsnippet of web.xml:\n1\u0026lt;?xml version=\u0026#34;1.0\u0026#34; encoding=\u0026#34;UTF-8\u0026#34;?\u0026gt; 2\u0026lt;web-app xmlns:xsi=\u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 3 xmlns=\u0026#34;http://java.sun.com/xml/ns/javaee\u0026#34; 4 xsi:schemaLocation=\u0026#34;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\u0026#34; 5 id=\u0026#34;WebApp_ID\u0026#34; version=\u0026#34;3.0\u0026#34;\u0026gt; 6 7 \u0026lt;servlet\u0026gt; 8 \u0026lt;servlet-name\u0026gt;ServletLifecycle\u0026lt;/servlet-name\u0026gt; 9 \u0026lt;servlet-class\u0026gt;ServletLifecycleExample\u0026lt;/servlet-class\u0026gt; 10 \u0026lt;/servlet\u0026gt; 11 12 \u0026lt;servlet-mapping\u0026gt; 13 \u0026lt;servlet-name\u0026gt;ServletLifecycle\u0026lt;/servlet-name\u0026gt; 14 \u0026lt;url-pattern\u0026gt;/\u0026lt;/url-pattern\u0026gt; 15 \u0026lt;/servlet-mapping\u0026gt; 16\u0026lt;/web-app\u0026gt; snippet of index.jsp:\n1\u0026lt;%@ page language=\u0026#34;java\u0026#34; 2 contentType=\u0026#34;text/html; charset=ISO-8859-1\u0026#34; 3 pageEncoding=\u0026#34;ISO-8859-1\u0026#34;%\u0026gt; 4\u0026lt;!DOCTYPE html PUBLIC \u0026#34;-//W3C//DTD HTML 4.01 Transitional//EN\u0026#34; \u0026#34;http://www.w3.org/TR/html4/loose.dtd\u0026#34;\u0026gt; 5\u0026lt;html\u0026gt; 6\u0026lt;head\u0026gt; 7 \u0026lt;title\u0026gt;Servlet Lifecycle Example\u0026lt;/title\u0026gt; 8\u0026lt;/head\u0026gt; 9\u0026lt;body\u0026gt; 10 \u0026lt;form action=\u0026#34;ServletLifecycle\u0026#34; method=\u0026#34;post\u0026#34;\u0026gt; 11 \u0026lt;input type=\u0026#34;submit\u0026#34; value=\u0026#34;Make request\u0026#34; /\u0026gt; 12 \u0026lt;/form\u0026gt; 13\u0026lt;/body\u0026gt; 14\u0026lt;/html\u0026gt; snippet of ServletLifecycleExample.java:\n1import java.io.IOException; 2import java.io.PrintWriter; 3 4import javax.servlet.GenericServlet; 5import javax.servlet.ServletException; 6import javax.servlet.ServletRequest; 7import javax.servlet.ServletResponse; 8 9public class ServletLifecycleExample extends GenericServlet { 10 11 @Override 12 public void init() { 13 System.out.println(\u0026#34;Servlet Initialized!\u0026#34;); 14 } 15 16 @Override 17 public void service(ServletRequest request, ServletResponse response) 18 throws ServletException, IOException { 19 response.setContentType(\u0026#34;text/html\u0026#34;); 20 PrintWriter out = response.getWriter(); 21 out.println(\u0026#34;Servlet called from jsp page!\u0026#34;); 22 } 23 24 @Override 25 public void destroy() { 26 } 27} Servlet life time shown in the sequence chart below:\nsequenceDiagram\rparticipant Browser\rparticipant Server\rparticipant Servlet\rautonumber\rBrowser-\u0026gt;\u0026gt;Server: Connect to the server\rBrowser-\u0026gt;\u0026gt;Server: HTTP GET\rServer-\u0026gt;\u0026gt;Server: Resolve\rServer-\u0026gt;\u0026gt;Servlet: Load Servlet and create obj for first access\rServer-\u0026gt;\u0026gt;Servlet: invoke `init()`\rServer-\u0026gt;\u0026gt;Servlet: invoke `service()`\rServlet-\u0026gt;\u0026gt;Servlet: Execute `service()` and generate Response\rServlet--\u0026gt;\u0026gt;Server: Response\rServer--\u0026gt;\u0026gt;Browser: Response\rConfiguration Tomcat Tomcat is a servlet container, which is a runtime shell that manages and invokes servlets on behalf of users.\nTomcat has the following directory structure:\n Directory Description bin startup/shutdown... scripts conf configuration files including server.xml (Tomcat's global configuration file) and web.xml(sets the default values for web applications deployed in Tomcat) doc documents regarding Tomcat lib various jar files that are used by Tomcat logs log files src servlet APIs source files, and these are only the empty interfaces and abstract classes that should be implemented by any servlet container webapps sample web applications work intermediate files, automatically generated by Tomcat classes to add additional classes to Tomcat's classpath Note:\n The single most important directory is webapps, where we can manually add our Servlet into it, e.g., if we want to create a servlet named HelloServlet, the first thing we do is to create the directory /webapps/HelloServlet.\n The default port for Tomcat is 8080, and if we want to switch the port to 80, we just need to modify /conf/server.xml:\n1 \u0026lt;Connector port=\u0026#34;80\u0026#34; protocol=\u0026#34;HTTP/1.1\u0026#34; 2 connectionTimeout=\u0026#34;20000\u0026#34; 3 redirectPort=\u0026#34;8443\u0026#34; /\u0026gt; web.xml To deploy servlets and map URLs to the servlets, we have to modify the web.xml file, a deployment descriptor, like this:\n1\u0026lt;web-app\u0026gt; 2\t\u0026lt;servlet\u0026gt; 3\t\u0026lt;servlet-name\u0026gt;servletName\u0026lt;/servlet-name\u0026gt; 4\t\u0026lt;servlet-class\u0026gt;servletClass\u0026lt;/servlet-class\u0026gt; 5\t\u0026lt;/servlet\u0026gt; 6\t\u0026lt;servlet-mapping\u0026gt; 7\t\u0026lt;servlet-name\u0026gt;servletName\u0026lt;/servlet-name\u0026gt; 8\t\u0026lt;url-pattern\u0026gt;*.*\u0026lt;/url-pattern\u0026gt; 9\t\u0026lt;/servlet-mapping\u0026gt; 10\u0026lt;/web-app\u0026gt; When a request comes, it is matched with URL pattern in servlet mapping attribute.\nWhen URL matched with URL pattern, Web Server try to find the servlet name in servlet attributes, same as in servlet mapping attribute.\nWhen match found, control goes to the associated servlet class.\nServletConfig ServletConfig, a servlet configuration object used by a servlet container to pass information to a servlet during initialization.\n\u0026lt;init-param\u0026gt; attribute is used to define a init parameter, which refers to the initialization parameters of a servlet or filter. \u0026lt;init-param\u0026gt; attribute has 2 main sub attributes: \u0026lt;param-name\u0026gt; and \u0026lt;param-value\u0026gt;. The \u0026lt;param-name\u0026gt; contains the name of the parameter and \u0026lt;param-value\u0026gt; contains the value of the parameter.\nExample:\nsnippet of web.xml:\n1\u0026lt;init-param\u0026gt; 2 \u0026lt;param-name\u0026gt;appUser\u0026lt;/param-name\u0026gt; 3 \u0026lt;param-value\u0026gt;jai\u0026lt;/param-value\u0026gt; 4\u0026lt;/init-param\u0026gt; snippet of InitParamExample.java:\n1ServletConfig config = getServletConfig(); 2String appUser = config.getInitParameter(\u0026#34;appUser\u0026#34;); This example shows how to read web.xml, and get init parameters \u0026quot;appUser\u0026quot;: \u0026quot;jai\u0026quot; for initialization.\nServletContext ServletContext defines a set of methods that a servlet will use to communicate with its servlet container, to share initial parameters or configuration information to the whole application.\n\u0026lt;context-param\u0026gt; attribute is used to define a context parameter, which refers to the initialization parameters for all servlets of an application. \u0026lt;context-param\u0026gt; attribute also has 2 main sub attributes: \u0026lt;param-name\u0026gt; and \u0026lt;param-value\u0026gt;. And also, the \u0026lt;param-name\u0026gt; contains the name of the parameter, the \u0026lt;param-value\u0026gt; contains the value of the parameter.\nExample:\nsnippet of web.xml:\n1\u0026lt;context-param\u0026gt; 2 \u0026lt;param-name\u0026gt;appUser\u0026lt;/param-name\u0026gt; 3 \u0026lt;param-value\u0026gt;jai\u0026lt;/param-value\u0026gt; 4\u0026lt;/context-param\u0026gt; snippet of ContextParamExample.java:\n1ServletContext context = this.getServletContext(); 2String value = (String) context.getAttribute(\u0026#34;appUser\u0026#34;); This example shows how to read web.xml, and get context parameters \u0026quot;appUser\u0026quot;: \u0026quot;jai\u0026quot; for communication.\nload-on-startup The load-on-startup is the sub attribute of servlet attribute in web.xml. It is used to control when the web server loads the servlet.\nAs we discussed that servlet is loaded at the time of first request. In this case, response time is increased for first request.\nIf load-on-startup is specified for a servlet in web.xml, then this servlet will be loaded when the server starts. So the response time will NOT increase for fist request.\nExample:\n1\u0026lt;servlet\u0026gt; 2 \u0026lt;servlet-name\u0026gt;servlet1\u0026lt;/servlet-name\u0026gt; 3 \u0026lt;servlet-class\u0026gt;com.w3spoint.business.Servlet1 \u0026lt;/servlet-class\u0026gt; 4 \u0026lt;load-on-startup\u0026gt;0\u0026lt;/load-on-startup\u0026gt; 5\u0026lt;/servlet\u0026gt; 6 7\u0026lt;servlet\u0026gt; 8 \u0026lt;servlet-name\u0026gt;servlet2\u0026lt;/servlet-name\u0026gt; 9 \u0026lt;servlet-class\u0026gt; com.w3spoint.business.Servlet2\u0026lt;/servlet-class\u0026gt; 10 \u0026lt;load-on-startup\u0026gt;1\u0026lt;/load-on-startup\u0026gt; 11\u0026lt;/servlet\u0026gt; 12 13\u0026lt;servlet\u0026gt; 14 \u0026lt;servlet-name\u0026gt;servlet3\u0026lt;/servlet-name\u0026gt; 15 \u0026lt;servlet-class\u0026gt; com.w3spoint.business.Servlet3\u0026lt;/servlet-class\u0026gt; 16 \u0026lt;load-on-startup\u0026gt;-1\u0026lt;/load-on-startup\u0026gt; 17\u0026lt;/servlet\u0026gt; In the example above, Servlet1 and Servlet2 will be loaded when server starts because non-negative value is passed in there load-on-startup. While Servlet3 will be loaded at the time of first request because negative value is passed in there load-on-startup.\nRequest and Response There is a method named service() in package javax.servlet, as is mentioned in the 'Life Cycle' section, it has a prototype like this:\n1void service(ServletRequest request, 2 ServletResponse response) 3 throws ServletException, 4 IOException where request is the ServletRequest object that contains the client's request, and response is the ServletResponse object that contains the servlet's response\nServletRequest ServletRequest defines an object to provide client request information to a servlet.\nThe servlet container creates a ServletRequest object and passes it as an argument to the servlet's service() method. A ServletRequest object provides data including parameter name and values, attributes, and an input stream.\nTo transfer data to other component, we can use getAttribute(), setAttribute() of ServletRequest, example code:\n1@WebServlet(name = \u0026#34;LoginServlet\u0026#34;, urlPatterns = {\u0026#34;/login.do\u0026#34;}) 2public class LoginServlet extends HttpServlet { 3 public void doPost(HttpServletRequest request, 4 HttpServletResponse response) 5 throws ServletException, IOException { 6 String username = request.getParameter(\u0026#34;username\u0026#34;); 7 String password = request.getParameter(\u0026#34;password\u0026#34;); 8 if (username.equals(\u0026#34;admin\u0026#34;) \u0026amp;\u0026amp; 9 password.equals(\u0026#34;5F4DCC3B5AA765D61D8327DEB882CF99\u0026#34;)) { 10 // Logged in 11 RequestDispatcher rd = 12 request.getRequestDispatcher(\u0026#34;/welcome.jsp\u0026#34;); 13 // to store `username` in request object 14 request.setAttribute(\u0026#34;user\u0026#34;, username); 15 rd.forward(request, response); 16 } else { 17 // Failed to log in 18 RequestDispatcher rd = 19 request.getRequestDispatcher(\u0026#34;/login.jsp\u0026#34;); 20 rd.forward(request, response); 21 } 22 23 } 24} HttpServletRequest HttpServletRequest interface adds the methods that relates to the HTTP protocol.\nclassDiagram\rclass ServletRequest {\r+getAttribute()\r+getParameter()\r}\rclass HttpServletRequest {\r+getMethod()\r+getSession()\r}\rServletRequest \u0026lt;|-- HttpServletRequest: extends\r(Note: could not display \u0026lt;\u0026lt;interface\u0026gt;\u0026gt; for both classes, due to error of Mermaid version 9.4.3 , maybe the Mermaid-js team will fix this issue later)\nThe servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service() methods (doGet(), doPost(), etc).\nDemo of HttpServletRequest:\nsnippet of index.html:\n1\u0026lt;form method=\u0026#34;post\u0026#34; action=\u0026#34;check\u0026#34;\u0026gt; 2 Name \u0026lt;input type=\u0026#34;text\u0026#34; name=\u0026#34;user\u0026#34; \u0026gt; 3 \u0026lt;input type=\u0026#34;submit\u0026#34; value=\u0026#34;submit\u0026#34;\u0026gt; 4\u0026lt;/form\u0026gt; snippet of web.xml:\n1\u0026lt;servlet\u0026gt; 2 \u0026lt;servlet-name\u0026gt;check\u0026lt;/servlet-name\u0026gt; 3 \u0026lt;servlet-class\u0026gt;MyHttpServletRequestServlet\u0026lt;/servlet-class\u0026gt; 4\u0026lt;/servlet\u0026gt; 5\u0026lt;servlet-mapping\u0026gt; 6 \u0026lt;servlet-name\u0026gt;check\u0026lt;/servlet-name\u0026gt; 7 \u0026lt;url-pattern\u0026gt;/check\u0026lt;/url-pattern\u0026gt; 8\u0026lt;/servlet-mapping\u0026gt; snippet of MyHttpServletRequestServlet.java:\n1import java.io.*; 2import javax.servlet.*; 3import javax.servlet.http.*; 4 5public class MyHttpServletRequestServlet extends HttpServlet { 6 7 protected void doPost(HttpServletRequest request, 8 HttpServletResponse response) 9 throws ServletException, IOException { 10 response.setContentType(\u0026#34;text/html;charset=UTF-8\u0026#34;); 11 PrintWriter out = response.getWriter(); 12 try { 13 String user = request.getParameter(\u0026#34;user\u0026#34;); 14 out.println(\u0026#34;\u0026lt;h2\u0026gt; Welcome \u0026#34;+user+\u0026#34;\u0026lt;/h2\u0026gt;\u0026#34;); 15 } finally { 16 out.close(); 17 } 18 } 19} RequestDispatcher RequestDispatcher defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.\nThe servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.\nMethods of RequestDispacher interface:\n1public void forward(ServletRequest request, 2 ServletResponse response) 3 throws ServletException, IOException 4 5public void include(ServletRequest request, 6 ServletResponse response) 7 throws ServletException, IOException To get an object of RequestDispacher:\nRequestDispacher object can be gets from HttpServletRequest object.\nServletRequest’s getRequestDispatcher() method is used to get RequestDispatcher object.\nExample:\n1protected void doPost(HttpServletRequest request, 2 HttpServletResponse response) 3 throws ServletException, IOException { 4 response.setContentType(\u0026#34;text/html\u0026#34;); 5 PrintWriter out = response.getWriter(); 6 7 //get parameters from request object. 8 String userName = 9 request.getParameter(\u0026#34;userName\u0026#34;).trim(); 10 String password = 11 request.getParameter(\u0026#34;password\u0026#34;).trim(); 12 13 //check for null and empty values. 14 if(userName == null || userName.equals(\u0026#34;\u0026#34;) 15 || password == null || password.equals(\u0026#34;\u0026#34;)){ 16 out.print(\u0026#34;Please enter both username\u0026#34; + 17 \u0026#34; and password. \u0026lt;br/\u0026gt;\u0026lt;br/\u0026gt;\u0026#34;); 18 RequestDispatcher requestDispatcher = 19 request.getRequestDispatcher(\u0026#34;/login.html\u0026#34;); 20 requestDispatcher.include(request, response); 21 }//Check for valid username and password. 22 else if(userName.equals(\u0026#34;jai\u0026#34;) \u0026amp;\u0026amp; 23 password.equals(\u0026#34;1234\u0026#34;)){ 24 RequestDispatcher requestDispatcher = 25 request.getRequestDispatcher(\u0026#34;WelcomeServlet\u0026#34;); 26 requestDispatcher.forward(request, response); 27 }else{ 28 out.print(\u0026#34;Wrong username or password. \u0026lt;br/\u0026gt;\u0026lt;br/\u0026gt;\u0026#34;); 29 RequestDispatcher requestDispatcher = 30 request.getRequestDispatcher(\u0026#34;/login.html\u0026#34;); 31 requestDispatcher.include(request, response); 32 } 33} In brief:\n1// 1. use `requestDispatcher.include()`: 2// if invalid `userName` or `password` inputed, 3// return to \u0026#39;login.html\u0026#39; and retry 4RequestDispatcher requestDispatcher = 5 request.getRequestDispatcher(\u0026#34;/login.html\u0026#34;); 6requestDispatcher.include(request, response); 7 8// 2. use `requestDispatcher.forward()`: 9// if correct `userName` and `password` inputed, 10// return to \u0026#39;Welcome Servlet\u0026#39; 11RequestDispatcher requestDispatcher = 12 request.getRequestDispatcher(\u0026#34;WelcomeServlet\u0026#34;); 13requestDispatcher.forward(request, response); ServletResponse ServletResponse defines an object to assist a servlet in sending a response to the client.\nThe servlet container creates a ServletResponse object and passes it as an argument to the servlet's service() method. To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.\nHttpServletResponse HttpServletResponse extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.\nThe servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's service() methods (doGet(), doPost(), etc).\nCookies and Sessions There are 2 mechanisms which allow us to store user data between subsequent requests to the server – the cookie and the session\nCookie A cookie is a small piece of information as a text file stored on client’s machine by a web application.\nThe servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.\nThe browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies() method. Several cookies might have the same name but different path attributes.\nThere are 2 types of cookies:\n Session cookies (Non-persistent cookies) They are accessible as long as session is open, and they are lost when session is closed by exiting from the web application.\n Permanent cookies(Persistent cookies) They are still alive when session is closed by exiting from the web application, and they are lost when they expire.\n Example:\n1//create cookie object 2Cookie cookie=new Cookie(“cookieName”,”cookieValue”); 3response.addCookie(cookie); 4 5//get all cookie objects. 6Cookie[] cookies = request.getCookies(); 7for(Cookie cookie : cookies){ 8 out.println(“Cookie Name: ” + cookie.getName()); 9 out.println(“Cookie Value: ” + cookie.getValue()); 10} 11 12//Remove value from cookie 13Cookie cookie = new Cookie(“cookieName”, “”); 14cookie.setMaxAge(0); 15response.addCookie(cookie); HttpSession HttpSession is an interface that provides a way to identify a user in multiple page requests. A unique session id is given to the user when first request comes. This id is stored in a request parameter or in a cookie.\nExample:\n1HttpSession session = request.getSession(); 2session.setAttribute(\u0026#34;attName\u0026#34;, \u0026#34;attValue\u0026#34;); 3String value = (String) session.getAttribute(\u0026#34;attName\u0026#34;); Filter and Event Listener In web applications, we use filters to preprocess and postprocess the parameters. And during runtime of web apps, we use event listeners to do callback stuff.\nFilter A filter is an object that is invoked at the preprocessing and postprocessing of a request on the server.\nServlet filters are mainly used for following tasks:\n Preprocessing\nPreprocessing of request before it accesses any resource at server side.\n Postprocessing\nPostprocessing of response before it sent back to client.\n flowchart TD\rClient \u0026lt;--\u0026gt; Listener[Web\u0026lt;br/\u0026gt;Listener]\rListener \u0026lt;--\u0026gt; Container[Servlet Container]\rContainer --\u0026gt; |Request| Filter1 --\u0026gt; Filter2 --\u0026gt; FilterN --\u0026gt; Servlet\rServlet --\u0026gt; |Response| FilterN --\u0026gt; Filter2 --\u0026gt; Filter1 --\u0026gt; Container\rThe order in which filters are invoked depends on the order in which they are configured in the web.xml file. The first filter in web.xml is the first one invoked during the request, and the last filter in web.xml is the first one invoked during the response. Note the reverse order during the response.\nFilter API (or interface) includes some methods which help us in filtering requests:\n1public void init(FilterConfig config) 2public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain) 3public void destroy() To create a filter, implement javax.servlet.Filter interface\n\u0026lt;filter\u0026gt; attribute is used to define a filter in web.xml:\n1\u0026lt;filter\u0026gt; 2 \u0026lt;filter-name\u0026gt;filterName \u0026lt;/filter-name\u0026gt; 3 \u0026lt;filter-class\u0026gt;filterClass\u0026lt;/filter-class\u0026gt; 4\u0026lt;/filter\u0026gt; 5\u0026lt;filter-mapping\u0026gt; 6 \u0026lt;filter-name\u0026gt;filterName\u0026lt;/filter-name\u0026gt; 7 \u0026lt;url-pattern\u0026gt;urlPattern\u0026lt;/url-pattern\u0026gt; 8\u0026lt;/filter-mapping\u0026gt; FilterChain object is used to call the next filter or a resource, if it is the last filter in filter chaining.\nExample:\nsnippet of MyFilter.java:\n1public class MyFilter implements Filter { 2 3\tpublic void init(FilterConfig filterConfig) throws ServletException { } 4 5\t@Override 6\tpublic void doFilter(ServletRequest request, 7\tServletResponse response, 8\tFilterChain chain) 9\tthrows IOException, ServletException 10\t{ 11 12\tPrintWriter out = response.getWriter(); 13\tSystem.out.println(\u0026#34;preprocessing before servlet\u0026#34;); 14 // pass to next filter for more check 15\tchain.doFilter(request, response); 16\tSystem.out.println(\u0026#34;postProcessing after servlet\u0026#34;); 17\t} 18 19\tpublic void destroy() {} 20} 21 snippet of index.html:\n1\u0026lt;form action=\u0026#34;MyFilterServlet\u0026#34;\u0026gt; 2 \u0026lt;button type=\u0026#34;submit\u0026#34;\u0026gt;Click here to go to the Servlet\u0026lt;/button\u0026gt; 3\u0026lt;/form\u0026gt; 1\u0026lt;?xml version=\u0026#34;1.0\u0026#34; encoding=\u0026#34;UTF-8\u0026#34;?\u0026gt; 2\u0026lt;web-app xmlns:xsi=\u0026#34;http://www.w3.org/2001/XMLSchema-instance\u0026#34; 3\txmlns=\u0026#34;http://xmlns.jcp.org/xml/ns/javaee\u0026#34; 4\txsi:schemaLocation=\u0026#34;http://xmlns.jcp.org/xml/ns/javaee 5http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd\u0026#34; 6\tid=\u0026#34;WebApp_ID\u0026#34; version=\u0026#34;4.0\u0026#34;\u0026gt; 7\u0026lt;display-name\u0026gt;MyFilterServlet\u0026lt;/display-name\u0026gt; 8\u0026lt;welcome-file-list\u0026gt; 9\t\u0026lt;welcome-file\u0026gt;index.html\u0026lt;/welcome-file\u0026gt; 10\u0026lt;/welcome-file-list\u0026gt; 11\t12\u0026lt;filter\u0026gt; 13\t\u0026lt;filter-name\u0026gt;filter1\u0026lt;/filter-name\u0026gt; 14\t\u0026lt;filter-class\u0026gt;com.app.MyFilterServlet\u0026lt;/filter-class\u0026gt; 15\u0026lt;/filter\u0026gt; 16\t17\u0026lt;filter-mapping\u0026gt; 18\t\u0026lt;filter-name\u0026gt;filter1\u0026lt;/filter-name\u0026gt; 19\t\u0026lt;url-pattern\u0026gt;/MyFilterServlet\u0026lt;/url-pattern\u0026gt; 20\u0026lt;/filter-mapping\u0026gt; 21\t22\u0026lt;/web-app\u0026gt; 23 snippet of MyFilterServlet.java:\n1@WebServlet(\u0026#34;/MyFilterServlet\u0026#34;) 2public class MyFilterServlet extends HttpServlet { 3 4\tprotected void doGet(HttpServletRequest request, 5\tHttpServletResponse response) 6\tthrows ServletException, IOException 7\t{ 8\tPrintWriter out = response.getWriter(); 9\tout.println(\u0026#34;\u0026lt;h1\u0026gt;Welcome to the Servlet.\u0026#34;); 10\tSystem.out.println(\u0026#34;MyFilterServlet is running\u0026#34;); 11\t} 12 13\tprotected void doPost(HttpServletRequest request, 14\tHttpServletResponse response) 15\tthrows ServletException, IOException 16 { 17\tdoGet(request, response); 18\t} 19} Event Listener Event Listener allows Servlet to track key events in your Web applications through event listeners.\nThis functionality allows more efficient resource management and automated processing based on event status.\nflowchart TD\rClient \u0026lt;--\u0026gt; Listener[Web\u0026lt;br/\u0026gt;Listener]\rListener \u0026lt;--\u0026gt; Container[Servlet Container]\rContainer --\u0026gt; |Request| Servlet\rServlet --\u0026gt; |Response| Container\rThere are 2 levels of servlet events:\n Servlet context-level (application-level) event\nThis event involves resources or state held at the level of the application servlet context object.\n Session-level event\nThis event involves resources or state associated with the series of requests from a single user session; that is, associated with the HTTP session object.\n Listeners handling Servlet Lifecycle Events:\n Object: Event Listener Interface Event Class Web context: Initialization and destruction ServletContextListener ServletContextEvent Web context: Attribute added, removed, or replaced ServletContextAttributeListener ServletContextAttributeEvent Session: Creation, invalidation, activation, passivation, and timeout HttpSessionListener, HttpSessionActivationListener HttpSessionEvent Session: Attribute added, removed, or replaced HttpSessionAttributeListener HttpSessionBindingEvent Request: A servlet request has started being processed by web components ServletRequestListener ServletRequestEvent Request: Attribute added, removed, or replaced ServletRequestAttributeListener ServletRequestAttributeEvent Event classes:\n Event Class Methods ServletRequestEvent getServletContext(), getServletRequest() ServletContextEvent getServletContext() ServletRequestAttributeEvent getName(), getValue() ServletContextAttributeEvent getName(), getValue() HttpSessionEvent sessionCreated(), sessionDestroyed(), sessionWillPassivate(), sessionDidActivate() HttpSessionBindingEvent getName(), getSession(), getValue() Configure the Listener class in the web.xml files:\n1\u0026lt;web-app\u0026gt; 2 \u0026lt;listener\u0026gt; 3 \u0026lt;listener-class\u0026gt;myListenerName\u0026lt;/listener-class\u0026gt; 4 \u0026lt;/listener\u0026gt; 5\u0026lt;/web-app\u0026gt; Note: Except for HttpSessionBindingListener and HttpSessionActivationListener, all Listeners require the aforementioned listener configuration.\nExample Code of AppContextAttributeListener:\nsnippet of web.xml:\n1\u0026lt;listener\u0026gt; 2 \u0026lt;listener-class\u0026gt;AppContextAttributeListener\u0026lt;/listener-class\u0026gt; 3\u0026lt;/listener\u0026gt; snippet of AppContextAttributeListener.java:\n1@WebListener 2public class AppContextAttributeListener implements ServletContextAttributeListener { 3\tpublic void attributeAdded(ServletContextAttributeEvent\tevent) { 4\tSystem.out.println( \u0026#34;ServletContext attribute added::{\u0026#34; event.getName() + \u0026#34;,\u0026#34;+ event.getValue() + \u0026#34;}\u0026#34;); 5\t} 6 7\tpublic void\tattributeReplaced(ServletContextAttributeEvent event) { 8 System.out.println( \u0026#34;ServletContext attribute replaced::{\u0026#34; event.getName() + \u0026#34;,\u0026#34;+ event.getValue() + \u0026#34;}\u0026#34;); 9\t} 10\tpublic void\tattributeRemoved(ServletContextAttributeEvent event) { 11 12 System.out.println( \u0026#34;ServletContext attribute removed::{\u0026#34; event.getName() + \u0026#34;,\u0026#34;+ event.getValue() + \u0026#34;}\u0026#34;); 13\t} 14} ","link":"https://mighten.github.io/2023/03/servlet/","section":"post","tags":["Java"],"title":"Servlet"},{"body":"Hello!\nToday, let's talk about signing a git commit with GPG, an encryption engine for signing and signature verification.\nWhen it comes to work across the Internet, it's recommended that we add a cryptographic signature to our commit, which provides some sort of assurance that a commit is originated from us, rather than from an impersonator.\nThis blog is based on the following environments:\n Windows 10 x64-based Ubuntu 20.04 LTS, Windows Subsystem Linux (WSL) version 2 1. Preparations In this section, we will install GPG, and config it.\nInstallation 1$ sudo apt-get install gnupg And it's done. Next, we have to configure it.\nFirstly, we will append these two lines to the profile file. In this case, I am using bash. So I will open ~/.bashrc, and append:\n1export GPG_TTY=$(tty) 2gpgconf --launch gpg-agent After saving these contents, we will go to the terminal, and type this command to validate settings:\n1$ source ~/.bashrc And the GPG is ready to go.\n2. Configurations 2.1 Generate a GPG Key Pair Just type this command:\n1$ gpg --full-gen-key Note:\n What kind of key you want: RSA and RSA (default) What keysize do you want: 4096 How long the key should be valid: 0 (key does not expire) Is this correct: Y Real Name: (Your GitHub Name) E-mail: (Your GitHub Email), and it MUST MATCH your GitHub account !!! Comment: (Leave your note for that key) 2.2 Add Public Key to GitHub Settings Now that the keys are generated, we need to add the Public Key to GitHub Setting pages.\nTo fill in the contents, we go back to the Terminal, and type these commands to get GPG Public Key:\n1# (1) List all the keys 2$ gpg --list-secret-keys --keyid-format=long 3 4# And it shows the following contents: (* hidden for privacy) 5# sec rsa4096/********** 2022-05-20 [SC] 6# ED0BEFAC1E5C4681F0A0FEF0E97461039812B753 7# uid [ultimate] Mighten Dai \u0026lt;mighten@outlook.com\u0026gt; 8# ssb rsa4096/********** 2022-05-20 [E] 9 10# (2) Display the associate Public Key 11$ gpg --armor --export ED0BEFAC1E5C4681F0A0FEF0E97461039812B753 # copy from above and this command will shows the required Public Key like that:\n1-----BEGIN PGP PUBLIC KEY BLOCK----- 2 3......... 4-----END PGP PUBLIC KEY BLOCK----- In SSH and GPG Keys of your GitHub Settings, click New GPG Key, and it prompts Begins with '-----BEGIN PGP PUBLIC KEY BLOCK-----', which exactly is the contents above.\n2.3 Associate with Git In Section 2.2, my Private Key shown as 'ED0BEFAC1E5C4681F0A0FEF0E97461039812B753', so I just open the configuration file ~/.gitconfig and change the following properties:\n1[user] 2 name = Mighten Dai 3email = mighten@outlook.com 4signingKey = ED0BEFAC1E5C4681F0A0FEF0E97461039812B753 5[commit] 6 gpgsign = true 7[gpg] 8 program = /usr/bin/gpg And it's done.\n3. Git Commit with GPG 1$ git add . 2$ git commit -S -m \u0026#34;This is a commit with PGP Signature\u0026#34; 4. (Optional) In this section, we talk about other usage of GPG\n4.1 Sign \u0026amp; Verify Plaintext If you just want to sign a plaintext, you just type with a Pipe command | like this:\n1echo \u0026#34;Signing a plaintext\u0026#34; | gpg --clearsign and it immediately shows:\n1-----BEGIN PGP SIGNED MESSAGE----- 2Hash: SHA512 3 4Signing a plaintext 5-----BEGIN PGP SIGNATURE----- 6 7iQIzBAEBCgAdFiEE7QvvrB5cRoHwoP7w6XRhA5gSt1MFAmRxbSoACgkQ6XRhA5gS 8t1OfvA/+IGNwwCfJmwkb2LjhUQgACcUedCS6/VGb7uek7PQwQJr6Aid4hp7cguVz 9lfGpadKTi6chokwcRgwjjuaCd/DFabaHs5e03Q2nn8qqE5Gx+chNcG/+9/cuDRxa 10JnyEiqTUY62UIGY6+WVYgKE/+T3CpRX3wdLYC3n0InyctdJZNIIycX/IragUhXAh 11VSZc66QxA60zgNFXzypMyl8NfxmDQKdE8IkCOgiPgHhat0dDQxQQd6zqSmTdQM8P 12OXpLpT0ryXI9ZnqkOk/gN9mUrncpilelE2J6NgMKbe0lOGNP45F9GQMxqVUQqw/1 13i6rCTV4gLR+Xmfaydo9fFj5p5mB7VK8IPZGh5Q7RM722D4NxJfaIekhlD1Sy32cP 14wp0581fHLk778ngz6jomNt/srND5xf13cStdHSxSMwHS8PXxyh5rUs5KtTDH7srg 15U19l8rdgr9TBl6/ydBlL0aepGQW95KA0loxW2mwrpsEG8Ii1fZ2kMWqR17dPxwoe 167O3BbeGW0k9Ur3MSm8m5jP2OKvDm62cMiLnUYP3LKakKGL4PBeer26NWK+4dXhi6 170/ohXd7GGa1zuhChFwj0/pqzjYU2PQLUUOb1/UXKXmpGvu/GvGvZ1Slu0VOKUVil 18dXv1cxUHgINY6CvoCdH6gxuKmz1K4B8TXqZ4wzMj4FLx/10PtPk= 19=tIWQ 20-----END PGP SIGNATURE----- And if some guy send you these thing, you can verify by:\n1$ gpg --verify signedMsg.txt 2gpg: Signature made Fri May 20 15:51:09 2022 CST 3gpg: using RSA key ED0BEFAC1E5C4681F0A0FEF0E97461039812B753 4gpg: Good signature from \u0026#34;Mighten Dai \u0026lt;mighten@outlook.com\u0026gt;\u0026#34; [ultimate] It seems that this message is good. What if we want to tamper with this message\n1$ gpg --verify signedMsg-tampered.txt 2gpg: Signature made Fri May 20 15:51:09 2022 CST 3gpg: using RSA key ED0BEFAC1E5C4681F0A0FEF0E97461039812B753 4gpg: BAD signature from \u0026#34;Mighten Dai \u0026lt;mighten@outlook.com\u0026gt;\u0026#34; [ultimate] So, now we can see the bad message detected.\n4.2 Verify Online Files In this section, I will verify the integrity of online files.\nI have downloaded the file gnupg-2.4.2.tar.bz2.sig and its signature file gnupg-2.4.2.tar.bz2, I can verify by:\n1# 1. acquire Public Key of the publisher, 2# e.g., https://gnupg.org/signature_key.html 3$ gpg --import public_key.asc 4... 5gpg: Total number processed: 4 6gpg: imported: 4 7gpg: marginals needed: 3 completes needed: 1 trust model: pgp 8gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u 9 10# 2. verify the file 11$ gpg --verify gnupg-2.4.2.tar.bz2.sig gnupg-2.4.2.tar.bz2 12gpg: Signature made 5/30/2023 8:27:44 PM China Standard Time 13gpg: using EDDSA key 6DAA6E64A76D2840571B4902528897B826403ADA 14gpg: Good signature from \u0026#34;Werner Koch (dist signing 2020)\u0026#34; [unknown] 15... 16 17# 3. List all the keys 18$ gpg --list-keys 19 20# 4. Delete keys that are temporarily imported 21$ gpg --delete-key \u0026lt; The keyID you want to delete \u0026gt; ","link":"https://mighten.github.io/2022/05/how-to-sign-our-git-commits-with-gpg/","section":"post","tags":["Misc"],"title":"How to Sign Our Git Commits with GPG"},{"body":"","link":"https://mighten.github.io/tags/misc/","section":"tags","tags":null,"title":"Misc"},{"body":"Hi, welcome to Mighten's Tech blog!\nThis blog focuses on Cloud Computing and Machine Learning.\nCurrently, I am studying Big Data and Artificial Intelligence (M.Eng. degree in Software Engineering) at University of Science and Technology of China (USTC).\nPLANS There are lists of what I gonna do:\nPlan on Skills UML Diagram Design Pattern NGINX CI/CD Pipeline AWS or Azure Plan on Courses MIT 6.824 Distributed Systems, Spring 2020 Plan on Readings Algorithms parts in Introduction to Java Programming Language (The Complete Version). Designing Data-Intensive Applications, which was written by Prof. Martin Kleppmann ACKNOWLEDGEMENTS There is a list of fantastic components that help to build this blog:\n Hugo, a fast and modern static site generator written in Go. Hugo Clarity, A theme based on VMware's Clarity Design System for publishing technical blogs with Hugo. KaTeX, a fast, easy-to-use JavaScript library for TeX math rendering on the web. Mermaid, a JavaScript-based diagramming and charting tool that uses Markdown-inspired text definitions and a renderer to create and modify complex diagrams. Utterances, a lightweight comments widget built on GitHub issues. Cloudflare Web Analytics, a free and privacy-first analytics tool for your website. Vecta Nano, a SVG file optimizer that can embed fonts and minify SVG file to save space and bandwidth. ","link":"https://mighten.github.io/about/","section":"","tags":null,"title":"About"},{"body":"","link":"https://mighten.github.io/series/ddia/","section":"series","tags":null,"title":"DDIA"},{"body":"Hi!\nLet's read the Chapter 01: Reliable, Scalable, and Maintainable Applications of Designing Data-Intensive Applications.\nIt introduces the terminology and approach that we are going to use throughout the book, and it also explores some fundamental ways of thinking about data-intensive applications: general properties (nonfunctional requirements) such as reliability, scalability, and maintainability.\nFirst of all, there are 2 types of applications:\n compute-intensive applications: raw CPU power is a limiting factor data-intensive applications: the bigger problems are usually the amount of data, the complexity of data, and the speed at which it is changing. And many applications today are data-intensive, which are typically built from standard building blocks (commonly needed functionalities):\n Databases Caches Search Indexes Streaming Processing Batch Processing In reality, however, it can be hard to combine these tools when building an application.\n1.1 Thinking About Data Systems In this section, we talk about the background of the Data Systems.\nData Systems all can store data for some time, but with different access patterns, which means different performance characteristics, and thus very different implementations.\nIn recent years, with new tools for data processing and storage emerged, the boundaries between traditional categories are becoming blurred. And with different tools stitched together by application code, the work is broken down into tasks that can be performed efficiently on a single tool.\nHowever, a lot of tricky questions arise when designing a data system or service. And in this book, we mainly focus on 3 concerns that are important in most software systems: Reliability, Scalabilility, and Maintainability.\n1.2 Reliability In this section, we deals with the kinds of faults that can be cured, such as hardware faults, software errors, and human errors.\nFirst of all, the Reliability means that the system should continue to work correctly, even in the face of adversity.\nHowever, if things did go wrong, it could only make sense to talk about tolerating certain types of faults, preventing faults from causing failures.\nIn practice, we generally prefer tolerating faults over preventing faults, and by deliberately inducing faults, we ensure that the fault-tolerant machinery is continually exercised and tested.\n1.2.1 Hardware Faults Hardware faults are faults that happen randomly, reported as having a Mean Time To Failure (MTTF).\nHardware Faults have weak correlation, and thus are independent from each other.\nSolution for tolerating faults (rather than preventing faults):\n add hardware redundancy use software fault-tolerance techniques 1.2.2 Software Errors Software Errors are systematic errors within the system.\nSoftware errors have strong correlation, which means they are correlated across nodes.\nSolutions:\n carefully thinking about assumptions and interactions in the system. thorough testing process isolation allowing process(es) to crash and restart measuring, monitoring, and analyzing system behavior in production 1.2.3 Human Errors Human errors are caused by human operations, and thus human are known to be unreliable.\nApproaches:\n minimize opportunities for error when designing systems use sandbox environments to decouple places where people make mistakes from places where mistakes causing outage test thoroughly, from unit tests to whole-system integration tests and manual tests quick and easy recovery from human errors detailed and clear monitoring, e.g., telemetry good management practices and training 1.3 Scalabilility In this section, we focus on scalabilility - the ability that a system have to cope with the the increased load.\n1.3.1 Describing 'Load' Load can be described with a few numbers, called load parameters.\nThe best choice of parameters depends on the architecture of the system.\n1.3.2 Describing 'Performance' We use performance numbers to investigate what happens when load increases.\nAnd we use percentile, one of the performance numbers, to denote response time, which is a distribution of values that can be measured (e.g., p999 meaning 99.9% of requests are handled faster than the particular threshold).\nHowever, reducing response times at very high percentiles (known as tail latencies) may be too expensive, and may be difficult due to random events outside your control.\nQueueing delays often account for a large part of the response time at high percentiles, for the following reasons:\n head-of-line blocking: a small number of slow requests in parallel hold up the processing of subsequent requests. tail latency amplification: just one slow backend request can slow down the entire end-user requests. 1.3.3 Coping with Load In this part, we talk about how to maintain good performance, even when load parameters increase.\n Rethink architecture on every order of magnitude of load increases. Use a mixture of 2 scaling approaches scaling up, or vertical scaling: moving to a more powerful machine scaling down, or horizontal scaling: distributing the load across multiple machines, also known as shared-nothing architecture When choosing load parameters, figure out which operations will be common and which will be rare. Use elastic systems to add computing resources automatically if load is highly unpredictable; but manually scaled systems are simpler and may have fewer operational surprises. 1.4 Maintainability The majority of cost of software is in its ongoing maintenance, so software should be designed to minimize pain during maintenance, and thus to avoid creating legacy softwares.\nAnd in this section, we pay attention to 3 designing principles for software systems: operability, simplicity, and evolvability.\n1.4.1 Operability Operability can make it easy for operations teams to keep the system running smoothly.\nData system should provide good operability, which means making routine tasks easy, allowing the operations team to focus their efforts on high-value activities.\n1.4.2 Simplicity Simplicity can make it easy for new engineers to understand the system.\nWe use abstraction to remove accidental complexity, which is not inherent in the problem that software solves (as seen by users) but arises only from the implementation.\nAnd our goal is to use good abstraction to extract parts of the large systems into well-defined, reusable components.\n1.4.3 Evolvability Evolvability can make it easy for engineers to make changes to the system in the future, adapting it for unanticipated use cases as requirements change.\nIn terms of organizational processes, we use a framework from Agile working patterns to adapt to change. And the Agile community has also developed technical tools and patterns that are helpful when developing softwares in frequently changing environments, such as test-driven development (TDD) and refactoring.\nAnd in this book, we will use evolvability to refer to agility on a data system level.\n","link":"https://mighten.github.io/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/","section":"post","tags":["System Design"],"title":"DDIA Ch01: Reliable, Scalable, and Maintainable Applications"},{"body":"Hi there, let's talk about how to nonrecursively do a In-Order traversal for a Binary Tree.\nA Binary Tree consists of 3 parts: the node itself, pointer to the left child, pointer to the right child.\nAn In-Order Traversal is to access the leftmost child firstly, then the node itself, and finally the right child.\n1. Question 94. Binary Tree Inorder Traversal:\nGiven the root of a binary tree, return the inorder traversal of its nodes' values.\n1.1 Examples Example 1: 1Input: root = [1,null,2,3] 2Output: [1,3,2] Example 2: 1Input: root = [] 2Output: [] Example 3: 1Input: root = [1] 2Output: [1] 1.2 Constraints The number of nodes in the tree is in the range $ \\left[ 0, 100 \\right ] $. $ -100 \\leq \\text{node.val} \\leq 100 $ 2. Solution To solve this problem, we will use stack.\nThis approach is a nonrecursive method.\n2.1 Code 1class Solution { 2public: 3 vector\u0026lt;int\u0026gt; inorderTraversal(TreeNode* root) { 4 if (root == nullptr) return {}; // corner case: empty tree 5 6 TreeNode * p = root; 7 stack\u0026lt;TreeNode *\u0026gt; stk; 8 9 vector\u0026lt;int\u0026gt; ans; 10 while (p != nullptr || stk.empty() == false) { 11 while (p != nullptr) { // To Left Child, until end 12 stk.push(p); 13 p = p-\u0026gt;left; 14 } 15 p = stk.top(); stk.pop(); 16 ans.push_back(p-\u0026gt;val); // Node-\u0026gt;val 17 p = p-\u0026gt;right; // Right Child 18 } 19 20 return ans; 21 } 22}; 2.2 Complexity Analysis Assume the number of nodes in the tree is $ n $, and thus:\n Time complexity: $ T(n) = O(n) $\n Space complexity: $ S(n) = O(n) $\n ","link":"https://mighten.github.io/2022/05/binary-tree-nonrecursive-inorder/","section":"post","tags":["Algorithm"],"title":"Binary Tree NonRecursive InOrder"},{"body":"Hello World!\nThis is my first blog post. Today, let's talk about writing a Markdown blog with Hugo, and eventually deploying it on GitHub Pages.\nHugo is a static HTML and CSS website generator, which allows us to concentrate on the contents rather than the layout tricks.\nEnvironment:\n Windows 10 (64-bit) Ubuntu 20.04 LTS, Windows Subsystem Linux 2 PREPARATIONS In this section, we will prepare the tools.\nNOTE: Please check out the official websites for detailed guidance. I may not cover full details.\nToolchain In this section, we will use two powerful tools: git and golang\n1$ sudo apt-get install git golang 2 3$ git config --global user.name \u0026#34;Your GitHub Username\u0026#34; 4$ git config --global user.email \u0026#34;Your GitHub Email\u0026#34; Install Hugo Compiler Install from GitHub Release package, choose the latest package with the name 'extended', e.g., \u0026quot;hugo_extended_0.98.0_Linux-64bit.deb\u0026quot;\nTo install it, type:\n1$ sudo dpkg -i ./hugo_extended_0.98.0_Linux-64bit.deb NOTE: DO NOT use apt to install hugo, because its version of hugo installation package has already been outdated and can thus cause runtime errors.\nGenerate RSA keys 1$ ssh-keygen -t rsa -C \u0026#34;Your GitHub Email\u0026#34; And then add the public key in ~/.ssh/id_rsa.pub to the GitHub Dashboard, and test connection:\n1$ ssh -T git@github.com CREATE BLOG In this section, we will initialize the blog.\nGenerate an empty site 1$ hugo new site \u0026#34;NewSite\u0026#34; 2$ cd NewSite Initialize '.git' This will prepare the submodule environment for Hugo themes.\n1$ git init Hugo Theme Pickup In this section, we will pick up a beautiful theme for the new site.\nUnlike Hexo, an alternative blog generating tool, the Hugo does not consist of a default theme, so let's pick theme(s) for Hugo.\nAnd I prefer the hugo-Clarity, so I type these commands:\n1# 1. Getting started with Clarity theme 2$ git submodule add https://github.com/chipzoller/hugo-clarity themes/hugo-clarity 3 4# 2. copy the essential files to start 5$ cp -a themes/hugo-clarity/exampleSite/* . \u0026amp;\u0026amp; rm -f config.toml NOTE: We use git submodule here, rather than git clone. Because we already have a .git configuration.\nPreview 1$ hugo server --buildDrafts=true Well done, now we can preview our blog (including drafts) with the URL shown in the Terminal.\nIn this case, my URL to preview is http://localhost:1313/\nPOST NOW In this section, we will talk about how to upload a new post and do some tweaks.\nCreate a new post 1$ hugo new post/post-1.md NOTE: the folder is 'post', not 'posts'\nFill in the contents Open the newly generated file in ./content/post/post-1.md, and change its header\n1--- 2title: \u0026#34;Hello World\u0026#34; 3 4description: \u0026#34;The first blog, and how to \u0026#39;Hugo\u0026#39; a blog\u0026#34; 5summary: \u0026#34;How to use Hugo to build a personal blog, and publish it onto GitHub Pages.\u0026#34; 6tags: [\u0026#34;Misc\u0026#34;] 7 8date: 2022-05-15T19:28:07+08:00 9 10katex: false 11mermaid: false 12utterances: true 13 14draft: false 15--- 16 17Hello World! 18 19This is my first blog post. NOTE:\n the header part begins with 3 dashes the draft: true meaning this file is a draft and will not be rendered into webpage (requires hugo command line $ hugo --buildDrafts=false); however if you do want to display (debug) this draft article, you can use command line $ hugo server --buildDrafts=true. Now that the Hugo server is started, your contents will be synchronized into webpage instantly once you saved your changes. Upload 1# 1) generate the output files in ./public 2$ hugo --buildDrafts=false 3$ cd public 4 5# 2) First Time: version control of the file to be published 6$ git init 7$ git remote add origin git@github.com:Mighten/Mighten.github.io.git 8 9# 3) Process the changes and commit 10$ git add . 11$ git commit -m \u0026#39;First Post: Hello World From Hugo!\u0026#39; 12$ git branch -m master main 13$ git push -f --set-upstream origin main NOTE:\n in step 2) the origin is different from person to person, please check your GitHub Settings and set it accordingly in step 3) the upstream origin is usually named main, please go to the GitHub Pages Setting to check it. Well Done, Now the first blog is published!\n","link":"https://mighten.github.io/2022/05/hello-world/","section":"post","tags":["Misc"],"title":"Hello World"},{"body":"","link":"https://mighten.github.io/categories/","section":"categories","tags":null,"title":"Categories"}] \ No newline at end of file diff --git a/index.xml b/index.xml new file mode 100644 index 0000000..cbce3ad --- /dev/null +++ b/index.xml @@ -0,0 +1,296 @@ + + + + Mighten's Blog + https://mighten.github.io/ + Recent content on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Thu, 02 May 2024 17:15:00 +0800 + + KIA CH01 Introducing Kubernetes + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + Thu, 02 May 2024 17:15:00 +0800 + + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + + + + <p>Hi there.</p> +<p>Today, let us read the <em>Chapter 01: Introducing Kubernetes</em> of <strong>Kubernetes in Action</strong></p> +<ol> +<li>the history of software developing</li> +<li>isolation by containers</li> +<li>how containers and Docker are used by Kubernetes</li> +<li>how to simplify works by Kubernetes</li> +</ol> + + + + + + + + Spring Framework + https://mighten.github.io/2023/07/spring-framework/ + Wed, 19 Jul 2023 00:00:00 +0800 + + https://mighten.github.io/2023/07/spring-framework/ + + + + <p>Hi there!</p> +<p>In this blog, we talk about <em><strong>Spring Framework</strong></em>, a Java platform that provides comprehensive infrastructure support for developing Java applications. The content of this blog is shown below:</p> +<ul> +<li>Architecture</li> +<li><em>Spring IoC Container</em></li> +<li>Spring Beans</li> +<li><em>Dependency Injection (DI)</em></li> +<li>Spring Annotations</li> +<li><em>Aspect Oriented Programming (AOP)</em></li> +</ul> + + + + + + + + Maven + https://mighten.github.io/2023/06/maven/ + Wed, 21 Jun 2023 00:00:00 +0800 + + https://mighten.github.io/2023/06/maven/ + + + + <p><em><strong>Maven</strong></em> is a <em>project management tool</em> that is based on <em>POM</em> (<em>project object model</em>). It is used for <strong>projects build</strong>, <strong>dependency</strong> and <strong>documentation</strong>.</p> + + + + + + + + Docker + https://mighten.github.io/2023/06/docker/ + Sat, 17 Jun 2023 23:10:00 +0800 + + https://mighten.github.io/2023/06/docker/ + + + + ***Docker*** is a platform for *developing*, *shipping*, and *deploying* applications quickly in **portable, self-sufficient containers**, and is used in the **Continuous Deployment (CD)** stage of the **DevOps** ecosystem. + + + + + + + + PuTTY with OpenSSH + https://mighten.github.io/2023/06/putty-with-openssh/ + Sat, 17 Jun 2023 22:08:00 +0800 + + https://mighten.github.io/2023/06/putty-with-openssh/ + + + + <p>Hi!</p> +<p>Today we use <em><strong>OpenSSH</strong></em> and <em><strong>PuTTY</strong></em> to log in remote computers.</p> +<ul> +<li><a href="https://www.openssh.com/"><strong>OpenSSH</strong></a> is an open-source version of the <em>Secure Shell</em> (SSH) tools used by administrators of remote systems</li> +<li><a href="https://www.chiark.greenend.org.uk/~sgtatham/putty/"><em><strong>PuTTY</strong></em></a> is a free implementation of <em>SSH</em></li> +</ul> + + + + + + + + MIT 6.033 CSE Security + https://mighten.github.io/2023/06/mit-6.033-cse-security/ + Tue, 13 Jun 2023 09:00:00 +0800 + + https://mighten.github.io/2023/06/mit-6.033-cse-security/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part IV: <em><strong>Security</strong></em>. And in this section, we mainly focus on <em><strong>common pitfalls</strong></em> in the security of computer systems, and how to <em>combat</em> them.</p> +<p>To build a secure system, we need to be clear about two aspects:</p> +<ol> +<li><em>security policy</em> (goal)</li> +<li><em>threat model</em> (assumptions on adversaries)</li> +</ol> + + + + + + + + MIT 6.033 CSE Distributed Systems + https://mighten.github.io/2023/06/mit-6.033-cse-distributed-systems/ + Tue, 06 Jun 2023 22:10:00 +0800 + + https://mighten.github.io/2023/06/mit-6.033-cse-distributed-systems/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part III: <em><strong>Distributed Systems</strong></em>. And in this section, we mainly focus on: How <em><strong>reliable, usable distributed systems</strong></em> are able to be built on top of an <em>unreliable</em> network.</p> + + + + + + + + MIT 6.033 CSE Networking + https://mighten.github.io/2023/05/mit-6.033-cse-networking/ + Tue, 30 May 2023 18:10:00 +0800 + + https://mighten.github.io/2023/05/mit-6.033-cse-networking/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part II: <em><strong>Networking</strong></em>. And in this section, we mainly focus on: how the <em><strong>Internet</strong></em> is designed to <em>scale</em> and its various applications.</p> + + + + + + + + MIT 6.033 CSE Operating System + https://mighten.github.io/2023/04/mit-6.033-cse-operating-system/ + Thu, 06 Apr 2023 15:06:00 +0800 + + https://mighten.github.io/2023/04/mit-6.033-cse-operating-system/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part I: <em><strong>Operating Systems</strong></em>. And in this section, we mainly focus on:</p> +<ul> +<li>How common <em>design patterns</em> in computer system — such as <em>abstraction</em> and <em>modularity</em> — are used to limit <em>complexity</em>.</li> +<li>How operating systems use <em>virtualization</em> and <em>abstraction</em> to enforce <em>modularity</em>.</li> +</ul> + + + + + + + + Linked List + https://mighten.github.io/2023/04/linked-list/ + Wed, 05 Apr 2023 22:22:00 +0800 + + https://mighten.github.io/2023/04/linked-list/ + + + + <p>Today, let's talk about <strong>Linked List</strong> algorithms that are frequently used.</p> +<p>A Linked List is a <em>data structure</em> that stores data into a series of <em>connected nodes</em>, and thus it can be dynamically allocated. For each node, it contains 2 fields: the <code>val</code> that stores data, and the <code>next</code> that points to the next node.</p> + + + + + + + + Servlet + https://mighten.github.io/2023/03/servlet/ + Thu, 30 Mar 2023 18:05:00 +0800 + + https://mighten.github.io/2023/03/servlet/ + + + + <p>Hi there, todaly let's talk about <strong>Servlet</strong> in a nutshell.</p> +<p>A <em>Servlet</em> is a <em>Java</em> programming language <em>class</em>, which is executed in <em>Web Server</em> and responsible for <em>dynamic</em> content generation in a portable way.</p> +<p><em>Servlet</em> extends the capabilities of servers that host applications accessed by means of a <em>request-response programming model</em>.</p> + + + + + + + + How to Sign Our Git Commits with GPG + https://mighten.github.io/2022/05/how-to-sign-our-git-commits-with-gpg/ + Fri, 20 May 2022 13:54:00 +0800 + + https://mighten.github.io/2022/05/how-to-sign-our-git-commits-with-gpg/ + + + + <p>Hello!</p> +<p>Today, let's talk about signing a <em>git commit</em> with <a href="https://gnupg.org/">GPG</a>, an encryption engine for signing and signature verification.</p> +<p>When it comes to work across the Internet, it's recommended that we add a cryptographic signature to our commit, which provides some sort of assurance that a commit is originated from us, rather than from an impersonator.</p> + + + + + + + + DDIA Ch01: Reliable, Scalable, and Maintainable Applications + https://mighten.github.io/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/ + Thu, 19 May 2022 22:06:00 +0800 + + https://mighten.github.io/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/ + + + + <p>Hi!</p> +<p>Let's read the Chapter 01: <em>Reliable, Scalable, and Maintainable Applications</em> of <a href="https://dataintensive.net/"><em>Designing Data-Intensive Applications</em></a>.</p> +<p>It introduces the terminology and approach that we are going to use throughout the book, and it also explores some fundamental ways of thinking about <em><strong>data-intensive applications</strong></em>: general properties (nonfunctional requirements) such as <em><strong>reliability</strong></em>, <em><strong>scalability</strong></em>, and <em><strong>maintainability</strong></em>.</p> + + + + + + + + Binary Tree NonRecursive InOrder + https://mighten.github.io/2022/05/binary-tree-nonrecursive-inorder/ + Mon, 16 May 2022 22:37:50 +0800 + + https://mighten.github.io/2022/05/binary-tree-nonrecursive-inorder/ + + + + <p>Hi there, let's talk about how to nonrecursively do a In-Order traversal for a Binary Tree.</p> +<p>A Binary Tree consists of 3 parts: the node itself, pointer to the left child, pointer to the right child.</p> +<p>An In-Order Traversal is to access the leftmost child firstly, then the node itself, and finally the right child.</p> + + + + + + + + Hello World + https://mighten.github.io/2022/05/hello-world/ + Sun, 15 May 2022 19:28:07 +0800 + + https://mighten.github.io/2022/05/hello-world/ + + + + <p>Hello World!</p> +<p>This is my first blog post. Today, let's talk about writing a <code>Markdown</code> blog with <a href="https://gohugo.io/">Hugo</a>, and eventually deploying it on GitHub Pages.</p> +<p><code>Hugo</code> is a static HTML and CSS website generator, which allows us to concentrate on the contents rather than the layout tricks.</p> + + + + + + + + diff --git a/page/1/index.html b/page/1/index.html new file mode 100644 index 0000000..4c6de81 --- /dev/null +++ b/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/ \ No newline at end of file diff --git a/page/2/index.html b/page/2/index.html new file mode 100644 index 0000000..0cea975 --- /dev/null +++ b/page/2/index.html @@ -0,0 +1,627 @@ + + + + + +Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+
    +
  • +
    +
    +

    + Servlet +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + How to Sign Our Git Commits with GPG +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + DDIA Ch01: Reliable, Scalable, and Maintainable Applications +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Binary Tree NonRecursive InOrder +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Hello World +

    + + + +
    + +
    +
  • + + +
  • + +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/post/index.html b/post/index.html new file mode 100644 index 0000000..518c246 --- /dev/null +++ b/post/index.html @@ -0,0 +1,882 @@ + + + + +Posts | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + KIA CH01 Introducing Kubernetes +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Spring Framework +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Maven +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Docker +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + PuTTY with OpenSSH +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Security +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Distributed Systems +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Networking +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Operating System +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Linked List +

    + + + +
    + +
    +
  • + + +
  • + +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/post/index.xml b/post/index.xml new file mode 100644 index 0000000..2bdb359 --- /dev/null +++ b/post/index.xml @@ -0,0 +1,296 @@ + + + + Posts on Mighten's Blog + https://mighten.github.io/post/ + Recent content in Posts on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Thu, 02 May 2024 17:15:00 +0800 + + KIA CH01 Introducing Kubernetes + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + Thu, 02 May 2024 17:15:00 +0800 + + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + + + + <p>Hi there.</p> +<p>Today, let us read the <em>Chapter 01: Introducing Kubernetes</em> of <strong>Kubernetes in Action</strong></p> +<ol> +<li>the history of software developing</li> +<li>isolation by containers</li> +<li>how containers and Docker are used by Kubernetes</li> +<li>how to simplify works by Kubernetes</li> +</ol> + + + + + + + + Spring Framework + https://mighten.github.io/2023/07/spring-framework/ + Wed, 19 Jul 2023 00:00:00 +0800 + + https://mighten.github.io/2023/07/spring-framework/ + + + + <p>Hi there!</p> +<p>In this blog, we talk about <em><strong>Spring Framework</strong></em>, a Java platform that provides comprehensive infrastructure support for developing Java applications. The content of this blog is shown below:</p> +<ul> +<li>Architecture</li> +<li><em>Spring IoC Container</em></li> +<li>Spring Beans</li> +<li><em>Dependency Injection (DI)</em></li> +<li>Spring Annotations</li> +<li><em>Aspect Oriented Programming (AOP)</em></li> +</ul> + + + + + + + + Maven + https://mighten.github.io/2023/06/maven/ + Wed, 21 Jun 2023 00:00:00 +0800 + + https://mighten.github.io/2023/06/maven/ + + + + <p><em><strong>Maven</strong></em> is a <em>project management tool</em> that is based on <em>POM</em> (<em>project object model</em>). It is used for <strong>projects build</strong>, <strong>dependency</strong> and <strong>documentation</strong>.</p> + + + + + + + + Docker + https://mighten.github.io/2023/06/docker/ + Sat, 17 Jun 2023 23:10:00 +0800 + + https://mighten.github.io/2023/06/docker/ + + + + ***Docker*** is a platform for *developing*, *shipping*, and *deploying* applications quickly in **portable, self-sufficient containers**, and is used in the **Continuous Deployment (CD)** stage of the **DevOps** ecosystem. + + + + + + + + PuTTY with OpenSSH + https://mighten.github.io/2023/06/putty-with-openssh/ + Sat, 17 Jun 2023 22:08:00 +0800 + + https://mighten.github.io/2023/06/putty-with-openssh/ + + + + <p>Hi!</p> +<p>Today we use <em><strong>OpenSSH</strong></em> and <em><strong>PuTTY</strong></em> to log in remote computers.</p> +<ul> +<li><a href="https://www.openssh.com/"><strong>OpenSSH</strong></a> is an open-source version of the <em>Secure Shell</em> (SSH) tools used by administrators of remote systems</li> +<li><a href="https://www.chiark.greenend.org.uk/~sgtatham/putty/"><em><strong>PuTTY</strong></em></a> is a free implementation of <em>SSH</em></li> +</ul> + + + + + + + + MIT 6.033 CSE Security + https://mighten.github.io/2023/06/mit-6.033-cse-security/ + Tue, 13 Jun 2023 09:00:00 +0800 + + https://mighten.github.io/2023/06/mit-6.033-cse-security/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part IV: <em><strong>Security</strong></em>. And in this section, we mainly focus on <em><strong>common pitfalls</strong></em> in the security of computer systems, and how to <em>combat</em> them.</p> +<p>To build a secure system, we need to be clear about two aspects:</p> +<ol> +<li><em>security policy</em> (goal)</li> +<li><em>threat model</em> (assumptions on adversaries)</li> +</ol> + + + + + + + + MIT 6.033 CSE Distributed Systems + https://mighten.github.io/2023/06/mit-6.033-cse-distributed-systems/ + Tue, 06 Jun 2023 22:10:00 +0800 + + https://mighten.github.io/2023/06/mit-6.033-cse-distributed-systems/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part III: <em><strong>Distributed Systems</strong></em>. And in this section, we mainly focus on: How <em><strong>reliable, usable distributed systems</strong></em> are able to be built on top of an <em>unreliable</em> network.</p> + + + + + + + + MIT 6.033 CSE Networking + https://mighten.github.io/2023/05/mit-6.033-cse-networking/ + Tue, 30 May 2023 18:10:00 +0800 + + https://mighten.github.io/2023/05/mit-6.033-cse-networking/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part II: <em><strong>Networking</strong></em>. And in this section, we mainly focus on: how the <em><strong>Internet</strong></em> is designed to <em>scale</em> and its various applications.</p> + + + + + + + + MIT 6.033 CSE Operating System + https://mighten.github.io/2023/04/mit-6.033-cse-operating-system/ + Thu, 06 Apr 2023 15:06:00 +0800 + + https://mighten.github.io/2023/04/mit-6.033-cse-operating-system/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part I: <em><strong>Operating Systems</strong></em>. And in this section, we mainly focus on:</p> +<ul> +<li>How common <em>design patterns</em> in computer system — such as <em>abstraction</em> and <em>modularity</em> — are used to limit <em>complexity</em>.</li> +<li>How operating systems use <em>virtualization</em> and <em>abstraction</em> to enforce <em>modularity</em>.</li> +</ul> + + + + + + + + Linked List + https://mighten.github.io/2023/04/linked-list/ + Wed, 05 Apr 2023 22:22:00 +0800 + + https://mighten.github.io/2023/04/linked-list/ + + + + <p>Today, let's talk about <strong>Linked List</strong> algorithms that are frequently used.</p> +<p>A Linked List is a <em>data structure</em> that stores data into a series of <em>connected nodes</em>, and thus it can be dynamically allocated. For each node, it contains 2 fields: the <code>val</code> that stores data, and the <code>next</code> that points to the next node.</p> + + + + + + + + Servlet + https://mighten.github.io/2023/03/servlet/ + Thu, 30 Mar 2023 18:05:00 +0800 + + https://mighten.github.io/2023/03/servlet/ + + + + <p>Hi there, todaly let's talk about <strong>Servlet</strong> in a nutshell.</p> +<p>A <em>Servlet</em> is a <em>Java</em> programming language <em>class</em>, which is executed in <em>Web Server</em> and responsible for <em>dynamic</em> content generation in a portable way.</p> +<p><em>Servlet</em> extends the capabilities of servers that host applications accessed by means of a <em>request-response programming model</em>.</p> + + + + + + + + How to Sign Our Git Commits with GPG + https://mighten.github.io/2022/05/how-to-sign-our-git-commits-with-gpg/ + Fri, 20 May 2022 13:54:00 +0800 + + https://mighten.github.io/2022/05/how-to-sign-our-git-commits-with-gpg/ + + + + <p>Hello!</p> +<p>Today, let's talk about signing a <em>git commit</em> with <a href="https://gnupg.org/">GPG</a>, an encryption engine for signing and signature verification.</p> +<p>When it comes to work across the Internet, it's recommended that we add a cryptographic signature to our commit, which provides some sort of assurance that a commit is originated from us, rather than from an impersonator.</p> + + + + + + + + DDIA Ch01: Reliable, Scalable, and Maintainable Applications + https://mighten.github.io/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/ + Thu, 19 May 2022 22:06:00 +0800 + + https://mighten.github.io/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/ + + + + <p>Hi!</p> +<p>Let's read the Chapter 01: <em>Reliable, Scalable, and Maintainable Applications</em> of <a href="https://dataintensive.net/"><em>Designing Data-Intensive Applications</em></a>.</p> +<p>It introduces the terminology and approach that we are going to use throughout the book, and it also explores some fundamental ways of thinking about <em><strong>data-intensive applications</strong></em>: general properties (nonfunctional requirements) such as <em><strong>reliability</strong></em>, <em><strong>scalability</strong></em>, and <em><strong>maintainability</strong></em>.</p> + + + + + + + + Binary Tree NonRecursive InOrder + https://mighten.github.io/2022/05/binary-tree-nonrecursive-inorder/ + Mon, 16 May 2022 22:37:50 +0800 + + https://mighten.github.io/2022/05/binary-tree-nonrecursive-inorder/ + + + + <p>Hi there, let's talk about how to nonrecursively do a In-Order traversal for a Binary Tree.</p> +<p>A Binary Tree consists of 3 parts: the node itself, pointer to the left child, pointer to the right child.</p> +<p>An In-Order Traversal is to access the leftmost child firstly, then the node itself, and finally the right child.</p> + + + + + + + + Hello World + https://mighten.github.io/2022/05/hello-world/ + Sun, 15 May 2022 19:28:07 +0800 + + https://mighten.github.io/2022/05/hello-world/ + + + + <p>Hello World!</p> +<p>This is my first blog post. Today, let's talk about writing a <code>Markdown</code> blog with <a href="https://gohugo.io/">Hugo</a>, and eventually deploying it on GitHub Pages.</p> +<p><code>Hugo</code> is a static HTML and CSS website generator, which allows us to concentrate on the contents rather than the layout tricks.</p> + + + + + + + + diff --git a/post/page/1/index.html b/post/page/1/index.html new file mode 100644 index 0000000..996d082 --- /dev/null +++ b/post/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/post/ \ No newline at end of file diff --git a/post/page/2/index.html b/post/page/2/index.html new file mode 100644 index 0000000..7f5eca6 --- /dev/null +++ b/post/page/2/index.html @@ -0,0 +1,619 @@ + + + + +Posts | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + Servlet +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + How to Sign Our Git Commits with GPG +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + DDIA Ch01: Reliable, Scalable, and Maintainable Applications +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Binary Tree NonRecursive InOrder +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Hello World +

    + + + +
    + +
    +
  • + + +
  • + +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/search/index.html b/search/index.html new file mode 100644 index 0000000..6a00b35 --- /dev/null +++ b/search/index.html @@ -0,0 +1,220 @@ + + + + +Search | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+
+ + + + + + + + diff --git a/series/algorithms/index.html b/series/algorithms/index.html new file mode 100644 index 0000000..faaac3f --- /dev/null +++ b/series/algorithms/index.html @@ -0,0 +1,451 @@ + + + + +Algorithms | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + Linked List +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Binary Tree NonRecursive InOrder +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/series/algorithms/index.xml b/series/algorithms/index.xml new file mode 100644 index 0000000..21f3d97 --- /dev/null +++ b/series/algorithms/index.xml @@ -0,0 +1,46 @@ + + + + Algorithms on Mighten's Blog + https://mighten.github.io/series/algorithms/ + Recent content in Algorithms on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Wed, 05 Apr 2023 22:22:00 +0800 + + Linked List + https://mighten.github.io/2023/04/linked-list/ + Wed, 05 Apr 2023 22:22:00 +0800 + + https://mighten.github.io/2023/04/linked-list/ + + + + <p>Today, let's talk about <strong>Linked List</strong> algorithms that are frequently used.</p> +<p>A Linked List is a <em>data structure</em> that stores data into a series of <em>connected nodes</em>, and thus it can be dynamically allocated. For each node, it contains 2 fields: the <code>val</code> that stores data, and the <code>next</code> that points to the next node.</p> + + + + + + + + Binary Tree NonRecursive InOrder + https://mighten.github.io/2022/05/binary-tree-nonrecursive-inorder/ + Mon, 16 May 2022 22:37:50 +0800 + + https://mighten.github.io/2022/05/binary-tree-nonrecursive-inorder/ + + + + <p>Hi there, let's talk about how to nonrecursively do a In-Order traversal for a Binary Tree.</p> +<p>A Binary Tree consists of 3 parts: the node itself, pointer to the left child, pointer to the right child.</p> +<p>An In-Order Traversal is to access the leftmost child firstly, then the node itself, and finally the right child.</p> + + + + + + + + diff --git a/series/algorithms/page/1/index.html b/series/algorithms/page/1/index.html new file mode 100644 index 0000000..6a70820 --- /dev/null +++ b/series/algorithms/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/series/algorithms/ \ No newline at end of file diff --git a/series/ddia/index.html b/series/ddia/index.html new file mode 100644 index 0000000..f6c0560 --- /dev/null +++ b/series/ddia/index.html @@ -0,0 +1,403 @@ + + + + +DDIA | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + DDIA Ch01: Reliable, Scalable, and Maintainable Applications +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/series/ddia/index.xml b/series/ddia/index.xml new file mode 100644 index 0000000..b8a9804 --- /dev/null +++ b/series/ddia/index.xml @@ -0,0 +1,29 @@ + + + + DDIA on Mighten's Blog + https://mighten.github.io/series/ddia/ + Recent content in DDIA on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Thu, 19 May 2022 22:06:00 +0800 + + DDIA Ch01: Reliable, Scalable, and Maintainable Applications + https://mighten.github.io/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/ + Thu, 19 May 2022 22:06:00 +0800 + + https://mighten.github.io/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/ + + + + <p>Hi!</p> +<p>Let's read the Chapter 01: <em>Reliable, Scalable, and Maintainable Applications</em> of <a href="https://dataintensive.net/"><em>Designing Data-Intensive Applications</em></a>.</p> +<p>It introduces the terminology and approach that we are going to use throughout the book, and it also explores some fundamental ways of thinking about <em><strong>data-intensive applications</strong></em>: general properties (nonfunctional requirements) such as <em><strong>reliability</strong></em>, <em><strong>scalability</strong></em>, and <em><strong>maintainability</strong></em>.</p> + + + + + + + + diff --git a/series/ddia/page/1/index.html b/series/ddia/page/1/index.html new file mode 100644 index 0000000..15471a6 --- /dev/null +++ b/series/ddia/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/series/ddia/ \ No newline at end of file diff --git a/series/index.html b/series/index.html new file mode 100644 index 0000000..606da4f --- /dev/null +++ b/series/index.html @@ -0,0 +1,579 @@ + + + + +Series | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + k8s-in-action +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Web +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Algorithms +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + DDIA +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/series/index.xml b/series/index.xml new file mode 100644 index 0000000..6e441b1 --- /dev/null +++ b/series/index.xml @@ -0,0 +1,11 @@ + + + + Series on Mighten's Blog + https://mighten.github.io/series/ + Recent content in Series on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Thu, 02 May 2024 17:15:00 +0800 + + diff --git a/series/k8s-in-action/index.html b/series/k8s-in-action/index.html new file mode 100644 index 0000000..f0627cf --- /dev/null +++ b/series/k8s-in-action/index.html @@ -0,0 +1,410 @@ + + + + +k8s-in-action | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + KIA CH01 Introducing Kubernetes +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/series/k8s-in-action/index.xml b/series/k8s-in-action/index.xml new file mode 100644 index 0000000..c39a4fe --- /dev/null +++ b/series/k8s-in-action/index.xml @@ -0,0 +1,34 @@ + + + + k8s-in-action on Mighten's Blog + https://mighten.github.io/series/k8s-in-action/ + Recent content in k8s-in-action on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Thu, 02 May 2024 17:15:00 +0800 + + KIA CH01 Introducing Kubernetes + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + Thu, 02 May 2024 17:15:00 +0800 + + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + + + + <p>Hi there.</p> +<p>Today, let us read the <em>Chapter 01: Introducing Kubernetes</em> of <strong>Kubernetes in Action</strong></p> +<ol> +<li>the history of software developing</li> +<li>isolation by containers</li> +<li>how containers and Docker are used by Kubernetes</li> +<li>how to simplify works by Kubernetes</li> +</ol> + + + + + + + + diff --git a/series/k8s-in-action/page/1/index.html b/series/k8s-in-action/page/1/index.html new file mode 100644 index 0000000..9e54eaf --- /dev/null +++ b/series/k8s-in-action/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/series/k8s-in-action/ \ No newline at end of file diff --git a/series/mit-6.033/index.html b/series/mit-6.033/index.html new file mode 100644 index 0000000..72525ca --- /dev/null +++ b/series/mit-6.033/index.html @@ -0,0 +1,555 @@ + + + + +MIT 6.033 | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + MIT 6.033 CSE Security +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Distributed Systems +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Networking +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Operating System +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/series/mit-6.033/index.xml b/series/mit-6.033/index.xml new file mode 100644 index 0000000..1a2abfc --- /dev/null +++ b/series/mit-6.033/index.xml @@ -0,0 +1,88 @@ + + + + MIT 6.033 on Mighten's Blog + https://mighten.github.io/series/mit-6.033/ + Recent content in MIT 6.033 on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Tue, 13 Jun 2023 09:00:00 +0800 + + MIT 6.033 CSE Security + https://mighten.github.io/2023/06/mit-6.033-cse-security/ + Tue, 13 Jun 2023 09:00:00 +0800 + + https://mighten.github.io/2023/06/mit-6.033-cse-security/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part IV: <em><strong>Security</strong></em>. And in this section, we mainly focus on <em><strong>common pitfalls</strong></em> in the security of computer systems, and how to <em>combat</em> them.</p> +<p>To build a secure system, we need to be clear about two aspects:</p> +<ol> +<li><em>security policy</em> (goal)</li> +<li><em>threat model</em> (assumptions on adversaries)</li> +</ol> + + + + + + + + MIT 6.033 CSE Distributed Systems + https://mighten.github.io/2023/06/mit-6.033-cse-distributed-systems/ + Tue, 06 Jun 2023 22:10:00 +0800 + + https://mighten.github.io/2023/06/mit-6.033-cse-distributed-systems/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part III: <em><strong>Distributed Systems</strong></em>. And in this section, we mainly focus on: How <em><strong>reliable, usable distributed systems</strong></em> are able to be built on top of an <em>unreliable</em> network.</p> + + + + + + + + MIT 6.033 CSE Networking + https://mighten.github.io/2023/05/mit-6.033-cse-networking/ + Tue, 30 May 2023 18:10:00 +0800 + + https://mighten.github.io/2023/05/mit-6.033-cse-networking/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part II: <em><strong>Networking</strong></em>. And in this section, we mainly focus on: how the <em><strong>Internet</strong></em> is designed to <em>scale</em> and its various applications.</p> + + + + + + + + MIT 6.033 CSE Operating System + https://mighten.github.io/2023/04/mit-6.033-cse-operating-system/ + Thu, 06 Apr 2023 15:06:00 +0800 + + https://mighten.github.io/2023/04/mit-6.033-cse-operating-system/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part I: <em><strong>Operating Systems</strong></em>. And in this section, we mainly focus on:</p> +<ul> +<li>How common <em>design patterns</em> in computer system — such as <em>abstraction</em> and <em>modularity</em> — are used to limit <em>complexity</em>.</li> +<li>How operating systems use <em>virtualization</em> and <em>abstraction</em> to enforce <em>modularity</em>.</li> +</ul> + + + + + + + + diff --git a/series/mit-6.033/page/1/index.html b/series/mit-6.033/page/1/index.html new file mode 100644 index 0000000..d7ae9b6 --- /dev/null +++ b/series/mit-6.033/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/series/mit-6.033/ \ No newline at end of file diff --git a/series/page/1/index.html b/series/page/1/index.html new file mode 100644 index 0000000..dad4f9a --- /dev/null +++ b/series/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/series/ \ No newline at end of file diff --git a/series/web/index.html b/series/web/index.html new file mode 100644 index 0000000..5ea3f0c --- /dev/null +++ b/series/web/index.html @@ -0,0 +1,460 @@ + + + + +Web | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + Spring Framework +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Servlet +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/series/web/index.xml b/series/web/index.xml new file mode 100644 index 0000000..ee04e07 --- /dev/null +++ b/series/web/index.xml @@ -0,0 +1,54 @@ + + + + Web on Mighten's Blog + https://mighten.github.io/series/web/ + Recent content in Web on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Wed, 19 Jul 2023 00:00:00 +0800 + + Spring Framework + https://mighten.github.io/2023/07/spring-framework/ + Wed, 19 Jul 2023 00:00:00 +0800 + + https://mighten.github.io/2023/07/spring-framework/ + + + + <p>Hi there!</p> +<p>In this blog, we talk about <em><strong>Spring Framework</strong></em>, a Java platform that provides comprehensive infrastructure support for developing Java applications. The content of this blog is shown below:</p> +<ul> +<li>Architecture</li> +<li><em>Spring IoC Container</em></li> +<li>Spring Beans</li> +<li><em>Dependency Injection (DI)</em></li> +<li>Spring Annotations</li> +<li><em>Aspect Oriented Programming (AOP)</em></li> +</ul> + + + + + + + + Servlet + https://mighten.github.io/2023/03/servlet/ + Thu, 30 Mar 2023 18:05:00 +0800 + + https://mighten.github.io/2023/03/servlet/ + + + + <p>Hi there, todaly let's talk about <strong>Servlet</strong> in a nutshell.</p> +<p>A <em>Servlet</em> is a <em>Java</em> programming language <em>class</em>, which is executed in <em>Web Server</em> and responsible for <em>dynamic</em> content generation in a portable way.</p> +<p><em>Servlet</em> extends the capabilities of servers that host applications accessed by means of a <em>request-response programming model</em>.</p> + + + + + + + + diff --git a/series/web/page/1/index.html b/series/web/page/1/index.html new file mode 100644 index 0000000..2544bf4 --- /dev/null +++ b/series/web/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/series/web/ \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml new file mode 100644 index 0000000..b3a3f7c --- /dev/null +++ b/sitemap.xml @@ -0,0 +1,111 @@ + + + + https://mighten.github.io/ + 2024-05-06T15:54:00+08:00 + + https://mighten.github.io/tags/cloud-native/ + 2024-05-06T15:54:00+08:00 + + https://mighten.github.io/tags/k8s/ + 2024-05-06T15:54:00+08:00 + + https://mighten.github.io/series/k8s-in-action/ + 2024-05-06T15:54:00+08:00 + + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + 2024-05-06T15:54:00+08:00 + + https://mighten.github.io/tags/kubernetes/ + 2024-05-06T15:54:00+08:00 + + https://mighten.github.io/post/ + 2024-05-06T15:54:00+08:00 + + https://mighten.github.io/series/ + 2024-05-06T15:54:00+08:00 + + https://mighten.github.io/tags/ + 2024-05-06T15:54:00+08:00 + + https://mighten.github.io/tags/java/ + 2023-07-19T00:00:00+08:00 + + https://mighten.github.io/tags/spring/ + 2023-07-19T00:00:00+08:00 + + https://mighten.github.io/2023/07/spring-framework/ + 2023-07-19T00:00:00+08:00 + + https://mighten.github.io/series/web/ + 2023-07-19T00:00:00+08:00 + + https://mighten.github.io/tags/devops/ + 2023-06-21T00:00:00+08:00 + + https://mighten.github.io/2023/06/maven/ + 2023-06-21T00:00:00+08:00 + + https://mighten.github.io/2023/06/docker/ + 2023-06-17T23:10:00+08:00 + + https://mighten.github.io/2023/06/putty-with-openssh/ + 2023-06-17T22:08:00+08:00 + + https://mighten.github.io/series/mit-6.033/ + 2023-06-13T09:00:00+08:00 + + https://mighten.github.io/2023/06/mit-6.033-cse-security/ + 2023-06-13T09:00:00+08:00 + + https://mighten.github.io/tags/system-design/ + 2023-06-13T09:00:00+08:00 + + https://mighten.github.io/2023/06/mit-6.033-cse-distributed-systems/ + 2023-06-06T22:10:00+08:00 + + https://mighten.github.io/2023/05/mit-6.033-cse-networking/ + 2023-05-30T18:10:00+08:00 + + https://mighten.github.io/2023/04/mit-6.033-cse-operating-system/ + 2023-04-06T15:06:00+08:00 + + https://mighten.github.io/tags/algorithm/ + 2023-04-05T22:22:00+08:00 + + https://mighten.github.io/series/algorithms/ + 2023-04-05T22:22:00+08:00 + + https://mighten.github.io/2023/04/linked-list/ + 2023-04-05T22:22:00+08:00 + + https://mighten.github.io/2023/03/servlet/ + 2023-03-30T18:05:00+08:00 + + https://mighten.github.io/2022/05/how-to-sign-our-git-commits-with-gpg/ + 2022-05-20T13:54:00+08:00 + + https://mighten.github.io/tags/misc/ + 2022-05-20T13:54:00+08:00 + + https://mighten.github.io/about/ + 2022-05-20T12:07:00+08:00 + + https://mighten.github.io/series/ddia/ + 2022-05-19T22:06:00+08:00 + + https://mighten.github.io/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/ + 2022-05-19T22:06:00+08:00 + + https://mighten.github.io/2022/05/binary-tree-nonrecursive-inorder/ + 2022-05-17T21:42:00+08:00 + + https://mighten.github.io/2022/05/hello-world/ + 2022-05-15T19:28:07+08:00 + + https://mighten.github.io/categories/ + + https://mighten.github.io/search/ + + diff --git a/tags/algorithm/index.html b/tags/algorithm/index.html new file mode 100644 index 0000000..8e2e4c0 --- /dev/null +++ b/tags/algorithm/index.html @@ -0,0 +1,451 @@ + + + + +Algorithm | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + Linked List +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Binary Tree NonRecursive InOrder +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/tags/algorithm/index.xml b/tags/algorithm/index.xml new file mode 100644 index 0000000..71a7854 --- /dev/null +++ b/tags/algorithm/index.xml @@ -0,0 +1,46 @@ + + + + Algorithm on Mighten's Blog + https://mighten.github.io/tags/algorithm/ + Recent content in Algorithm on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Wed, 05 Apr 2023 22:22:00 +0800 + + Linked List + https://mighten.github.io/2023/04/linked-list/ + Wed, 05 Apr 2023 22:22:00 +0800 + + https://mighten.github.io/2023/04/linked-list/ + + + + <p>Today, let's talk about <strong>Linked List</strong> algorithms that are frequently used.</p> +<p>A Linked List is a <em>data structure</em> that stores data into a series of <em>connected nodes</em>, and thus it can be dynamically allocated. For each node, it contains 2 fields: the <code>val</code> that stores data, and the <code>next</code> that points to the next node.</p> + + + + + + + + Binary Tree NonRecursive InOrder + https://mighten.github.io/2022/05/binary-tree-nonrecursive-inorder/ + Mon, 16 May 2022 22:37:50 +0800 + + https://mighten.github.io/2022/05/binary-tree-nonrecursive-inorder/ + + + + <p>Hi there, let's talk about how to nonrecursively do a In-Order traversal for a Binary Tree.</p> +<p>A Binary Tree consists of 3 parts: the node itself, pointer to the left child, pointer to the right child.</p> +<p>An In-Order Traversal is to access the leftmost child firstly, then the node itself, and finally the right child.</p> + + + + + + + + diff --git a/tags/algorithm/page/1/index.html b/tags/algorithm/page/1/index.html new file mode 100644 index 0000000..43cd108 --- /dev/null +++ b/tags/algorithm/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/tags/algorithm/ \ No newline at end of file diff --git a/tags/cloud-native/index.html b/tags/cloud-native/index.html new file mode 100644 index 0000000..45ff6e1 --- /dev/null +++ b/tags/cloud-native/index.html @@ -0,0 +1,410 @@ + + + + +Cloud-Native | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + KIA CH01 Introducing Kubernetes +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/tags/cloud-native/index.xml b/tags/cloud-native/index.xml new file mode 100644 index 0000000..276c83f --- /dev/null +++ b/tags/cloud-native/index.xml @@ -0,0 +1,34 @@ + + + + Cloud-Native on Mighten's Blog + https://mighten.github.io/tags/cloud-native/ + Recent content in Cloud-Native on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Thu, 02 May 2024 17:15:00 +0800 + + KIA CH01 Introducing Kubernetes + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + Thu, 02 May 2024 17:15:00 +0800 + + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + + + + <p>Hi there.</p> +<p>Today, let us read the <em>Chapter 01: Introducing Kubernetes</em> of <strong>Kubernetes in Action</strong></p> +<ol> +<li>the history of software developing</li> +<li>isolation by containers</li> +<li>how containers and Docker are used by Kubernetes</li> +<li>how to simplify works by Kubernetes</li> +</ol> + + + + + + + + diff --git a/tags/cloud-native/page/1/index.html b/tags/cloud-native/page/1/index.html new file mode 100644 index 0000000..f35d656 --- /dev/null +++ b/tags/cloud-native/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/tags/cloud-native/ \ No newline at end of file diff --git a/tags/devops/index.html b/tags/devops/index.html new file mode 100644 index 0000000..20a0c2a --- /dev/null +++ b/tags/devops/index.html @@ -0,0 +1,500 @@ + + + + +DevOps | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + Maven +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Docker +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + PuTTY with OpenSSH +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/tags/devops/index.xml b/tags/devops/index.xml new file mode 100644 index 0000000..5145a70 --- /dev/null +++ b/tags/devops/index.xml @@ -0,0 +1,64 @@ + + + + DevOps on Mighten's Blog + https://mighten.github.io/tags/devops/ + Recent content in DevOps on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Wed, 21 Jun 2023 00:00:00 +0800 + + Maven + https://mighten.github.io/2023/06/maven/ + Wed, 21 Jun 2023 00:00:00 +0800 + + https://mighten.github.io/2023/06/maven/ + + + + <p><em><strong>Maven</strong></em> is a <em>project management tool</em> that is based on <em>POM</em> (<em>project object model</em>). It is used for <strong>projects build</strong>, <strong>dependency</strong> and <strong>documentation</strong>.</p> + + + + + + + + Docker + https://mighten.github.io/2023/06/docker/ + Sat, 17 Jun 2023 23:10:00 +0800 + + https://mighten.github.io/2023/06/docker/ + + + + ***Docker*** is a platform for *developing*, *shipping*, and *deploying* applications quickly in **portable, self-sufficient containers**, and is used in the **Continuous Deployment (CD)** stage of the **DevOps** ecosystem. + + + + + + + + PuTTY with OpenSSH + https://mighten.github.io/2023/06/putty-with-openssh/ + Sat, 17 Jun 2023 22:08:00 +0800 + + https://mighten.github.io/2023/06/putty-with-openssh/ + + + + <p>Hi!</p> +<p>Today we use <em><strong>OpenSSH</strong></em> and <em><strong>PuTTY</strong></em> to log in remote computers.</p> +<ul> +<li><a href="https://www.openssh.com/"><strong>OpenSSH</strong></a> is an open-source version of the <em>Secure Shell</em> (SSH) tools used by administrators of remote systems</li> +<li><a href="https://www.chiark.greenend.org.uk/~sgtatham/putty/"><em><strong>PuTTY</strong></em></a> is a free implementation of <em>SSH</em></li> +</ul> + + + + + + + + diff --git a/tags/devops/page/1/index.html b/tags/devops/page/1/index.html new file mode 100644 index 0000000..eaac53b --- /dev/null +++ b/tags/devops/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/tags/devops/ \ No newline at end of file diff --git a/tags/index.html b/tags/index.html new file mode 100644 index 0000000..8a75ffa --- /dev/null +++ b/tags/index.html @@ -0,0 +1,759 @@ + + + + +Tags | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + Cloud-Native +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + k8s +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Kubernetes +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Java +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Spring +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + DevOps +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + System Design +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Algorithm +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Misc +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/tags/index.xml b/tags/index.xml new file mode 100644 index 0000000..eecd697 --- /dev/null +++ b/tags/index.xml @@ -0,0 +1,11 @@ + + + + Tags on Mighten's Blog + https://mighten.github.io/tags/ + Recent content in Tags on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Thu, 02 May 2024 17:15:00 +0800 + + diff --git a/tags/java/index.html b/tags/java/index.html new file mode 100644 index 0000000..d3e6bdd --- /dev/null +++ b/tags/java/index.html @@ -0,0 +1,460 @@ + + + + +Java | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + Spring Framework +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Servlet +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/tags/java/index.xml b/tags/java/index.xml new file mode 100644 index 0000000..5e8b807 --- /dev/null +++ b/tags/java/index.xml @@ -0,0 +1,54 @@ + + + + Java on Mighten's Blog + https://mighten.github.io/tags/java/ + Recent content in Java on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Wed, 19 Jul 2023 00:00:00 +0800 + + Spring Framework + https://mighten.github.io/2023/07/spring-framework/ + Wed, 19 Jul 2023 00:00:00 +0800 + + https://mighten.github.io/2023/07/spring-framework/ + + + + <p>Hi there!</p> +<p>In this blog, we talk about <em><strong>Spring Framework</strong></em>, a Java platform that provides comprehensive infrastructure support for developing Java applications. The content of this blog is shown below:</p> +<ul> +<li>Architecture</li> +<li><em>Spring IoC Container</em></li> +<li>Spring Beans</li> +<li><em>Dependency Injection (DI)</em></li> +<li>Spring Annotations</li> +<li><em>Aspect Oriented Programming (AOP)</em></li> +</ul> + + + + + + + + Servlet + https://mighten.github.io/2023/03/servlet/ + Thu, 30 Mar 2023 18:05:00 +0800 + + https://mighten.github.io/2023/03/servlet/ + + + + <p>Hi there, todaly let's talk about <strong>Servlet</strong> in a nutshell.</p> +<p>A <em>Servlet</em> is a <em>Java</em> programming language <em>class</em>, which is executed in <em>Web Server</em> and responsible for <em>dynamic</em> content generation in a portable way.</p> +<p><em>Servlet</em> extends the capabilities of servers that host applications accessed by means of a <em>request-response programming model</em>.</p> + + + + + + + + diff --git a/tags/java/page/1/index.html b/tags/java/page/1/index.html new file mode 100644 index 0000000..b0fd62d --- /dev/null +++ b/tags/java/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/tags/java/ \ No newline at end of file diff --git a/tags/k8s/index.html b/tags/k8s/index.html new file mode 100644 index 0000000..608863d --- /dev/null +++ b/tags/k8s/index.html @@ -0,0 +1,410 @@ + + + + +k8s | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + KIA CH01 Introducing Kubernetes +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/tags/k8s/index.xml b/tags/k8s/index.xml new file mode 100644 index 0000000..50a6559 --- /dev/null +++ b/tags/k8s/index.xml @@ -0,0 +1,34 @@ + + + + k8s on Mighten's Blog + https://mighten.github.io/tags/k8s/ + Recent content in k8s on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Thu, 02 May 2024 17:15:00 +0800 + + KIA CH01 Introducing Kubernetes + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + Thu, 02 May 2024 17:15:00 +0800 + + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + + + + <p>Hi there.</p> +<p>Today, let us read the <em>Chapter 01: Introducing Kubernetes</em> of <strong>Kubernetes in Action</strong></p> +<ol> +<li>the history of software developing</li> +<li>isolation by containers</li> +<li>how containers and Docker are used by Kubernetes</li> +<li>how to simplify works by Kubernetes</li> +</ol> + + + + + + + + diff --git a/tags/k8s/page/1/index.html b/tags/k8s/page/1/index.html new file mode 100644 index 0000000..1757c02 --- /dev/null +++ b/tags/k8s/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/tags/k8s/ \ No newline at end of file diff --git a/tags/kubernetes/index.html b/tags/kubernetes/index.html new file mode 100644 index 0000000..036c5c8 --- /dev/null +++ b/tags/kubernetes/index.html @@ -0,0 +1,410 @@ + + + + +Kubernetes | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + KIA CH01 Introducing Kubernetes +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/tags/kubernetes/index.xml b/tags/kubernetes/index.xml new file mode 100644 index 0000000..f91dd65 --- /dev/null +++ b/tags/kubernetes/index.xml @@ -0,0 +1,34 @@ + + + + Kubernetes on Mighten's Blog + https://mighten.github.io/tags/kubernetes/ + Recent content in Kubernetes on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Thu, 02 May 2024 17:15:00 +0800 + + KIA CH01 Introducing Kubernetes + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + Thu, 02 May 2024 17:15:00 +0800 + + https://mighten.github.io/2024/05/kia-ch01-introducing-kubernetes/ + + + + <p>Hi there.</p> +<p>Today, let us read the <em>Chapter 01: Introducing Kubernetes</em> of <strong>Kubernetes in Action</strong></p> +<ol> +<li>the history of software developing</li> +<li>isolation by containers</li> +<li>how containers and Docker are used by Kubernetes</li> +<li>how to simplify works by Kubernetes</li> +</ol> + + + + + + + + diff --git a/tags/kubernetes/page/1/index.html b/tags/kubernetes/page/1/index.html new file mode 100644 index 0000000..2154036 --- /dev/null +++ b/tags/kubernetes/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/tags/kubernetes/ \ No newline at end of file diff --git a/tags/misc/index.html b/tags/misc/index.html new file mode 100644 index 0000000..1c1b59b --- /dev/null +++ b/tags/misc/index.html @@ -0,0 +1,452 @@ + + + + +Misc | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + How to Sign Our Git Commits with GPG +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + Hello World +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/tags/misc/index.xml b/tags/misc/index.xml new file mode 100644 index 0000000..6aeda07 --- /dev/null +++ b/tags/misc/index.xml @@ -0,0 +1,47 @@ + + + + Misc on Mighten's Blog + https://mighten.github.io/tags/misc/ + Recent content in Misc on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Fri, 20 May 2022 13:54:00 +0800 + + How to Sign Our Git Commits with GPG + https://mighten.github.io/2022/05/how-to-sign-our-git-commits-with-gpg/ + Fri, 20 May 2022 13:54:00 +0800 + + https://mighten.github.io/2022/05/how-to-sign-our-git-commits-with-gpg/ + + + + <p>Hello!</p> +<p>Today, let's talk about signing a <em>git commit</em> with <a href="https://gnupg.org/">GPG</a>, an encryption engine for signing and signature verification.</p> +<p>When it comes to work across the Internet, it's recommended that we add a cryptographic signature to our commit, which provides some sort of assurance that a commit is originated from us, rather than from an impersonator.</p> + + + + + + + + Hello World + https://mighten.github.io/2022/05/hello-world/ + Sun, 15 May 2022 19:28:07 +0800 + + https://mighten.github.io/2022/05/hello-world/ + + + + <p>Hello World!</p> +<p>This is my first blog post. Today, let's talk about writing a <code>Markdown</code> blog with <a href="https://gohugo.io/">Hugo</a>, and eventually deploying it on GitHub Pages.</p> +<p><code>Hugo</code> is a static HTML and CSS website generator, which allows us to concentrate on the contents rather than the layout tricks.</p> + + + + + + + + diff --git a/tags/misc/page/1/index.html b/tags/misc/page/1/index.html new file mode 100644 index 0000000..94050d8 --- /dev/null +++ b/tags/misc/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/tags/misc/ \ No newline at end of file diff --git a/tags/page/1/index.html b/tags/page/1/index.html new file mode 100644 index 0000000..3492a0e --- /dev/null +++ b/tags/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/tags/ \ No newline at end of file diff --git a/tags/spring/index.html b/tags/spring/index.html new file mode 100644 index 0000000..a7ed528 --- /dev/null +++ b/tags/spring/index.html @@ -0,0 +1,411 @@ + + + + +Spring | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + Spring Framework +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/tags/spring/index.xml b/tags/spring/index.xml new file mode 100644 index 0000000..d6ca34f --- /dev/null +++ b/tags/spring/index.xml @@ -0,0 +1,36 @@ + + + + Spring on Mighten's Blog + https://mighten.github.io/tags/spring/ + Recent content in Spring on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Wed, 19 Jul 2023 00:00:00 +0800 + + Spring Framework + https://mighten.github.io/2023/07/spring-framework/ + Wed, 19 Jul 2023 00:00:00 +0800 + + https://mighten.github.io/2023/07/spring-framework/ + + + + <p>Hi there!</p> +<p>In this blog, we talk about <em><strong>Spring Framework</strong></em>, a Java platform that provides comprehensive infrastructure support for developing Java applications. The content of this blog is shown below:</p> +<ul> +<li>Architecture</li> +<li><em>Spring IoC Container</em></li> +<li>Spring Beans</li> +<li><em>Dependency Injection (DI)</em></li> +<li>Spring Annotations</li> +<li><em>Aspect Oriented Programming (AOP)</em></li> +</ul> + + + + + + + + diff --git a/tags/spring/page/1/index.html b/tags/spring/page/1/index.html new file mode 100644 index 0000000..095fa23 --- /dev/null +++ b/tags/spring/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/tags/spring/ \ No newline at end of file diff --git a/tags/system-design/index.html b/tags/system-design/index.html new file mode 100644 index 0000000..8b9d31f --- /dev/null +++ b/tags/system-design/index.html @@ -0,0 +1,604 @@ + + + + +System Design | Mighten's Blog + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
+
+
    +
  • +
    +
    +

    + MIT 6.033 CSE Security +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Distributed Systems +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Networking +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + MIT 6.033 CSE Operating System +

    + + + +
    + +
    +
  • + + +
  • +
    +
    +

    + DDIA Ch01: Reliable, Scalable, and Maintainable Applications +

    + + + +
    + +
    +
  • + + +
  • +
  • +
+
+ + +
+ + +
+ + + + + + + + diff --git a/tags/system-design/index.xml b/tags/system-design/index.xml new file mode 100644 index 0000000..b76a621 --- /dev/null +++ b/tags/system-design/index.xml @@ -0,0 +1,106 @@ + + + + System Design on Mighten's Blog + https://mighten.github.io/tags/system-design/ + Recent content in System Design on Mighten's Blog + Hugo -- gohugo.io + Mighten Dai + Tue, 13 Jun 2023 09:00:00 +0800 + + MIT 6.033 CSE Security + https://mighten.github.io/2023/06/mit-6.033-cse-security/ + Tue, 13 Jun 2023 09:00:00 +0800 + + https://mighten.github.io/2023/06/mit-6.033-cse-security/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part IV: <em><strong>Security</strong></em>. And in this section, we mainly focus on <em><strong>common pitfalls</strong></em> in the security of computer systems, and how to <em>combat</em> them.</p> +<p>To build a secure system, we need to be clear about two aspects:</p> +<ol> +<li><em>security policy</em> (goal)</li> +<li><em>threat model</em> (assumptions on adversaries)</li> +</ol> + + + + + + + + MIT 6.033 CSE Distributed Systems + https://mighten.github.io/2023/06/mit-6.033-cse-distributed-systems/ + Tue, 06 Jun 2023 22:10:00 +0800 + + https://mighten.github.io/2023/06/mit-6.033-cse-distributed-systems/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part III: <em><strong>Distributed Systems</strong></em>. And in this section, we mainly focus on: How <em><strong>reliable, usable distributed systems</strong></em> are able to be built on top of an <em>unreliable</em> network.</p> + + + + + + + + MIT 6.033 CSE Networking + https://mighten.github.io/2023/05/mit-6.033-cse-networking/ + Tue, 30 May 2023 18:10:00 +0800 + + https://mighten.github.io/2023/05/mit-6.033-cse-networking/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part II: <em><strong>Networking</strong></em>. And in this section, we mainly focus on: how the <em><strong>Internet</strong></em> is designed to <em>scale</em> and its various applications.</p> + + + + + + + + MIT 6.033 CSE Operating System + https://mighten.github.io/2023/04/mit-6.033-cse-operating-system/ + Thu, 06 Apr 2023 15:06:00 +0800 + + https://mighten.github.io/2023/04/mit-6.033-cse-operating-system/ + + + + <p><a href="https://ocw.mit.edu/courses/6-033-computer-system-engineering-spring-2018/">MIT 6.033</a> (<em>Computer System Engineering</em>) covers 4 parts: <em>Operating Systems</em>, <em>Networking</em>, <em>Distributed Systems</em>, and <em>Security</em>.</p> +<p>This is the course note for Part I: <em><strong>Operating Systems</strong></em>. And in this section, we mainly focus on:</p> +<ul> +<li>How common <em>design patterns</em> in computer system — such as <em>abstraction</em> and <em>modularity</em> — are used to limit <em>complexity</em>.</li> +<li>How operating systems use <em>virtualization</em> and <em>abstraction</em> to enforce <em>modularity</em>.</li> +</ul> + + + + + + + + DDIA Ch01: Reliable, Scalable, and Maintainable Applications + https://mighten.github.io/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/ + Thu, 19 May 2022 22:06:00 +0800 + + https://mighten.github.io/2022/05/ddia-ch01-reliable-scalable-and-maintainable-applications/ + + + + <p>Hi!</p> +<p>Let's read the Chapter 01: <em>Reliable, Scalable, and Maintainable Applications</em> of <a href="https://dataintensive.net/"><em>Designing Data-Intensive Applications</em></a>.</p> +<p>It introduces the terminology and approach that we are going to use throughout the book, and it also explores some fundamental ways of thinking about <em><strong>data-intensive applications</strong></em>: general properties (nonfunctional requirements) such as <em><strong>reliability</strong></em>, <em><strong>scalability</strong></em>, and <em><strong>maintainability</strong></em>.</p> + + + + + + + + diff --git a/tags/system-design/page/1/index.html b/tags/system-design/page/1/index.html new file mode 100644 index 0000000..9e8fa04 --- /dev/null +++ b/tags/system-design/page/1/index.html @@ -0,0 +1 @@ +https://mighten.github.io/tags/system-design/ \ No newline at end of file