├── Backbone ├── 6.TBD.md ├── 2.Spring Boot.md ├── 3.Spring MVC.md ├── 4.Spring Data.md ├── 5.Spring Security.md └── 1.Basics.md ├── Spring MVC ├── Controller Interface.md ├── Spring MVC.md ├── Service.md ├── Servlets and Controllers.md └── Rest Controller.md ├── .obsidian ├── appearance.json ├── community-plugins.json ├── app.json ├── plugins │ └── obsidian-git │ │ ├── manifest.json │ │ ├── data.json │ │ └── styles.css ├── hotkeys.json ├── core-plugins.json ├── graph.json └── workspace ├── Infrastructure and DevOps ├── Logging.md ├── Swagger.md ├── Infrastructure and DevOps.md └── Spring Actuator.md ├── Images ├── Salt.png ├── Pepper.png ├── FiltersServlets.png ├── MongoDB_Queries.webp └── MongoDB_Queries_Table.png ├── Spring Data ├── Repository Types.md ├── Spring Data JPA │ ├── Databases │ │ ├── H2 Database.md │ │ └── Apache Derby.md │ ├── JPA Relations.md │ ├── JPA Overview.md │ ├── Spring Data JPA.md │ ├── Entity.md │ ├── Repository Usage.md │ └── Connecting to Database with JPA.md ├── Spring Data.md ├── Spring Data JDBC │ └── Spring Data JDBC.md ├── Spring Data MongoDB │ ├── Spring Data MongoDB vs Spring Data JPA.md │ ├── Creating a MongoDB instance.md │ ├── Spring Data MongoDB.md │ ├── MongoRepository.md │ ├── Connecting to MongoDB.md │ ├── Getting Data from MongoDB.md │ └── MongoDB Queries.md ├── JPA Repository.md ├── CRUD Repository.md └── PagingAndSortingRepository.md ├── Basics ├── Basics.md ├── Dependency Injection.md ├── Bean Scopes.md ├── Lifecycle Callbacks.md ├── Application Context.md ├── Autowiring.md ├── Event Handling.md └── Beans.md ├── TBD └── TODO-List.md ├── Spring Security ├── LDAP │ ├── Spring Security LDAP.md │ └── LDAP Protocoll.md ├── Implementing Authentication.md ├── Reference Controller.md ├── Passwords │ ├── Password Hashing Concepts.md │ └── Password Encryprion.md ├── Default User and Password.md ├── Spring Security.md ├── Basic concepts.md ├── Implementing Authorization.md ├── Authentication │ ├── Hardcoding the Users.md │ ├── Configuring the Users with DataSource.md │ └── Configuring the Users with UserDetailsService.md ├── Default User Schema.md └── Filters.md ├── README.md ├── Side Notes.md ├── Introduction.md ├── Playlists.md ├── Spring Boot ├── CommandLineRunner.md ├── Spring Boot.md ├── Starting an application.md ├── SpringBootApplication.md └── Application Properies.md └── LICENSE /Backbone/6.TBD.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Spring MVC/Controller Interface.md: -------------------------------------------------------------------------------- 1 | TODO -------------------------------------------------------------------------------- /.obsidian/appearance.json: -------------------------------------------------------------------------------- 1 | { 2 | "baseFontSize": 18 3 | } -------------------------------------------------------------------------------- /.obsidian/community-plugins.json: -------------------------------------------------------------------------------- 1 | [ 2 | "obsidian-git" 3 | ] -------------------------------------------------------------------------------- /Infrastructure and DevOps/Logging.md: -------------------------------------------------------------------------------- 1 | TBD 2 | 3 | https://www.youtube.com/watch?v=lGrcZsw-hKQ -------------------------------------------------------------------------------- /Infrastructure and DevOps/Swagger.md: -------------------------------------------------------------------------------- 1 | TBD 2 | 3 | https://www.youtube.com/watch?v=gduKpLW_vdY -------------------------------------------------------------------------------- /Backbone/2.Spring Boot.md: -------------------------------------------------------------------------------- 1 | [[Spring Boot]]. 2 | 3 | Then go to [[3.Spring MVC]] 4 | 5 | #backbone -------------------------------------------------------------------------------- /Backbone/3.Spring MVC.md: -------------------------------------------------------------------------------- 1 | [[Spring MVC]] 2 | 3 | Then go to [[4.Spring Data]] 4 | 5 | #backbone -------------------------------------------------------------------------------- /Backbone/4.Spring Data.md: -------------------------------------------------------------------------------- 1 | [[Spring Data]] 2 | 3 | Then go to [[5.Spring Security]] 4 | 5 | #backbone -------------------------------------------------------------------------------- /Backbone/5.Spring Security.md: -------------------------------------------------------------------------------- 1 | [[Spring Security]] 2 | 3 | Then go to [[6.TBD]] 4 | 5 | #backbone 6 | -------------------------------------------------------------------------------- /Images/Salt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ValeriiZhyla/spring_learning_notes/HEAD/Images/Salt.png -------------------------------------------------------------------------------- /Images/Pepper.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ValeriiZhyla/spring_learning_notes/HEAD/Images/Pepper.png -------------------------------------------------------------------------------- /Infrastructure and DevOps/Infrastructure and DevOps.md: -------------------------------------------------------------------------------- 1 | [[Spring Actuator]] 2 | [[Swagger]] 3 | [[Logging]] -------------------------------------------------------------------------------- /Images/FiltersServlets.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ValeriiZhyla/spring_learning_notes/HEAD/Images/FiltersServlets.png -------------------------------------------------------------------------------- /Images/MongoDB_Queries.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ValeriiZhyla/spring_learning_notes/HEAD/Images/MongoDB_Queries.webp -------------------------------------------------------------------------------- /Images/MongoDB_Queries_Table.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ValeriiZhyla/spring_learning_notes/HEAD/Images/MongoDB_Queries_Table.png -------------------------------------------------------------------------------- /.obsidian/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "legacyEditor": false, 3 | "livePreview": false, 4 | "newFileLocation": "current", 5 | "alwaysUpdateLinks": true 6 | } -------------------------------------------------------------------------------- /Spring Data/Repository Types.md: -------------------------------------------------------------------------------- 1 | [[CRUD Repository]] 2 | [[PagingAndSortingRepository]] 3 | [[JPA Repository]] 4 | 5 | Documentation and comparison: https://www.baeldung.com/spring-data-repositories 6 | -------------------------------------------------------------------------------- /Basics/Basics.md: -------------------------------------------------------------------------------- 1 | There are several important concepts, that are implemented in Spring Framework: 2 | - [[Dependency Injection]] 3 | - [[Beans]] 4 | - [[Application Context]] 5 | - [[Autowiring]] 6 | - [[Event Handling]] -------------------------------------------------------------------------------- /.obsidian/plugins/obsidian-git/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "obsidian-git", 3 | "name": "Obsidian Git", 4 | "description": "Backup your vault with git.", 5 | "isDesktopOnly": true, 6 | "js": "main.js", 7 | "version": "1.24.0" 8 | } 9 | -------------------------------------------------------------------------------- /.obsidian/hotkeys.json: -------------------------------------------------------------------------------- 1 | { 2 | "obsidian-git:commit": [ 3 | { 4 | "modifiers": [ 5 | "Alt" 6 | ], 7 | "key": "F1" 8 | } 9 | ], 10 | "obsidian-git:push2": [ 11 | { 12 | "modifiers": [ 13 | "Alt" 14 | ], 15 | "key": "F2" 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /Infrastructure and DevOps/Spring Actuator.md: -------------------------------------------------------------------------------- 1 | "Mini-Prometeus", that can added as dependency. Actuator generates the endpoint /health, that give us the information about application status, ressources, database etc. 2 | 3 | Link: https://www.youtube.com/watch?v=ojc_Jy_0EgI&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=33 -------------------------------------------------------------------------------- /Spring Data/Spring Data JPA/Databases/H2 Database.md: -------------------------------------------------------------------------------- 1 | ### Spring Boot Default H2 Database Settings 2 | JDBC URL: jdbc:h2:mem:testdb 3 | User Name: sa 4 | Password: \[blank\] 5 | 6 | ```properties 7 | spring.jpa.defer-datasource-initialization=true 8 | 9 | spring.jpa.hibernate.ddl-auto=update 10 | ``` 11 | -------------------------------------------------------------------------------- /Spring Data/Spring Data.md: -------------------------------------------------------------------------------- 1 | Spring Data is a family of frameworks that are used for interaction with databases. 2 | 3 | Frameworks: 4 | [[Spring Data JDBC]] 5 | [[Spring Data JPA]] 6 | [[Spring Data MongoDB]] 7 | 8 | Basics: 9 | [[Repository Types]] 10 | 11 | Documentation: https://spring.io/projects/spring-data -------------------------------------------------------------------------------- /.obsidian/core-plugins.json: -------------------------------------------------------------------------------- 1 | [ 2 | "file-explorer", 3 | "global-search", 4 | "switcher", 5 | "graph", 6 | "backlink", 7 | "page-preview", 8 | "note-composer", 9 | "command-palette", 10 | "editor-status", 11 | "markdown-importer", 12 | "word-count", 13 | "open-with-default-app", 14 | "file-recovery" 15 | ] -------------------------------------------------------------------------------- /TBD/TODO-List.md: -------------------------------------------------------------------------------- 1 | How to test spring applications? 2 | 3 | Spring Security 4 | 5 | Swagger configuration and usage 6 | 7 | Logging 8 | 9 | Spring Data Rest 10 | 11 | 12 | Spring Data with JDBC, not JPA 13 | 14 | Spring Security: OAuth usage 15 | 16 | 17 | @GeneratedValue(strategy = GenerationType.AUTO) (and other strategies) 18 | 19 | -------------------------------------------------------------------------------- /Spring Data/Spring Data JDBC/Spring Data JDBC.md: -------------------------------------------------------------------------------- 1 | Simplest way to communicate with database. Spring Data JDBC is an Spring wrapper for Java JDBC. We can execute normal queries, create statements, work with result sets etc. 2 | 3 | Most of Spring Data JPA content is built on Spring Data JDBC. 4 | 5 | Documentation: https://spring.io/projects/spring-data-jdbc -------------------------------------------------------------------------------- /Spring Security/LDAP/Spring Security LDAP.md: -------------------------------------------------------------------------------- 1 | Dependencies: 2 | - Spring Web 3 | - Spring Security 4 | - Spring LDAP 5 | - Embedded LDAP Server 6 | 7 | 8 | [[LDAP Protocoll]] 9 | 10 | Guide: https://spring.io/guides/gs/authenticating-ldap/ 11 | 12 | Video: https://www.youtube.com/watch?v=-wDUChgvYgU&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE&index=9 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring_learning_notes 2 | This repository contains my Obsidian notes about learning process of Spring Framework. 3 | 4 | Content: 5 | - Basics 6 | - Spring Boot 7 | - Spring MVC 8 | - Spring Data (JDBC, JPA, MongoDB) 9 | - Spring Security 10 | - TBD 11 | 12 | How to use these notes: start with Introduction.md, and then follow \#backbone 13 | 14 | -------------------------------------------------------------------------------- /Spring Security/Implementing Authentication.md: -------------------------------------------------------------------------------- 1 | There are two ways to implement authentication. 2 | 3 | At first, we can do it directly with some Database. In this case we can use only a plain JDBC: [[Configuring the Users with DataSource]] 4 | 5 | Or we can add one more abstraction layer, for example, for the JPA usage: [[Configuring the Users with UserDetailsService]] -------------------------------------------------------------------------------- /Spring Data/Spring Data JPA/JPA Relations.md: -------------------------------------------------------------------------------- 1 | There are four types of relations in JPA: 2 | - _@ManyToOne_ Relation (Many people can have the same address) 3 | - _@OneToMany_ Relation (One address can be own by many people) 4 | - _@OneToOne_ Relation (One man can have only one tax identifier) 5 | - _@ManyToMany_ Relation (Employee can have many projects, each project can have many employees) -------------------------------------------------------------------------------- /Basics/Dependency Injection.md: -------------------------------------------------------------------------------- 1 | Idea: Dependency Injection works like singletons that are initialized at application startup, and connected via annotations. 2 | 3 | Video with good explanation of dependency injection: https://www.youtube.com/watch?v=GB8k2-Egfv0&list=PLC97BDEFDCDD169D7 4 | 5 | The spring containers, called [[Beans]] can be injected in other objects. This can be done with [[Autowiring]]. -------------------------------------------------------------------------------- /Side Notes.md: -------------------------------------------------------------------------------- 1 | - Spring Documentation: https://docs.spring.io/spring-framework/docs/current/reference/html/ 2 | 3 | - Community documentation: https://www.baeldung.com/ 4 | 5 | - Spring Initializr: https://start.spring.io/ 6 | 7 | - Obsidian guide: https://www.youtube.com/watch?v=47hOfPGsrqk 8 | 9 | - Markdown CheatSheet: https://www.markdownguide.org/cheat-sheet/ 10 | 11 | - Postman: https://www.postman.com/ -------------------------------------------------------------------------------- /Introduction.md: -------------------------------------------------------------------------------- 1 | 2 | [[1.Basics]] - Get the motivation and idea about Spring. Installation of framework, configuration of environment, application fields, essential concepts. 3 | [[Playlists]] - All the playlists, that i liked during this learning 4 | [[Side Notes]] - Information, that is not directly related with spring, but is interesting in context of backend 5 | 6 | 7 | Follow the #backbone tag to see the structure of notes. 8 | 9 | #start 10 | -------------------------------------------------------------------------------- /Spring Security/Reference Controller.md: -------------------------------------------------------------------------------- 1 | ## Simple Controller 2 | ```java 3 | @RestController 4 | public class HomeResource { 5 | 6 | @GetMapping("/") 7 | public String home() { 8 | return "Welcome"; 9 | } 10 | 11 | @GetMapping("/user") 12 | public String homeUser() { 13 | return "Welcome User"; 14 | } 15 | 16 | @GetMapping("/admin") 17 | public String homeAdmin() { 18 | return "Welcome Admin"; 19 | } 20 | } 21 | ``` -------------------------------------------------------------------------------- /Spring MVC/Spring MVC.md: -------------------------------------------------------------------------------- 1 | Idea: handle http the requests, react on them, perform some actions and return some response. Key element of Spring MVC is a Controller 2 | 3 | I'll use Spring project with Spring Web package. 4 | 5 | I'll run the application at localhost:8080, and perform endpoint tests with Postman. 6 | 7 | [[Service]] 8 | [[Rest Controller]] 9 | [[Controller Interface]] 10 | 11 | 12 | https://www.youtube.com/watch?v=xkDBaldNki4&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=15 -------------------------------------------------------------------------------- /Playlists.md: -------------------------------------------------------------------------------- 1 | - Spring Basics. Tutorial about essentials. This one is quite old, but it will be used only for understanding some concepts from original Spring: https://www.youtube.com/playlist?list=PLC97BDEFDCDD169D7 2 | 3 | - Spring Boot, Spring MVC, Spring Data JPA. Nice, popular and modern playlist about basics. All videos will be used: https://www.youtube.com/playlist?list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x 4 | 5 | - Spring Security: https://www.youtube.com/watch?v=sm-8qfMWEV8&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE -------------------------------------------------------------------------------- /Spring Data/Spring Data MongoDB/Spring Data MongoDB vs Spring Data JPA.md: -------------------------------------------------------------------------------- 1 | Spring Data JPA can be used for all database types in principle, but it performs good and convenient only with relational databases (normal SQL databases). 2 | 3 | Spring Data MongoDB is constructed specially for MongoDB NoSQL database. It allows the usage of full functionality of MongoDB, and not "adhoc adapting for NoSQL" of Spring Data JPA. 4 | 5 | There ale also specialised frameworks for another NoSQL databases, like Spring Data for Apache Cassandra. -------------------------------------------------------------------------------- /Backbone/1.Basics.md: -------------------------------------------------------------------------------- 1 | Getting Started: 2 | - Motivation and idea of Spring: https://www.youtube.com/watch?v=gq4S-ovWVlM 3 | - Spring Getting Started: https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started.html 4 | - You can build your Spring scaffold here: https://start.spring.io/ 5 | - I'll use Spring 2.6.5 with Maven and Java 11. 6 | 7 | Concepts of Spring Framework, that are important for further learning of the framework: [[Basics]] 8 | 9 | After these concepts we move to [[2.Spring Boot]] 10 | 11 | #backbone -------------------------------------------------------------------------------- /Spring Boot/CommandLineRunner.md: -------------------------------------------------------------------------------- 1 | You can implement the CommandLineRunner interface, if you want to use the Spring application as "normal" Java application, that can be started via command line with some arguments . 2 | 3 | ```java 4 | @SpringBootApplication 5 | public class CmdApplication implements CommandLineRunner { 6 | 7 | public static void main(String[] args) { 8 | SpringApplication.run(CmdApplication.class, args); 9 | } 10 | 11 | @Override 12 | public void run(String... args) { 13 | //your code 14 | } 15 | } 16 | ``` -------------------------------------------------------------------------------- /Spring Data/Spring Data JPA/Databases/Apache Derby.md: -------------------------------------------------------------------------------- 1 | Small embedded database, that can be used for development, before the remote database server is available. It is configured by spring automatically. 2 | 3 | Wonderful tool to start the project or for learning purpose, if we don't need any production database. It can be used as in-memory database (without any persisting, default mode) and in persisting mode (directory should be configured and some properties should be set). 4 | 5 | Links: 6 | - https://db.apache.org/derby/ 7 | - https://www.baeldung.com/java-apache-derby -------------------------------------------------------------------------------- /Spring Data/Spring Data JPA/JPA Overview.md: -------------------------------------------------------------------------------- 1 | JPA - Java Persistence API 2 | 3 | Idea: Each class can be mapped to table - each attribute is a column, and each instance is a row. 4 | 5 | By itself, JPA is not a tool or framework; rather, it defines a set of concepts that can be implemented by any tool or framework. 6 | 7 | JPA is an abstraction over JDBC 8 | 9 | Links: 10 | - https://www.youtube.com/watch?v=WZLTwbeENGs 11 | - https://www.infoworld.com/article/3379043/what-is-jpa-introduction-to-the-java-persistence-api.html 12 | - https://www.baeldung.com/jpa-vs-jdbc -------------------------------------------------------------------------------- /Spring Security/LDAP/LDAP Protocoll.md: -------------------------------------------------------------------------------- 1 | LDAP (Lightweight Directory Access Protocol) is a protocoll that allows acces to directory services. 2 | 3 | Directory services store the users, passwords, accounts, share information with other entities on the network, but they are not a part from LDAP (mostly third-party programms). 4 | 5 | Spring has framework for interaction with LDAP: Spring LDAP. Spring has also an Embedded LDAP Server for unit testing. 6 | 7 | Explanation: https://www.youtube.com/watch?v=ciYhxMEvR6Q 8 | Indian explanation: https://www.youtube.com/watch?v=XzEuvBX0I64 -------------------------------------------------------------------------------- /Spring Data/Spring Data MongoDB/Creating a MongoDB instance.md: -------------------------------------------------------------------------------- 1 | ## Creating a MongoDB instance 2 | 3 | At first, i'll use a free MongoDB Atlas instance: https://www.mongodb.com/docs/atlas/getting-started/ 4 | 5 | I'll create the database sandbox with username admin and password admin_password. 6 | 7 | Make sure, that you have added your IP adress to IP whitelist on atlas, or your connection will be refused. You can also allow connection from everywhere. 8 | 9 | 10 | ## Database IDE 11 | I'll use DataGrip to view and manipulate the database. There are also good free alternatives, my personal open-souce favourite is DBeaver. -------------------------------------------------------------------------------- /Spring Data/Spring Data MongoDB/Spring Data MongoDB.md: -------------------------------------------------------------------------------- 1 | If we want to use some NoSQL Database, like MongoDB, Spring Data JPA can be used, but it will be sometimes tricky, it will introduce complex dependencies and might just not work. More aboud difference between [[Spring Data MongoDB vs Spring Data JPA]] 2 | 3 | There is more convenient to use the specialised frameworks for NoSQL databases. 4 | 5 | For this part i'll use a project with following dependencies: 6 | - Spring Web 7 | - Spring Data MongoDB 8 | 9 | 10 | [[Creating a MongoDB instance]] 11 | [[Connecting to MongoDB]] 12 | [[Getting Data from MongoDB]] 13 | 14 | -------------------------------------------------------------------------------- /.obsidian/graph.json: -------------------------------------------------------------------------------- 1 | { 2 | "collapse-filter": false, 3 | "search": "", 4 | "showTags": true, 5 | "showAttachments": false, 6 | "hideUnresolved": false, 7 | "showOrphans": true, 8 | "collapse-color-groups": false, 9 | "colorGroups": [], 10 | "collapse-display": false, 11 | "showArrow": true, 12 | "textFadeMultiplier": 0, 13 | "nodeSizeMultiplier": 1.1185393258427, 14 | "lineSizeMultiplier": 2.4123595505618, 15 | "collapse-forces": false, 16 | "centerStrength": 0, 17 | "repelStrength": 20, 18 | "linkStrength": 1, 19 | "linkDistance": 500, 20 | "scale": 0.2588386562181687, 21 | "close": false 22 | } -------------------------------------------------------------------------------- /Spring Boot/Spring Boot.md: -------------------------------------------------------------------------------- 1 | Idea: make the configuration of Spring applications easier with some abstractions, generate a standalone web application from sources, that can be just started. 2 | 3 | Spring Boot is also responsible for configuration and usage of embedded Tomcat Web Server. 4 | 5 | Motivation and explanation: 6 | - https://www.youtube.com/watch?v=YXlSkWq04jk&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=5 7 | - https://www.youtube.com/watch?v=cONbHJ9azvw&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=6 8 | 9 | Content: 10 | - [[Starting an application]] 11 | - [[SpringBootApplication]] 12 | - [[CommandLineRunner]] 13 | - [[Application Properies]] -------------------------------------------------------------------------------- /.obsidian/plugins/obsidian-git/data.json: -------------------------------------------------------------------------------- 1 | { 2 | "commitMessage": "vault backup: {{date}}", 3 | "autoCommitMessage": "vault backup: {{date}}", 4 | "commitDateFormat": "YYYY-MM-DD HH:mm:ss", 5 | "autoSaveInterval": 0, 6 | "autoPullInterval": 0, 7 | "autoPullOnBoot": false, 8 | "disablePush": false, 9 | "pullBeforePush": true, 10 | "disablePopups": false, 11 | "listChangedFilesInMessageBody": false, 12 | "showStatusBar": true, 13 | "updateSubmodules": false, 14 | "syncMethod": "merge", 15 | "gitPath": "", 16 | "customMessageOnAutoBackup": false, 17 | "autoBackupAfterFileChange": false, 18 | "treeStructure": false, 19 | "refreshSourceControl": true 20 | } -------------------------------------------------------------------------------- /Spring Security/Passwords/Password Hashing Concepts.md: -------------------------------------------------------------------------------- 1 | Concepts: https://www.youtube.com/watch?v=--tnZMuoK3E 2 | 3 | ## Salt 4 | Salts are short random set of characters, that will be concatenated with passwords, before they are hashed. The usage of salts prevents the hacks with [Rainbow Tables](https://en.wikipedia.org/wiki/Rainbow_table). 5 | 6 | Salts are ususally not encrypted. 7 | 8 | ![[Salt.png]] 9 | 10 | ## Pepper 11 | Pepers are very short random strings, that are added to the end of password and encrypted with it. 12 | 13 | Pepper is not stored in system. 1-character pepper with only 1 letter makes the brute force hack 52 times harder. 14 | ![[Pepper.png]] 15 | 16 | 17 | -------------------------------------------------------------------------------- /Spring Boot/Starting an application.md: -------------------------------------------------------------------------------- 1 | Spring Boot starts a servlet container and host the application in this container. 2 | Important: @SpringBootApplication annotaion in main class. More here: [[SpringBootApplication]] 3 | 4 | There are four main startup internal stages: 5 | - Set up default configuration 6 | - Start Spring ApplicationContext 7 | - Scan class path (find and process Annotations: Controllers, Components, Beans etc) 8 | - Start Tomcat server (There are also alternative servers) 9 | 10 | Videos: 11 | - https://www.youtube.com/watch?v=E7_a-kB46LU&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=9 12 | - https://www.youtube.com/watch?v=E7_a-kB46LU&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=10 -------------------------------------------------------------------------------- /Basics/Bean Scopes.md: -------------------------------------------------------------------------------- 1 | There are two scope types for Beans in original Spring: 2 | - singleton – a single instance of this bean 3 | - prototype – multiple instances of this bean 4 | 5 | 6 | We use @Scope annotation to define scope 7 | ```java 8 | @Bean 9 | @Scope("singleton") 10 | public Person personSingleton() { 11 | return new Person(); 12 | } 13 | ``` 14 | 15 | Documentation: https://www.baeldung.com/spring-bean-scopes 16 | 17 | 18 | There are other types of scopes in latest Spring (only for web): 19 | - request - instance for a single HTTP request 20 | - session - instance for an HTTP Session 21 | - application - instance for the lifecycle of a _ServletContext_ 22 | - websocket - instance for a particular _WebSocket_ session -------------------------------------------------------------------------------- /Basics/Lifecycle Callbacks.md: -------------------------------------------------------------------------------- 1 | There are two important stages in the Bean Lifecycle: directly after initialization and directly before destruction. We can handle these moments with two interfaces: InitializingBean, DisposableBean. 2 | 3 | These interfaces require the implementation of corresponding methods: 4 | ```java 5 | @Component 6 | public class LifecycleExample implements InitializingBean, DisposableBean { 7 | 8 | @Override 9 | public void afterPropertiesSet() throws Exception { 10 | System.out.println("Im alive!"); 11 | } 12 | 13 | @Override 14 | public void destroy() throws Exception { 15 | System.out.println("Chao"); 16 | } 17 | } 18 | ``` 19 | These methods will be automatically called when object is initialized/disposed. -------------------------------------------------------------------------------- /Spring Boot/SpringBootApplication.md: -------------------------------------------------------------------------------- 1 | This annotation @SpringBootApplication is equivalent to using _@Configuration_, _@EnableAutoConfiguration_, and _@ComponentScan_. 2 | 3 | ```java 4 | @SpringBootApplication 5 | class VehicleFactoryApplication { 6 | public static void main(String[] args) { 7 | SpringApplication.run(VehicleFactoryApplication.class, args); 8 | } 9 | } 10 | ``` 11 | As a result, when we run this Spring Boot application, **it will automatically scan the components in the current package and its sub-packages**. Thus it will register them in Spring's Application Context, and allow us to inject beans using _@Autowired_. 12 | See [[Autowiring]]. 13 | 14 | Links: 15 | - https://www.baeldung.com/spring-boot-annotations#spring-boot-application 16 | - https://www.baeldung.com/spring-autowire -------------------------------------------------------------------------------- /Spring Security/Default User and Password.md: -------------------------------------------------------------------------------- 1 | Dafault username: user 2 | Default password: generated during startup 3 | 4 | ```log 5 | 2022-04-01 18:44:49.059 WARN 18744 --- [ main] .s.s.UserDetailsServiceAutoConfiguration : 6 | 7 | Using generated security password: ac09a4e5-cd44-4bbb-aa88-a9ded882873e 8 | 9 | This generated password is for development use only. Your security configuration must be updated before running your application in production. 10 | 11 | ``` 12 | 13 | Spring generates the new password on each startup. 14 | Default username and password can be set in application.properties file: 15 | 16 | ```properties 17 | spring.security.user.name=hello 18 | spring.security.user.password=world 19 | ``` 20 | 21 | Video: https://www.youtube.com/watch?v=PhG5p_yv0zs&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE&index=3 -------------------------------------------------------------------------------- /Spring Boot/Application Properies.md: -------------------------------------------------------------------------------- 1 | Most convenient way to specify some properties for application (like URL of database server) is a file application.properties, located in ressources folder. 2 | 3 | ```properties 4 | server.port=8081 5 | 6 | spring.data.mongodb.uri=mongodb://localhost/test 7 | ``` 8 | 9 | We can also use enivonment arguments here: 10 | ```properties 11 | spring.datasource.username=${OPENSHIFT_MYSQL_DB_USERNAME} 12 | spring.datasource.password=${OPENSHIFT_MYSQL_DB_PASSWORD} 13 | ``` 14 | 15 | And command line arguments: 16 | 17 | ```properties 18 | server.port=${port} 19 | ``` 20 | 21 | Guide: https://docs.spring.io/spring-boot/docs/1.2.0.M1/reference/html/howto-properties-and-configuration.html 22 | 23 | Commonly used properies and their defaults: https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html -------------------------------------------------------------------------------- /Spring Security/Spring Security.md: -------------------------------------------------------------------------------- 1 | Spring Sercurity provides the authentication and access-control. 2 | 3 | I'll use the package with dependencies: 4 | - Spring Web 5 | - Spring Security 6 | - Spring Data JPA 7 | - H2 Database 8 | - JDBC API 9 | 10 | 11 | We will get the authentification window, /login and /logout endpoints from the box, without single line of code. Spring Security adds mandatory authentication for all API endpoints. It creates one default user with name "user", and generates the security password, that can be seen in console during the startup. 12 | 13 | [[Basic concepts]] 14 | [[Filters]] 15 | [[Default User and Password]] 16 | [[Hardcoding the Users]] 17 | [[Password Encryprion]] 18 | [[Implementing Authorization]] 19 | [[Implementing Authentication]] 20 | [[Spring Security LDAP]] 21 | 22 | 23 | https://www.youtube.com/watch?v=sm-8qfMWEV8&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE&index=2 -------------------------------------------------------------------------------- /Spring Security/Passwords/Password Encryprion.md: -------------------------------------------------------------------------------- 1 | We shouldn't save passwords as plain Strings in memory. 2 | Instead, we have to encrypt them with some hash-function. 3 | 4 | We can do it by defining a Spring Bean with type PasswordEncoder, and return some specific password encoder from it. 5 | 6 | This NoOpPasswordEncoder uses **no hashing**. I'll use it at first, for learning purpose. 7 | 8 | ```java 9 | @Bean 10 | public PasswordEncoder getPasswordEncoder() { 11 | return NoOpPasswordEncoder.getInstance(); //no encryption 12 | } 13 | ``` 14 | 15 | Current **best practice** in Spring nowadays is the usage of BCryptPasswordEncoder 16 | 17 | ```java 18 | @Bean 19 | public PasswordEncoder getPasswordEncoder() { 20 | return new BCryptPasswordEncoder(); //proper encryption 21 | } 22 | ``` 23 | 24 | BCrypt is besser than SHA, because we don't have to store the private key, it will be generated. More about [[Password Hashing Concepts]]. -------------------------------------------------------------------------------- /Spring Data/Spring Data MongoDB/MongoRepository.md: -------------------------------------------------------------------------------- 1 | We can use a special repository interface type, the **MongoRepository** to get users from database. 2 | 3 | ```java 4 | public interface UserRepository extends MongoRepository { 5 | 6 | User findUserByUsername(String username); 7 | 8 | } 9 | ``` 10 | 11 | The implementation of the function will be automatically derived from it's name. The patterns of function naming are described here: https://www.baeldung.com/spring-data-derived-queries 12 | 13 | We can also define the query explicitely with _@Query_ annotations. This way is more robust and suitable for complex queries. 14 | 15 | ```java 16 | public interface UserRepository extends MongoRepository { 17 | 18 | @Query("{name:'?0'}") 19 | User findUserByUsername(String username); 20 | 21 | } 22 | ``` 23 | 24 | More about [[MongoDB Queries]]. 25 | 26 | Documentation: https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/repository/MongoRepository.html -------------------------------------------------------------------------------- /Spring Data/JPA Repository.md: -------------------------------------------------------------------------------- 1 | Interface JpaRepository is the most powerful interface in Spring Data JPA. 2 | It contains the functionality from [[CRUD Repository]] and [[PagingAndSortingRepository]], and introduces some new features. 3 | 4 | Documentation: https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html 5 | 6 | Important are batch and flush methods, that can modify many entities in a single transaction. 7 | 8 | ## Explicit Queries with @Query 9 | 10 | With _@Query_ annotation we can specify the exact SQL Statements. We can also use the named arguments, with usage of _@Param_ annotation. 11 | 12 | ```java 13 | public interface UserRepository extends JpaRepository { 14 | 15 | @Query("SELECT u FROM User u WHERE u.firstname = :firstname OR u.lastname = :lastname") 16 | User findByLastnameOrFirstname(@Param("lastname") String lastname, 17 | @Param("firstname") String firstname); 18 | } 19 | ``` 20 | 21 | More about queries and parameter naming: https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.named-parameters -------------------------------------------------------------------------------- /Spring MVC/Service.md: -------------------------------------------------------------------------------- 1 | We can mark the class that manages some business logic with @Service annotation. 2 | 3 | ```java 4 | @Service 5 | public class BookService { 6 | List books; 7 | 8 | public BookService() { 9 | this.books = new ArrayList<>(); 10 | books.add(new Book(145, "Spring", "Baeldung")); 11 | books.add(new Book(932, "Operating Systems", "Tanenbaum")); 12 | } 13 | 14 | public List getAllBooks() { 15 | return books; 16 | } 17 | 18 | public Book getBookById(Long id) { 19 | return books.stream().filter(b -> b.getId().equals(id)).findFirst().get(); 20 | } 21 | } 22 | ``` 23 | 24 | And then autowire it the controller class. 25 | 26 | ```java 27 | @RestController 28 | public class BookController { 29 | private final BookService bookService; 30 | 31 | @Autowired 32 | public BookController(BookService bookService) { 33 | this.bookService = bookService; 34 | } 35 | 36 | @RequestMapping(value = "/books", method = RequestMethod.GET) 37 | public List getAllBooks() { 38 | return bookService.getAllBooks(); 39 | } 40 | } 41 | ``` -------------------------------------------------------------------------------- /Spring Security/Basic concepts.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | **Authentication** - answering the question "Who are you" with proofs. 5 | There are three main types of authentication: 6 | 7 | - Knowledge based authentication: password, pin code, secret question 8 | - Possession based authentication: phone message, key card, access token device 9 | - Multi Factor Authentication: combination of different types of authentication, like password + code from SMS. 10 | 11 | 12 | **Authorization** - answering the question "Has this user the permission to perform the desired action?". 13 | 14 | **Principal** - currently log in account. 15 | 16 | 17 | How does authorization happen - how to decide, whether user can perform the action or not? This is controlled by some set of permissions. Each permission is called **Authority**. 18 | 19 | The set of all Authorities of the use is called **Granted Authority**. 20 | 21 | **Role** - group of authorities, that are assigned together. For exampe, role User, role Moderator and Role admin, that can use different API endpoints. 22 | 23 | Video: https://www.youtube.com/watch?v=I0poT4UxFxE&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE&index=2 -------------------------------------------------------------------------------- /Spring Data/Spring Data JPA/Spring Data JPA.md: -------------------------------------------------------------------------------- 1 | We can use Spring Data JPA to map table entries from relational databases to java objects, and persist the java objects in corresponding tables. 2 | 3 | Note, that Spring Data JPA can be used with all database types, but it was constructed to create an abstraction on RDBMS. There are better frameworks for other database types. If you want to use NoSQL database MongoDB, here is some information: [[Spring Data MongoDB]] 4 | 5 | I'll use Spring Data with Apache Derby (not usual database, but simple embedded database). Just create the new project on Spring Initializr with: 6 | 7 | - Spring Web 8 | - Spring Data JPA 9 | - Apache Derby Database 10 | 11 | Link: https://www.youtube.com/watch?v=du99WcQztNU&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=27 12 | 13 | Content: 14 | - [[JPA Overview]] 15 | - [[Apache Derby]] 16 | - [[Entity]] 17 | - [[CRUD Repository]] 18 | - [[Repository Usage]] 19 | - [[JPA Relations]] 20 | - [[JPA Repository]] 21 | 22 | Normal database: 23 | - [[Connecting to Database with JPA]] 24 | 25 | 26 | TODO https://www.youtube.com/watch?v=bEKt7LLEvb0&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=30 -------------------------------------------------------------------------------- /Spring Data/Spring Data JPA/Entity.md: -------------------------------------------------------------------------------- 1 | @Entity annotation shows to Spring, that this class will be used as model object. Each entity requires the primary key, that is defined with @Id annotation. 2 | 3 | ```java 4 | import javax.persistence.Entity; 5 | import javax.persistence.Id; 6 | 7 | @Entity 8 | public class Wine { 9 | 10 | @Id 11 | private String id; 12 | private String name; 13 | private String producer; 14 | 15 | public Wine() { 16 | } 17 | 18 | public Wine(String id, String name, String producer) { 19 | this.id = id; 20 | this.name = name; 21 | this.producer = producer; 22 | } 23 | 24 | public String getId() { 25 | return id; 26 | } 27 | 28 | public String getName() { 29 | return name; 30 | } 31 | 32 | public String getProducer() { 33 | return producer; 34 | } 35 | } 36 | ``` 37 | 38 | We can also set the table and column names for the database with annotations. 39 | 40 | ```java 41 | @Entity 42 | @Table(name = "employee") 43 | public class Employee implements Serializable { 44 | @Column(name = "employee_name") 45 | private String employeeName; 46 | } 47 | ``` -------------------------------------------------------------------------------- /Spring Data/Spring Data MongoDB/Connecting to MongoDB.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Connecting to MongoDB 4 | Guide about connecting Spring Boot to MongoDB Atlas: https://www.mongodb.com/compatibility/spring-boot 5 | 6 | We have to add a Spring Boot MongoDB Dependency (spring-boot-starter-data-mongodb in Maven) 7 | 8 | These properties habe to be set in application.properties to configure the URL, username and password. 9 | 10 | **This is a sandbox example, do not store the passwords in configs in real life! Use some environment variables and secrets instead** 11 | 12 | ```properties 13 | 14 | spring.data.mongodb.uri=mongodb+srv://:@.mongodb.net/mygrocerylist 15 | 16 | spring.data.mongodb.database=mygrocerylist 17 | ``` 18 | 19 | My properties: 20 | 21 | ```properties 22 | spring.data.mongodb.uri=mongodb+srv://admin:************@sandboxcluster.ngis0.mongodb.net/sandbox 23 | 24 | spring.data.mongodb.database=sandbox 25 | ``` 26 | 27 | If specified database does not exist, MongoDB will create a new one. 28 | 29 | Then we have to specify, that we want a connection with MongoDB. It can be done with just one annotation _@EnableMongoRepositories_ in main apllication file 30 | 31 | ```java 32 | @SpringBootApplication 33 | @EnableMongoRepositories 34 | public class SecurityJdbcApplication { 35 | 36 | public static void main(String[] args) { 37 | SpringApplication.run(SecurityJdbcApplication.class, args); 38 | } 39 | 40 | } 41 | ``` 42 | 43 | 44 | -------------------------------------------------------------------------------- /Spring Data/Spring Data JPA/Repository Usage.md: -------------------------------------------------------------------------------- 1 | Let's make our entity a little bit more complex, by adding the GrapeSort field to Wine class. 2 | 3 | ```java 4 | @Entity 5 | public class GrapeSort { 6 | @Id 7 | private String name; 8 | } 9 | ``` 10 | 11 | If we link one entity with another entity, we have to define the cardinality of relation: [[JPA Relations]] 12 | 13 | 14 | One Wine can have only one sort (naive assumption), but there can be different wines, that use the same grape sort. 15 | 16 | Structure is "MainClass-to-Field". Many Wine types to one GrapeSort Therefore in this case we have to use @ManyToOne relation. 17 | 18 | ```java 19 | @Entity 20 | public class Wine { 21 | 22 | @Id 23 | private String id; 24 | private String name; 25 | private String producer; 26 | 27 | @ManyToOne 28 | private GrapeSort grapeSort; 29 | ``` 30 | 31 | If we want to get the list of wines of one specific GrapeSort, we can't just use the [[CRUD Repository]]. 32 | In this case, we have to define a new method in the interface. If we use the correct method name, JPA will generate the code from it, without any additional annotation. 33 | 34 | ```java 35 | public interface WineRepository extends CrudRepository { 36 | public List findAllByGrapeSortName(String grapeSortName); 37 | } 38 | ``` 39 | 40 | Stucture: find\[All\]By{Entity}{Field} 41 | 42 | More rules here: https://www.baeldung.com/spring-data-derived-queries -------------------------------------------------------------------------------- /Basics/Application Context.md: -------------------------------------------------------------------------------- 1 | When you start a Spring application, the framework firstly creates a special object called ApplicationContext. The ApplicationContext, also known as the Inversion of Control (IoC)  container, is the heart of the framework. 2 | 3 | The ApplicationContext is a container in which your bean objects exist. 4 | 5 | The context is responsible for detecting and reading your Spring bean definitions. Once the ApplicationContext loads bean definitions, it can start creating bean objects for your application based on provided bean properties and their dependencies. 6 | 7 | Text from http://dolszewski.com/spring/spring-bean/ 8 | 9 | ApplicationContext can be seen as main BeanFactory of the application. 10 | 11 | Documentation: https://www.baeldung.com/spring-application-context 12 | 13 | To use ApplicationContext as bean factory, we have to autowire it. To do it in main class, we can use the interface [[CommandLineRunner]] from SpringBoot. 14 | 15 | ```java 16 | @SpringBootApplication 17 | public class LearningApplication implements CommandLineRunner { 18 | @Autowired 19 | private ApplicationContext applicationContext; 20 | 21 | public static void main(String[] args) { 22 | SpringApplication.run(LearningApplication.class, args); 23 | } 24 | 25 | @Override 26 | public void run(String... args) { 27 | FooService service = applicationContext.getBean(FooService.class); 28 | System.out.println(service.getFooFormatter().format()); 29 | } 30 | } 31 | ``` 32 | -------------------------------------------------------------------------------- /Spring Data/Spring Data JPA/Connecting to Database with JPA.md: -------------------------------------------------------------------------------- 1 | I'll use create a PostgreSQL instance on Heroku and use it for connection. 2 | I is important to allow access to the cloud instance from your ip address. 3 | 4 | Guide: https://www.codejava.net/frameworks/spring-boot/connect-to-postgresql-database-examples 5 | 6 | We have to specify following parameters in application.properties: 7 | 8 | ```properties 9 | spring.datasource.url= 10 | spring.datasource.username= 11 | spring.datasource.password= 12 | spring.datasource.driver-class-name=org.postgresql.Driver 13 | ``` 14 | 15 | Note, that the dependency spring-boot-starter-data-jpa and postgres driver is required. 16 | ```xml 17 | 18 | org.springframework.boot 19 | spring-boot-starter-data-jpa 20 | 21 | 22 | 23 | org.postgresql 24 | postgresql 25 | 26 | ``` 27 | 28 | My credentials: 29 | 30 | ```properties 31 | spring.datasource.url=jdbc:postgresql://ec2-52-18-116-67.eu-west-1.compute.amazonaws.com:5432/dbmiq3db65kq18 32 | spring.datasource.username=rtqdhjzpirhsbt 33 | spring.datasource.password=*********************************************** 34 | ``` 35 | 36 | Usually i use the Datagrip (or free Dbeaver) to establish the initial database connection and the form the connection url. 37 | 38 | If you are getting errors on Spring startup, then try to connect via some database IDE at first, it would give you some detailed problem specification. -------------------------------------------------------------------------------- /Spring Security/Implementing Authorization.md: -------------------------------------------------------------------------------- 1 | We have to create the configuration, that extends the WebSecurityConfigurerAdapter class and is registered as Spring Security Configuration Bean with _@EnableWebSecurity_ annotation. 2 | 3 | To configure the authorization rules for different roles, we ahve to override configure(HttpSecurity http) method. 4 | 5 | This configuration will allow the usage of all endpoints only for the user with ADMIN role. 6 | 7 | ```java 8 | @EnableWebSecurity 9 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 10 | 11 | @Override 12 | protected void configure(HttpSecurity http) throws Exception { 13 | http.authorizeRequests(). 14 | .antMatchers("/**").hasRole("ADMIN") 15 | .and().formLogin(); 16 | } 17 | } 18 | 19 | ``` 20 | 21 | You can chain the rules, and go from most restricted rules to least restricted endpoints. 22 | 23 | ```java 24 | @EnableWebSecurity 25 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 26 | 27 | @Override 28 | protected void configure(HttpSecurity http) throws Exception { 29 | http.authorizeRequests() 30 | .antMatchers("/admin").hasRole("ADMIN") 31 | .antMatchers("/user").hasAnyRole("USER", "ADMIN") 32 | .antMatchers("/", "static/css", "static/js").permitAll() 33 | .and().formLogin(); 34 | } 35 | ``` 36 | 37 | I will use the simple [[Reference Controller]] for testing. 38 | 39 | 40 | Video: https://www.youtube.com/watch?v=payxWrmF_0k&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE&index=5 -------------------------------------------------------------------------------- /Spring Security/Authentication/Hardcoding the Users.md: -------------------------------------------------------------------------------- 1 | We can extend the class WebSecurityConfigurerAdapter and override the method configure(AuthenticationManagerBuilder auth) to hardcode the user with some password. 2 | 3 | This class should be marked for Spring with _@EnableWebSecurity_ annotation. 4 | 5 | ```java 6 | @EnableWebSecurity 7 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 8 | 9 | @Override 10 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 11 | auth.inMemoryAuthentication() 12 | .withUser("user").password("password").roles("USER"); 13 | } 14 | ``` 15 | 16 | If we want to add multiple users, we can chain the call with chaining method and(). 17 | 18 | ```java 19 | @EnableWebSecurity 20 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 21 | 22 | @Override 23 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 24 | auth.inMemoryAuthentication() 25 | .withUser("user").password("password").roles("USER") 26 | .and() 27 | .withUser("user2").password("password2").roles("USER"); 28 | } 29 | ``` 30 | 31 | Spring will use this configuration, to build the instance of AuthenticationManager using the AuthenticationManagerBuilder. 32 | 33 | In general, we don't want to store the passwords as plain text. More about [[Password Encryprion]]. 34 | 35 | Hardcoding the users is good for beginning, but in practice the users are stored in some database: [[Implementing Authentication]] 36 | 37 | Video: https://www.youtube.com/watch?v=iyXne7dIn7U -------------------------------------------------------------------------------- /Spring Data/Spring Data MongoDB/Getting Data from MongoDB.md: -------------------------------------------------------------------------------- 1 | _@Document_ annotation defines a name of persisting object in MongoDB. 2 | 3 | Let's create a model object, that represents a User with credentials. 4 | 5 | ```java 6 | @Document("user") 7 | public class User { 8 | @Id 9 | private String username; 10 | private String password; 11 | private String role; 12 | 13 | public User(String id, String username, String password, String role) { 14 | this.username = username; 15 | this.password = password; 16 | this.role = role; 17 | } 18 | 19 | public String getUsername() { 20 | return username; 21 | } 22 | 23 | public void setUsername(String username) { 24 | this.username = username; 25 | } 26 | 27 | public String getPassword() { 28 | return password; 29 | } 30 | 31 | public void setPassword(String password) { 32 | this.password = password; 33 | } 34 | 35 | public String getRole() { 36 | return role; 37 | } 38 | 39 | public void setRole(String role) { 40 | this.role = role; 41 | } 42 | } 43 | ``` 44 | 45 | We can use a special repository interface type, the **MongoRepository** to get users from database. 46 | 47 | ```java 48 | public interface UserRepository extends MongoRepository { 49 | 50 | User findUserByUsername(String username); 51 | 52 | } 53 | 54 | ``` 55 | 56 | The implementation of the function will be automatically derived from it's name. The patterns of function naming are described here: https://www.baeldung.com/spring-data-derived-queries 57 | 58 | More about [[MongoRepository]] -------------------------------------------------------------------------------- /Spring MVC/Servlets and Controllers.md: -------------------------------------------------------------------------------- 1 | Servlet is a Java object, that implements the Servlet interface and handles the incoming HTTP requests. Methods init(), service() and destroy() have to be implemented. 2 | 3 | ```java 4 | public class ServletLifeCycleExample extends HttpServlet { 5 | private Integer sharedCounter; 6 | 7 | @Override 8 | public void init(final ServletConfig config) throws ServletException { 9 | super.init(config); 10 | getServletContext().log("init() called"); 11 | sharedCounter = 0; 12 | } 13 | 14 | @Override 15 | protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { 16 | getServletContext().log("service() called"); 17 | int localCounter; 18 | synchronized (sharedCounter) { 19 | sharedCounter++; 20 | localCounter = sharedCounter; 21 | } 22 | response.getWriter().write("Incrementing the count to " + localCounter); // accessing a local variable 23 | } 24 | 25 | @Override 26 | public void destroy() { 27 | getServletContext().log("destroy() called"); 28 | } 29 | } 30 | ``` 31 | 32 | Each request is creates a new thread, that process this request. The mapping between URLs and Servlet classes is configured via web.xml 33 | 34 | Servlets can be seen as low-level way to handle HTTP requests. They were used to implement web servers in the past, but nowadays they are implemented internally by different framework wrappers, like Controllers in Spring. 35 | 36 | Spring Controllers are not the same as servlets, but Spring uses the custom extension of HttpServlet called DispacherServlet internally. 37 | -------------------------------------------------------------------------------- /Basics/Autowiring.md: -------------------------------------------------------------------------------- 1 | 2 | The annotation @Autowire allows Spring to resolve and inject collaborating beans into our bean. 3 | 4 | Documentation: https://www.baeldung.com/spring-autowire 5 | 6 | Component scan should be enabled to use the autowiring. The annotation _@SpringBootApplication_ includes _@ComponentScan_. More here: [[SpringBootApplication]] 7 | 8 | ```java 9 | @Component 10 | public class FooFormatter { 11 | public String format() { 12 | return "foo"; 13 | } 14 | } 15 | ``` 16 | 17 | ```java 18 | @Component 19 | public class FooService { 20 | @Autowired 21 | private FooFormatter fooFormatter; 22 | } 23 | ``` 24 | 25 | If we create the instance of FooService in classic java way, then we will ignore all Spring functionality, and Autowiring will not work. We have to call [[Application Context]] and get the Bean for our component. 26 | 27 | **Dont**: 28 | ```java 29 | FooService service = new FooService() // DONT DO IT - IT WILL PRODUCE GARBAGE 30 | ``` 31 | 32 | **Do**: 33 | ```java 34 | FooService service = applicationContext.getBean(FooService.class); // CORRECT WAY 35 | ``` 36 | 37 | Spring says, that this way (called field injection) is not recommended. The better way is constructor injection. 38 | 39 | You can do this for constructor injection: 40 | 41 | ```java 42 | @Component 43 | public class FooService { 44 | private final FooFormatter fooFormatter; 45 | 46 | @Autowired 47 | public FooService(FooFormatter fooFormatter) { 48 | this.fooFormatter = fooFormatter; 49 | } 50 | } 51 | ``` 52 | 53 | Advantages: at first, we can use final modifier with constructor injection (we cant do it with field injection). Field Injection violates the responsibility principle, it is not good for architecture and testing. 54 | -------------------------------------------------------------------------------- /Spring Data/CRUD Repository.md: -------------------------------------------------------------------------------- 1 | Documentation: https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html 2 | 3 | We have to create an interface for database connection. If we want simple CRUD operations, then we can extend class CrudRepository. 4 | 5 | Only create an interface, and extend the class. No further code. Not a joke. 6 | ```java 7 | public interface WineRepository extends CrudRepository { 8 | } 9 | ``` 10 | 11 | Then we have to autowire this repository to our service and use it. 12 | 13 | ```java 14 | @Service 15 | public class WineService { 16 | private final WineRepository wineRepository; 17 | 18 | @Autowired 19 | public WineService(WineRepository wineRepository) { 20 | this.wineRepository = wineRepository; 21 | } 22 | 23 | public List getAllWines() { 24 | List wines = new ArrayList<>(); 25 | wineRepository.findAll().forEach(wines::add); 26 | return wines; 27 | } 28 | 29 | public void addWine(Wine wine) { 30 | wineRepository.save(wine); 31 | } 32 | 33 | public Wine getWineById(String id) { 34 | return wineRepository.findById(id).get(); 35 | } 36 | } 37 | ``` 38 | 39 | Important methods: 40 | - findAll() 41 | - findById(id) 42 | - findAllById(id) 43 | - save(obj) 44 | - saveAll(list) 45 | - delete(obj) 46 | - deleteById(id) 47 | - deleteAll() 48 | - deleteAll(list) 49 | 50 | The class representing the model are described in [[Entity]]. 51 | 52 | The repository with custom methods is described here: [[Repository Usage]] 53 | 54 | Links: 55 | - https://www.youtube.com/watch?v=z3HnFBzn7DI&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=28 56 | - https://www.youtube.com/watch?v=lpcOSXWPXTk&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=29 -------------------------------------------------------------------------------- /Basics/Event Handling.md: -------------------------------------------------------------------------------- 1 | We need three things, to implement event system: 2 | - Event class (extend _ApplicationEvent_) 3 | - Event Listener class (implement _ApplicationListener_ as Component) 4 | - Event Publisher instance (autowire ApplicationEventPublisher and use it) 5 | 6 | At first, we need an event class, that extends _ApplicationEvent_ class. I'll create a simple event, that stores some message. Instances of this class will represent the events. 7 | 8 | ```java 9 | public class ExampleEvent extends ApplicationEvent { 10 | private final String message; 11 | 12 | public ExampleEvent(Object source, String message) { 13 | super(source); 14 | this.message = message; 15 | } 16 | 17 | public String getMessage() { 18 | return message; 19 | } 20 | } 21 | ``` 22 | 23 | Then we have to create the listener class, that implements _ApplicationListener_ interface for our target event type. It is required to react on the events, that will be published somewhere in code. 24 | **Important: do not forget to register it as Spring object with @Component** 25 | 26 | ```java 27 | @Component 28 | public class ExampleEventListener implements ApplicationListener { 29 | @Override 30 | public void onApplicationEvent(ExampleEvent event) { 31 | System.out.println("Event received: " + event.getMessage()); 32 | } 33 | } 34 | ``` 35 | 36 | Then we have to add ApplicationEventPublisher to our class, that can "fire" the event: 37 | 38 | ```java 39 | @Autowired 40 | private ApplicationEventPublisher applicationEventPublisher; 41 | ``` 42 | 43 | And use it on the some place in code: 44 | ```java 45 | public void run(String... args) { 46 | String now = new SimpleDateFormat("yyyyMMdd_HHmmss") 47 | .format(Calendar.getInstance().getTime()); 48 | 49 | ExampleEvent testEvent = new ExampleEvent(this, 50 | "Custom event created on " + now); 51 | 52 | applicationEventPublisher.publishEvent(testEvent); 53 | } 54 | ``` 55 | 56 | Documentation: https://www.baeldung.com/spring-events -------------------------------------------------------------------------------- /Spring Data/Spring Data MongoDB/MongoDB Queries.md: -------------------------------------------------------------------------------- 1 | We can bind native MongoDB queries to repository methods with _@Query_ Annotation. 2 | 3 | Guide: https://javatechonline.com/spring-boot-mongodb-query-examples/ 4 | 5 | _@Query_ takes a JSON string as argument. 6 | 7 | Let's assume, that out MongoDB instance stores Book objects with fields: 8 | - int id (Primary Key) 9 | - String title 10 | - int price 11 | - int pages 12 | 13 | The parameters will be injected in query, positions can be marked with ?0 for first parameter, ?1 for second parameter, ?2 for third etc. 14 | 15 | Note, that String parameters have to be wrapped with quotes. 16 | 17 | ```java 18 | public interface BookRepository extends MongoRepository { 19 | 20 | @Query("{id:?0}") 21 | Book findBookById(int id); 22 | 23 | @Query("{title:'?0'}") 24 | Book findBookByTitle(String title); 25 | 26 | } 27 | 28 | ``` 29 | 30 | ## Syntax 31 | 32 | Here is an overview for query syntax 33 | ![[MongoDB_Queries_Table.png]] 34 | 35 | And the comparison to classical SQL Statements 36 | 37 | ![[MongoDB_Queries.webp]] 38 | 39 | ## Operators 40 | 41 | Note, that the mathematical and logical operators like <, >, not are presented as named functions: $lt, $gt, $ne. 42 | 43 | ```java 44 | public interface BookRepository extends MongoRepository { 45 | 46 | @Query("{price: {$lt: ?0}}") 47 | List findAllBooksCheaperThan(int upperPriceBorder); 48 | 49 | @Query("{pages: {$gt: ?0, $lt : ?1}}") 50 | List findAllBooksWithPagesBetween(int minPages, int maxPages); 51 | 52 | } 53 | 54 | ``` 55 | 56 | ## Projection 57 | We can project the result with the fields parameter. 58 | 59 | Expression fields="{a:1}" defines, that only field a should be displayed (and all others are implicit marked with fieldname:0) 60 | 61 | ```java 62 | public interface BookRepository extends MongoRepository { 63 | 64 | @Query("{price: {$lt: ?0}}") 65 | List findAllBooksCheaperThan(int upperPriceBorder); 66 | 67 | @Query(value = "{pages: {$gt: ?0, $lt : ?1}}", 68 | fields = "{price:1, pages:1}") 69 | List findAllPricesOfBooksWithPagesBetween(int minPages, int maxPages); 70 | 71 | } 72 | 73 | ``` 74 | 75 | -------------------------------------------------------------------------------- /Spring Security/Default User Schema.md: -------------------------------------------------------------------------------- 1 | ## Initialize Schema 2 | 3 | Spring will use the default user schema configuration, if no further configuration was done. The syntax of the schema depends on database dialect. 4 | 5 | We can set up the schema for the in-memory databases by adding the file **schema.sql** in ressources folder. 6 | 7 | Here is the abstract structure: 8 | 9 | ```sql 10 | create table users( 11 | username varchar_ignorecase(50) not null primary key, 12 | password varchar_ignorecase(500) not null, 13 | enabled boolean not null 14 | ); 15 | 16 | create table authorities ( 17 | username varchar_ignorecase(50) not null, 18 | authority varchar_ignorecase(50) not null, 19 | constraint fk_authorities_users foreign key(username) references users(username) 20 | ); 21 | create unique index ix_auth_username on authorities (username,authority); 22 | ``` 23 | 24 | Oracle schema: 25 | 26 | ```sql 27 | CREATE TABLE USERS ( 28 | USERNAME NVARCHAR2(128) PRIMARY KEY, 29 | PASSWORD NVARCHAR2(128) NOT NULL, 30 | ENABLED CHAR(1) CHECK (ENABLED IN ('Y','N') ) NOT NULL 31 | ); 32 | 33 | 34 | CREATE TABLE AUTHORITIES ( 35 | USERNAME NVARCHAR2(128) NOT NULL, 36 | AUTHORITY NVARCHAR2(128) NOT NULL 37 | ); 38 | ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_UNIQUE UNIQUE (USERNAME, AUTHORITY); 39 | ALTER TABLE AUTHORITIES ADD CONSTRAINT AUTHORITIES_FK1 FOREIGN KEY (USERNAME) REFERENCES USERS (USERNAME) ENABLE; 40 | ``` 41 | 42 | Default Schema documentation: https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/jdbc.html#servlet-authentication-jdbc-schema 43 | 44 | We can use different table and column structure, but then we have to use explicit SQL statements. More here: [[Configuring the Users with DataSource#Custom Schema]]. 45 | 46 | ## Initialize Users 47 | We can initialize the database object by creating the **data.sql** file in ressource directory. The SQL Statements will be executed on startup. 48 | ```sql 49 | INSERT INTO users (username, password, enabled) VALUES ('user', 'password', true); 50 | INSERT INTO users (username, password, enabled) VALUES ('admin', 'admin', true); 51 | 52 | INSERT INTO authorities (username, authority) VALUES ('user', 'ROLE_USER'); 53 | INSERT INTO authorities (username, authority) VALUES ('admin', 'ROLE_ADMIN'); 54 | ``` 55 | -------------------------------------------------------------------------------- /Spring Security/Filters.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | A Filter is an object that is invoked at the preprocessing and postprocessing of a request. Filter can be used to log every request, or to check every request and look for some specific header or token. They can also handle the encryption, decryption, and input validation. 4 | 5 | Each filter can be applied to some group of URLs, or to all URLs. 6 | 7 | We create two filters: 8 | 1. _TransactionFilter_ – to start and commit transactions 9 | 2. _RequestResponseLoggingFilter_ – to log requests and responses 10 | 11 | Moreover, to have the filters fire in the right order, we need to use the _@Order_ annotation. These filters are registered by default for all of the URLs in our application. 12 | 13 | ```java 14 | @Component 15 | @Order(1) 16 | public class TransactionFilter implements Filter { 17 | 18 | @Override 19 | public void doFilter( 20 | ServletRequest request, 21 | ServletResponse response, 22 | FilterChain chain) throws IOException, ServletException { 23 | 24 | HttpServletRequest req = (HttpServletRequest) request; 25 |         LOG.info( 26 | "Starting a transaction for req : {}", 27 | req.getRequestURI()); 28 | 29 |         chain.doFilter(request, response); 30 |         LOG.info( 31 | "Committing a transaction for req : {}", 32 | req.getRequestURI()); 33 | } 34 | // other methods 35 | } 36 | 37 | ``` 38 | 39 | ```java 40 | @Component 41 | @Order(2) 42 | public class RequestResponseLoggingFilter implements Filter { 43 | 44 | @Override 45 | public void doFilter( 46 | ServletRequest request, 47 | ServletResponse response, 48 | FilterChain chain) throws IOException, ServletException { 49 | 50 | HttpServletRequest req = (HttpServletRequest) request; 51 | HttpServletResponse res = (HttpServletResponse) response; 52 | LOG.info( 53 | "Logging Request {} : {}", req.getMethod(), 54 | req.getRequestURI()); 55 | chain.doFilter(request, response); 56 | LOG.info( 57 | "Logging Response :{}", 58 | res.getContentType()); 59 | } 60 | 61 | // other methods 62 | } 63 | ``` 64 | 65 | 66 | 67 | 68 | Only after the filters are passed, request will be handled with corresponding [[Servlets and Controllers]]. 69 | 70 | Link: https://www.baeldung.com/spring-boot-add-filter 71 | 72 | ![[FiltersServlets.png]] -------------------------------------------------------------------------------- /Basics/Beans.md: -------------------------------------------------------------------------------- 1 | We have to put the Java objects in containers, that are managed by Spring. Then Spring can perform all the necessary internal handling. 2 | If we use normal Java objects, without putting them into Spring container, Spring will know nothing about these objects. 3 | 4 | Bean concept: https://www.youtube.com/watch?v=xlWwMSu5I70&list=PLC97BDEFDCDD169D7&index=3 5 | 6 | Code tutorial for Bean Factories: https://www.youtube.com/watch?v=7c6ZTF6cF88&list=PLC97BDEFDCDD169D7&index=4 7 | 8 | There are three ways to create Beans: 9 | - XML old and deprecated way 10 | - @Component - for classes of application 11 | - @Bean - for classes from libs 12 | 13 | The usage of XmlBeanFactory (and XML beans) is deprecated, this is an example of "oldest" way to create a bean. 14 | 15 | ```java 16 | public class LearningApplication { 17 | public static void main(String[] args) { 18 | SpringApplication.run(LearningApplication.class, args); 19 | BeanFactory factory = new XmlBeanFactory(new FileSystemResource("src/main/resources/beans.xml")); 20 | Triangle triangle = (Triangle) factory.getBean("triangle"); 21 | triangle.draw(); 22 | } 23 | } 24 | ``` 25 | 26 | ```xml 27 | 28 | 31 | 32 | 33 | 34 | ``` 35 | 36 | Descriptions of beans: 37 | - https://stackoverflow.com/questions/17193365/what-in-the-world-are-spring-beans 38 | - http://dolszewski.com/spring/spring-bean/ 39 | 40 | Today beans are configured via @Component class anotation, or its derivatives @Service, @Repository, @Controller. Simply add one of these annotations to your class. 41 | ```java 42 | @Component 43 | class BeanWithDependency { 44 | private final MyBeanClass beanClass; 45 | 46 | BeanWithDependency(MyBeanClass beanClass) { 47 | this.beanClass = beanClass; 48 | } 49 | } 50 | ``` 51 | 52 | 53 | We can also use @Bean and @Configuration annotations to wrap classes from libraries. 54 | ```java 55 | @Configuration 56 | class MyConfigurationClass { 57 | @Bean 58 | public NotMyClass notMyClass() { 59 | return new NotMyClass(); 60 | } 61 | } 62 | ``` 63 | 64 | 65 | The scope of a Spring bean defines how many instances of a particular class the framework creates at runtime. The scope also describes on what condition a new object is created. More about scopes: [[Bean Scopes]] 66 | 67 | There are many stages of bean lifecycle. Main lifecycle callbacks: [[Lifecycle Callbacks]] 68 | -------------------------------------------------------------------------------- /Spring Data/PagingAndSortingRepository.md: -------------------------------------------------------------------------------- 1 | An inteface PagingAndSortingRepository extends the interface [[CRUD Repository]]. 2 | 3 | Documentation: https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/PagingAndSortingRepository.html 4 | 5 | Usage: https://www.baeldung.com/spring-data-jpa-pagination-sorting 6 | 7 | If we extend an interface PagingAndSortingRepository, we can use two new features - pagination and sorting. 8 | 9 | Let's define a reference repository: 10 | ```java 11 | public interface ProductRepository extends PagingAndSortingRepository { 12 | 13 | List findAll(Sort sort); 14 | 15 | List findAllByPrice(double price, Sort sort); 16 | 17 | List findAllByPrice(double price, Pageable pageable); 18 | } 19 | ``` 20 | 21 | ## Sorting 22 | Sort object is an object that represents the sorting relation, that can be applied to data. 23 | 24 | This sort object can be applied to query, to get the object list sorted by descending order by column "price". 25 | ```java 26 | Sort sortPriceDesc = Sort.by(Sort.Direction.DESC, "price"); 27 | List productsSortedByPrice = repository.findAll(sortPriceDesc); 28 | ``` 29 | 30 | or, alternatively: 31 | 32 | ```java 33 | Sort sortPriceDesc = Sort.by("price").descending(); 34 | List productsSortedByPrice = repository.findAll(sortPriceDesc); 35 | ``` 36 | 37 | We can also chain different sorts: 38 | 39 | ```java 40 | Sort sortPriceDesc = Sort.by("price").descending().and(Sort.by("name")); 41 | List productsSortedByPrice = repository.findAll(sortPriceDesc); 42 | ``` 43 | 44 | ## Paging 45 | Paging (or pagination) is helpful, when we have a large dataset and we want to present it in smaller chunks, called pages. 46 | 47 | To use it, we have to create a PageRequest object, which defines, which pages we want to get and how many object should this page contain. 48 | 49 | **The action, that is achieved with paging, is aquivalent to "WHERE ROWNUM <= 5" in Oracle or "LIMIT 5" in PostgreSQL** 50 | 51 | ```java 52 | Pageable firstPageWithFiveElements = PageRequest.of(0, 5); 53 | 54 | Page allProductsFirstPage = repository.findAll(firstPageWithTwoElements); 55 | 56 | ``` 57 | 58 | We can return Page object or List object from findAll* method. Page is a list, that also knows about hte total number of available pages. 59 | 60 | ## Paging and Sorting 61 | We can also use paging and sorting together. For example, if we want the five products with the highest price, we can use following code: 62 | 63 | ```java 64 | Pageable sortedByPriceDescTopFive = 65 | PageRequest.of(0, 5, Sort.by("price").descending()); 66 | 67 | List topExpensiveProducts = 68 | findAll(sortedByPriceDescTopFive); 69 | ``` 70 | 71 | 72 | Pageable javadoc: https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Pageable.html 73 | 74 | PageRequest javadoc: https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/PageRequest.html -------------------------------------------------------------------------------- /.obsidian/workspace: -------------------------------------------------------------------------------- 1 | { 2 | "main": { 3 | "id": "5ddbf2a2b8419835", 4 | "type": "split", 5 | "children": [ 6 | { 7 | "id": "cc8a1dcc5ae1ec20", 8 | "type": "leaf", 9 | "state": { 10 | "type": "markdown", 11 | "state": { 12 | "file": "Spring Security/LDAP/Spring Security LDAP.md", 13 | "mode": "source", 14 | "source": true 15 | } 16 | } 17 | } 18 | ], 19 | "direction": "vertical" 20 | }, 21 | "left": { 22 | "id": "ef3f135d335bf58f", 23 | "type": "split", 24 | "children": [ 25 | { 26 | "id": "72e8ab8ab9959ef9", 27 | "type": "tabs", 28 | "children": [ 29 | { 30 | "id": "29ec377731b5825e", 31 | "type": "leaf", 32 | "state": { 33 | "type": "file-explorer", 34 | "state": {} 35 | } 36 | }, 37 | { 38 | "id": "56f08bc03e618dec", 39 | "type": "leaf", 40 | "state": { 41 | "type": "search", 42 | "state": { 43 | "query": "", 44 | "matchingCase": false, 45 | "explainSearch": false, 46 | "collapseAll": false, 47 | "extraContext": false, 48 | "sortOrder": "alphabetical" 49 | } 50 | } 51 | } 52 | ] 53 | } 54 | ], 55 | "direction": "horizontal", 56 | "width": 350 57 | }, 58 | "right": { 59 | "id": "4206c3ce913ef184", 60 | "type": "split", 61 | "children": [ 62 | { 63 | "id": "e473df0e45ecbe8c", 64 | "type": "tabs", 65 | "children": [ 66 | { 67 | "id": "b81022e443fc690f", 68 | "type": "leaf", 69 | "state": { 70 | "type": "backlink", 71 | "state": { 72 | "file": "Spring Security/LDAP/Spring Security LDAP.md", 73 | "collapseAll": false, 74 | "extraContext": false, 75 | "sortOrder": "alphabetical", 76 | "showSearch": false, 77 | "searchQuery": "", 78 | "backlinkCollapsed": false, 79 | "unlinkedCollapsed": true 80 | } 81 | } 82 | } 83 | ] 84 | } 85 | ], 86 | "direction": "horizontal", 87 | "width": 300, 88 | "collapsed": true 89 | }, 90 | "active": "cc8a1dcc5ae1ec20", 91 | "lastOpenFiles": [ 92 | "Spring Security/LDAP/Spring Security LDAP.md", 93 | "Spring Security/Spring Security.md", 94 | "Spring Security/LDAP/LDAP Protocoll.md", 95 | "TBD/TODO-List.md", 96 | "Playlists.md", 97 | "README.md", 98 | "Spring Data/JPA Repository.md", 99 | "Spring Data/CRUD Repository.md", 100 | "Spring Data/Spring Data JPA/Spring Data JPA.md", 101 | "Spring Data/Repository Types.md" 102 | ] 103 | } -------------------------------------------------------------------------------- /Spring Security/Authentication/Configuring the Users with DataSource.md: -------------------------------------------------------------------------------- 1 | In practice the users are stored in some database. If we want to work with this database with JDBC, we have to use an instance of _DataSource_. 2 | 3 | We have to add the _DataSource_, and Spring will inject it. If we add the [[H2 Database]] to dependencies, Spring will start automatically. 4 | 5 | 6 | ## Hardcoding the Users and Schema 7 | 8 | The default schema will be created, and then some hardcoded users inserted. 9 | 10 | ```java 11 | @EnableWebSecurity 12 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 13 | 14 | private final DataSource dataSource; 15 | 16 | @Autowired 17 | public SecurityConfiguration(DataSource dataSource) { 18 | this.dataSource = dataSource; 19 | } 20 | 21 | @Override 22 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 23 | auth.jdbcAuthentication() 24 | .dataSource(dataSource) 25 | .withDefaultSchema() 26 | .withUser( 27 | User.withUsername("user") 28 | .password("password") 29 | .roles("USER") 30 | ) 31 | .withUser( 32 | User.withUsername("admin") 33 | .password("admin") 34 | .roles("ADMIN") 35 | ); 36 | } 37 | 38 | @Bean 39 | public PasswordEncoder getPasswordEncoder() { 40 | return NoOpPasswordEncoder.getInstance(); 41 | } 42 | } 43 | ``` 44 | 45 | ## Getting the Users from Database 46 | ### Default Schema 47 | If the database with users and authorities is configured and filled, we can just tell spring to use it. 48 | 49 | ```java 50 | @EnableWebSecurity 51 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 52 | 53 | private final DataSource dataSource; 54 | 55 | @Autowired 56 | public SecurityConfiguration(DataSource dataSource) { 57 | this.dataSource = dataSource; 58 | } 59 | 60 | @Override 61 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 62 | auth.jdbcAuthentication() 63 | .dataSource(dataSource); 64 | } 65 | 66 | @Bean 67 | public PasswordEncoder getPasswordEncoder() { 68 | return NoOpPasswordEncoder.getInstance(); 69 | } 70 | } 71 | ``` 72 | 73 | Required schema is described here: [[Default User Schema]]. 74 | 75 | ### Custom Schema 76 | If we don't want to use default schema, we have to pass the SQL Queries in corresponding authentication methods: _usersByUsernameQuery(String query)_ and _authoritiesByUsernameQuery(String query)_. 77 | 78 | ```java 79 | @EnableWebSecurity 80 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 81 | 82 | private final DataSource dataSource; 83 | 84 | @Autowired 85 | public SecurityConfiguration(DataSource dataSource) { 86 | this.dataSource = dataSource; 87 | } 88 | 89 | @Override 90 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 91 | auth.jdbcAuthentication() 92 | .dataSource(dataSource) 93 | .usersByUsernameQuery( 94 | "SELECT username, password, enabled " + 95 | "FROM users " + 96 | "WHERE username = ?" 97 | ) 98 | .authoritiesByUsernameQuery( 99 | "SELECT username, authority " + 100 | "FROM authorities " + 101 | "WHERE username = ?" 102 | ); 103 | } 104 | 105 | @Bean 106 | public PasswordEncoder getPasswordEncoder() { 107 | return NoOpPasswordEncoder.getInstance(); 108 | } 109 | } 110 | ``` 111 | 112 | 113 | ## Links 114 | 115 | Video: https://www.youtube.com/watch?v=LKvrFltAgCQ&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE&index=7 116 | 117 | 118 | -------------------------------------------------------------------------------- /Spring MVC/Rest Controller.md: -------------------------------------------------------------------------------- 1 | We can create a controller for REST API with @RestController annotation. It is just a combination of the @Controller and the @ResponseBody annotations. 2 | 3 | ```java 4 | @RestController 5 | public class HelloController { 6 | 7 | @RequestMapping(method = RequestMethod.GET, value = "/hello") 8 | public String sayHello() { 9 | return "Hello"; 10 | } 11 | } 12 | ``` 13 | 14 | Controllers are using Servlets intermally: [[Servlets and Controllers]] 15 | 16 | # Mapping of HTTP Methods 17 | 18 | ## GET Endpoints 19 | 20 | We can return different object types and data structures from controller, not only the strings. Objects will be transformed internally to jsons. 21 | 22 | ```java 23 | @RestController 24 | public class BookController { 25 | private final BookService bookService; 26 | 27 | @Autowired 28 | public BookController(BookService bookService) { 29 | this.bookService = bookService; 30 | } 31 | 32 | @RequestMapping(method = RequestMethod.GET, value = "/books") 33 | public List getAllBooks() { 34 | return bookService.getAllBooks(); 35 | } 36 | 37 | @RequestMapping(method = RequestMethod.GET, value = "/books/{id}") 38 | public Book getBookById(@PathVariable("id") Long id) { 39 | return bookService.getBookById(id); 40 | } 41 | } 42 | ``` 43 | 44 | The Service BookService is described here: [[Service]] 45 | 46 | I'll use Postman to test the endpoints. The endpoint _/books_ returns a Json Array. 47 | GET http://localhost:8080/books -> 48 | 49 | ```json 50 | [ 51 | { 52 | "id": 145, 53 | "title": "Spring", 54 | "author": "Baeldung" 55 | }, 56 | { 57 | "id": 932, 58 | "title": "Operating Systems", 59 | "author": "Tanenbaum" 60 | }, 61 | { 62 | "id": 12, 63 | "title": "Clean Code", 64 | "author": "Uncle Bob" 65 | } 66 | ] 67 | ``` 68 | 69 | Links: 70 | - https://www.youtube.com/watch?v=oRFCeRVWCNE&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=11 71 | - https://www.youtube.com/watch?v=gDHSLKmG8ZQ&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=12 72 | - 73 | #### Variables Mapping 74 | ```java 75 | @RestController 76 | public class BookController { 77 | private final BookService bookService; 78 | 79 | @Autowired 80 | public BookController(BookService bookService) { 81 | this.bookService = bookService; 82 | } 83 | 84 | @RequestMapping(method = RequestMethod.GET, value = "/books") 85 | public List getAllBooks() { 86 | return bookService.getAllBooks(); 87 | } 88 | 89 | @RequestMapping( method = RequestMethod.GET, value = "/books/{id}") 90 | public Book getBookById(@PathVariable("id") Long id) { 91 | return bookService.getBookById(id); 92 | } 93 | } 94 | ``` 95 | 96 | We can define our variable position in URL, and use annotation @PathVariable to connect it with java parameter. 97 | 98 | We can omit the name parameter of @PathVariable, if the variable name corresponds with name in URL. Long id and {id}. 99 | 100 | ```java 101 | @RequestMapping(method = RequestMethod.GET, value = "/books/{id}") 102 | public Book getBookById(@PathVariable Long id) { 103 | return bookService.getBookById(id); 104 | } 105 | 106 | ``` 107 | 108 | But if the names are different, we have to define the name: 109 | ```java 110 | @RequestMapping(method = RequestMethod.GET, value = "/books/{id}") 111 | public Book getBookById(@PathVariable("id") Long identifier) { 112 | return bookService.getBookById(identifier); 113 | } 114 | 115 | ``` 116 | 117 | Type will be converted automatically. If type is incorrect, server will send Bad Request Error. 118 | 119 | Get http://localhost:8080/books/12 -> 120 | ```json 121 | { 122 | "id": 12, 123 | "title": "Clean Code", 124 | "author": "Uncle Bob" 125 | } 126 | ``` 127 | 128 | Links: 129 | - https://www.youtube.com/watch?v=AI2oBJkPK3c&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=18 130 | 131 | 132 | ## POST Endpoints 133 | We have to set the RequestMethod, and use the _@RequestBody_ annotation. _@RequestBody_ marks, that Http Body contains a JSON, that should be mapped to the Book object. 134 | 135 | ```java 136 | @RequestMapping(method = RequestMethod.POST, value = "/books") 137 | public void addNewBook(@RequestBody Book book) { 138 | bookService.addBook(book); 139 | } 140 | ``` 141 | 142 | Links: 143 | - https://www.youtube.com/watch?v=AI2oBJkPK3c&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=19 144 | 145 | ## PUT Endpoints 146 | Like Post Endpoint, but requires some additional key (depends on business logic) and PUT parameter. 147 | 148 | ```java 149 | @RequestMapping(method = RequestMethod.PUT, value = "/books/{id}") 150 | public void addNewBook(@RequestBody Book book, @PathVariable Long id) { 151 | bookService.updateBookWithExistingId(book, id); 152 | } 153 | ``` 154 | 155 | Links: 156 | - https://www.youtube.com/watch?v=AI2oBJkPK3c&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=20 157 | 158 | 159 | ## DELETE Endpoints 160 | Requires DELETE parameter. 161 | ```java 162 | @RequestMapping(method = RequestMethod.DELETE, value = "/books/{id}") 163 | public void addNewBook(@PathVariable Long id) { 164 | bookService.deleteBookById(id); 165 | } 166 | ``` 167 | 168 | Links: 169 | - https://www.youtube.com/watch?v=AI2oBJkPK3c&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x&index=20 170 | 171 | # Wrappers for Mapping Annotations 172 | We can also use some wrappera annotations for @RequestMapping, for each HTTP Method. 173 | 174 | ```java 175 | @RequestMapping(method = RequestMethod.GET, value = "/books") 176 | public List getAllBooks() { 177 | return bookService.getAllBooks(); 178 | } 179 | ``` 180 | 181 | 182 | ```java 183 | @GetMapping("/books") 184 | public List getAllBooks() { 185 | return bookService.getAllBooks(); 186 | } 187 | ``` -------------------------------------------------------------------------------- /Spring Security/Authentication/Configuring the Users with UserDetailsService.md: -------------------------------------------------------------------------------- 1 | Instead of getting a users directly from the _DataSource_ we can add one more abstraction level, and use the _UserDetailsService_. 2 | 3 | The usage of _DataSource_ is described here: [[Configuring the Users with DataSource]]. 4 | 5 | ## Hardcoded user 6 | Let's add an instance, that implements an _UserDetailsService_ interface. 7 | 8 | ```java 9 | @EnableWebSecurity 10 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 11 | 12 | private final UserDetailsService userDetailsService; 13 | 14 | @Autowired 15 | public SecurityConfiguration(HardcodedUserDetailsService userDetailsService) { 16 | this.userDetailsService = userDetailsService; 17 | } 18 | 19 | @Override 20 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 21 | auth.userDetailsService(userDetailsService); 22 | } 23 | } 24 | ``` 25 | 26 | The purpose of _UserDetailsService_ - get the userName and return an object that implements an _UserDetails_ interface. It can be some hardcoded user, it can be retrieved from a database JDBC directly or with JPA indirectly, it can be read from some textfile etc. It has to be implemented, and it is fully generic abstraction. 27 | 28 | In this example we will simply return a user with password "password" and role "ROLE_USER" for all userNames; 29 | 30 | ```java 31 | @Service 32 | public class HardcodedUserDetailsService implements UserDetailsService { 33 | 34 | @Override 35 | public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { 36 | return new HardcodedUserDetails(userName); 37 | } 38 | } 39 | ``` 40 | 41 | We have to implement a bunch of methods to implement the interface _UserDetails_ 42 | 43 | 44 | ```java 45 | public class HardcodedUserDetails implements UserDetails { 46 | private final String userName; 47 | 48 | public HardcodedUserDetails(String userName) { 49 | this.userName = userName; 50 | } 51 | 52 | @Override 53 | public Collection getAuthorities() { 54 | return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")); 55 | } 56 | 57 | @Override 58 | public String getPassword() { 59 | return "password"; 60 | } 61 | 62 | @Override 63 | public String getUsername() { 64 | return userName; 65 | } 66 | 67 | @Override 68 | public boolean isAccountNonExpired() { 69 | return true; 70 | } 71 | 72 | @Override 73 | public boolean isAccountNonLocked() { 74 | return true; 75 | } 76 | 77 | @Override 78 | public boolean isCredentialsNonExpired() { 79 | return true; 80 | } 81 | 82 | @Override 83 | public boolean isEnabled() { 84 | return true; 85 | } 86 | } 87 | ``` 88 | 89 | ## Accessing the Users from External Database with JPA 90 | Let's assume, that we have configuted some external database with table _users_, where each user has some id, username, password, active state and roles. 91 | 92 | Connecting to External Database: [[Connecting to Database with JPA]] 93 | 94 | We have to define the user JPA Entity: 95 | 96 | ```java 97 | @Entity 98 | @Table(name = "users") 99 | public class User { 100 | @Id 101 | @GeneratedValue(strategy = GenerationType.AUTO) 102 | private int id; 103 | private String username; 104 | private String password; 105 | private boolean active; 106 | private String roles; 107 | 108 | public int getId() { 109 | return id; 110 | } 111 | 112 | public void setId(int id) { 113 | this.id = id; 114 | } 115 | 116 | public String getUsername() { 117 | return username; 118 | } 119 | 120 | public void setUsername(String userName) { 121 | this.username = userName; 122 | } 123 | 124 | public String getPassword() { 125 | return password; 126 | } 127 | 128 | public void setPassword(String password) { 129 | this.password = password; 130 | } 131 | 132 | public boolean isActive() { 133 | return active; 134 | } 135 | 136 | public void setActive(boolean active) { 137 | this.active = active; 138 | } 139 | 140 | public String getRoles() { 141 | return roles; 142 | } 143 | 144 | public void setRoles(String roles) { 145 | this.roles = roles; 146 | } 147 | } 148 | 149 | ``` 150 | 151 | And a repository, to get the users by name: 152 | 153 | ```java 154 | public interface UserRepository extends JpaRepository { 155 | Optional findByUsername(String userName); 156 | } 157 | ``` 158 | 159 | Create a mapping from database entity to _UserDetails_ object. Note, that roles in database is a CSV string, and it has to be converted to list of _SimpleGrantedAuthority_ objects. 160 | 161 | ```java 162 | public class CustomUserDetails implements UserDetails { 163 | private final String userName; 164 | private final String password; 165 | private final boolean active; 166 | private final List authorities; 167 | 168 | public CustomUserDetails(User user) { 169 | this.userName = user.getUsername(); 170 | this.password = user.getPassword(); 171 | this.active = user.isActive(); 172 | this.authorities = Arrays.stream(user.getRoles().split(",")) 173 | .map(SimpleGrantedAuthority::new) 174 | .collect(Collectors.toList()); 175 | 176 | } 177 | 178 | @Override 179 | public Collection getAuthorities() { 180 | return authorities; 181 | } 182 | 183 | @Override 184 | public String getPassword() { 185 | return password; 186 | } 187 | 188 | @Override 189 | public String getUsername() { 190 | return userName; 191 | } 192 | 193 | @Override 194 | public boolean isAccountNonExpired() { 195 | return true; 196 | } 197 | 198 | @Override 199 | public boolean isAccountNonLocked() { 200 | return true; 201 | } 202 | 203 | @Override 204 | public boolean isCredentialsNonExpired() { 205 | return true; 206 | } 207 | 208 | @Override 209 | public boolean isEnabled() { 210 | return active; 211 | } 212 | } 213 | 214 | ``` 215 | 216 | Then we have to implement the _UserDetailService_, that returns a _CustomUserDetails_ object, if an user with given userName was found in database. 217 | 218 | ```java 219 | @Service 220 | public class JpaUserDetailsService implements UserDetailsService { 221 | 222 | private final UserRepository userRepository; 223 | 224 | @Autowired 225 | public JpaUserDetailsService(UserRepository userRepository) { 226 | this.userRepository = userRepository; 227 | } 228 | 229 | @Override 230 | public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { 231 | Optional user = userRepository.findByUsername(userName); 232 | user.orElseThrow(() -> new UsernameNotFoundException("Not found: " + userName)); 233 | return user.map(CustomUserDetails::new).get(); 234 | } 235 | } 236 | ``` 237 | 238 | At the end, edit the _SecurityConfiguration_, to use the _JpaUserDetailsService_. 239 | 240 | ```java 241 | @EnableWebSecurity 242 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 243 | 244 | private final UserDetailsService userDetailsService; 245 | 246 | @Autowired 247 | public SecurityConfiguration(JpaUserDetailsService userDetailsService) { 248 | this.userDetailsService = userDetailsService; 249 | } 250 | 251 | @Override 252 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 253 | auth.userDetailsService(userDetailsService); 254 | } 255 | 256 | @Bean 257 | public PasswordEncoder getPasswordEncoder() { 258 | return NoOpPasswordEncoder.getInstance(); 259 | } 260 | } 261 | 262 | ``` 263 | 264 | ## Links 265 | https://www.youtube.com/watch?v=TNt3GHuayXs&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE&index=8 266 | -------------------------------------------------------------------------------- /.obsidian/plugins/obsidian-git/styles.css: -------------------------------------------------------------------------------- 1 | @keyframes loading { 2 | 0% { 3 | transform: rotate(0deg); 4 | } 5 | 100% { 6 | transform: rotate(360deg); 7 | } 8 | } 9 | 10 | .loading > svg { 11 | animation: 2s linear infinite loading; 12 | transform-origin: 50% 50%; 13 | display: inline-block; 14 | } 15 | .obsidian-git-center { 16 | margin: auto; 17 | width: 50%; 18 | } 19 | .tooltip.mod-left { 20 | overflow-wrap: break-word; 21 | } 22 | .tooltip.mod-right { 23 | overflow-wrap: break-word; 24 | } 25 | .obsidian-git-shortcuts { 26 | margin: 10px; 27 | } 28 | 29 | .diff-err { 30 | height: 100%; 31 | display: flex; 32 | justify-content: center; 33 | flex-direction: column; 34 | align-items: center; 35 | } 36 | 37 | .diff-err-sign { 38 | font-size: 2em; 39 | } 40 | 41 | .d2h-d-none { 42 | display: none; 43 | } 44 | .d2h-wrapper { 45 | text-align: left; 46 | } 47 | .d2h-file-header { 48 | background-color: var(--background-primary); 49 | border-bottom: 1px solid var(--interactive-accent); 50 | font-family: var(--font-monospace); 51 | height: 35px; 52 | padding: 5px 10px; 53 | } 54 | .d2h-file-header, 55 | .d2h-file-stats { 56 | display: -webkit-box; 57 | display: -ms-flexbox; 58 | display: flex; 59 | } 60 | .d2h-file-stats { 61 | font-size: 14px; 62 | margin-left: auto; 63 | } 64 | .d2h-lines-added { 65 | border: 1px solid #b4e2b4; 66 | border-radius: 5px 0 0 5px; 67 | color: #399839; 68 | padding: 2px; 69 | text-align: right; 70 | vertical-align: middle; 71 | } 72 | .d2h-lines-deleted { 73 | border: 1px solid #e9aeae; 74 | border-radius: 0 5px 5px 0; 75 | color: #c33; 76 | margin-left: 1px; 77 | padding: 2px; 78 | text-align: left; 79 | vertical-align: middle; 80 | } 81 | .d2h-file-name-wrapper { 82 | -webkit-box-align: center; 83 | -ms-flex-align: center; 84 | align-items: center; 85 | display: -webkit-box; 86 | display: -ms-flexbox; 87 | display: flex; 88 | font-size: 15px; 89 | width: 100%; 90 | } 91 | .d2h-file-name { 92 | overflow-x: hidden; 93 | text-overflow: ellipsis; 94 | white-space: nowrap; 95 | } 96 | .d2h-file-wrapper { 97 | border: 1px solid var(--background-modifier-border); 98 | border-radius: 3px; 99 | margin-bottom: 1em; 100 | } 101 | .d2h-file-collapse { 102 | -webkit-box-pack: end; 103 | -ms-flex-pack: end; 104 | -webkit-box-align: center; 105 | -ms-flex-align: center; 106 | align-items: center; 107 | border: 1px solid var(--background-modifier-border); 108 | border-radius: 3px; 109 | cursor: pointer; 110 | display: none; 111 | font-size: 12px; 112 | justify-content: flex-end; 113 | padding: 4px 8px; 114 | } 115 | .d2h-file-collapse.d2h-selected { 116 | background-color: #c8e1ff; 117 | } 118 | .d2h-file-collapse-input { 119 | margin: 0 4px 0 0; 120 | } 121 | .d2h-diff-table { 122 | border-collapse: collapse; 123 | font-family: Menlo, Consolas, monospace; 124 | font-size: 13px; 125 | width: 100%; 126 | } 127 | .d2h-files-diff { 128 | width: 100%; 129 | } 130 | .d2h-file-diff { 131 | overflow-y: hidden; 132 | } 133 | .d2h-file-side-diff { 134 | display: inline-block; 135 | margin-bottom: -8px; 136 | margin-right: -4px; 137 | overflow-x: scroll; 138 | overflow-y: hidden; 139 | width: 50%; 140 | } 141 | .d2h-code-line { 142 | padding: 0 8em; 143 | } 144 | .d2h-code-line, 145 | .d2h-code-side-line { 146 | display: inline-block; 147 | -webkit-user-select: none; 148 | -moz-user-select: none; 149 | -ms-user-select: none; 150 | user-select: none; 151 | white-space: nowrap; 152 | width: 100%; 153 | } 154 | .d2h-code-side-line { 155 | padding: 0 4.5em; 156 | } 157 | .d2h-code-line-ctn { 158 | word-wrap: normal; 159 | background: none; 160 | display: inline-block; 161 | padding: 0; 162 | -webkit-user-select: text; 163 | -moz-user-select: text; 164 | -ms-user-select: text; 165 | user-select: text; 166 | vertical-align: middle; 167 | white-space: pre; 168 | width: 100%; 169 | } 170 | .theme-light .d2h-code-line del, 171 | .theme-light .d2h-code-side-line del { 172 | background-color: #ffb6ba; 173 | } 174 | .theme-dark .d2h-code-line del, 175 | .theme-dark .d2h-code-side-line del { 176 | background-color: #8d232881; 177 | } 178 | .d2h-code-line del, 179 | .d2h-code-line ins, 180 | .d2h-code-side-line del, 181 | .d2h-code-side-line ins { 182 | border-radius: 0.2em; 183 | display: inline-block; 184 | margin-top: -1px; 185 | text-decoration: none; 186 | vertical-align: middle; 187 | } 188 | .theme-light .d2h-code-line ins, 189 | .theme-light .d2h-code-side-line ins { 190 | background-color: #97f295; 191 | text-align: left; 192 | } 193 | .theme-dark .d2h-code-line ins, 194 | .theme-dark .d2h-code-side-line ins { 195 | background-color: #1d921996; 196 | text-align: left; 197 | } 198 | .d2h-code-line-prefix { 199 | word-wrap: normal; 200 | background: none; 201 | display: inline; 202 | padding: 0; 203 | white-space: pre; 204 | } 205 | .line-num1 { 206 | float: left; 207 | } 208 | .line-num1, 209 | .line-num2 { 210 | -webkit-box-sizing: border-box; 211 | box-sizing: border-box; 212 | overflow: hidden; 213 | padding: 0 0.5em; 214 | text-overflow: ellipsis; 215 | width: 3.5em; 216 | } 217 | .line-num2 { 218 | float: right; 219 | } 220 | .d2h-code-linenumber { 221 | background-color: var(--background-primary); 222 | border: solid var(--background-modifier-border); 223 | border-width: 0 1px; 224 | -webkit-box-sizing: border-box; 225 | box-sizing: border-box; 226 | color: var(--text-muted); 227 | cursor: pointer; 228 | display: inline-block; 229 | position: absolute; 230 | text-align: right; 231 | width: 7.5em; 232 | } 233 | .d2h-code-linenumber:after { 234 | content: "\200b"; 235 | } 236 | .d2h-code-side-linenumber { 237 | background-color: var(--background-primary); 238 | border: solid var(--background-modifier-border); 239 | border-width: 0 1px; 240 | -webkit-box-sizing: border-box; 241 | box-sizing: border-box; 242 | color: var(--text-muted); 243 | cursor: pointer; 244 | display: inline-block; 245 | overflow: hidden; 246 | padding: 0 0.5em; 247 | position: absolute; 248 | text-align: right; 249 | text-overflow: ellipsis; 250 | width: 4em; 251 | } 252 | .d2h-code-side-linenumber:after { 253 | content: "\200b"; 254 | } 255 | .d2h-code-side-emptyplaceholder, 256 | .d2h-emptyplaceholder { 257 | background-color: var(--background-primary); 258 | border-color: var(--background-modifier-border); 259 | } 260 | .d2h-code-line-prefix, 261 | .d2h-code-linenumber, 262 | .d2h-code-side-linenumber, 263 | .d2h-emptyplaceholder { 264 | -webkit-user-select: none; 265 | -moz-user-select: none; 266 | -ms-user-select: none; 267 | user-select: none; 268 | } 269 | .d2h-code-linenumber, 270 | .d2h-code-side-linenumber { 271 | direction: rtl; 272 | } 273 | .theme-light .d2h-del { 274 | background-color: #fee8e9; 275 | border-color: #e9aeae; 276 | } 277 | .theme-light .d2h-ins { 278 | background-color: #dfd; 279 | border-color: #b4e2b4; 280 | } 281 | .theme-dark .d2h-del { 282 | background-color: #521b1d83; 283 | border-color: #691d1d73; 284 | } 285 | .theme-dark .d2h-ins { 286 | background-color: rgba(30, 71, 30, 0.5); 287 | border-color: #13501381; 288 | } 289 | .d2h-info { 290 | background-color: var(--background-primary); 291 | border-color: var(--background-modifier-border); 292 | color: var(--text-normal); 293 | } 294 | .theme-light .d2h-file-diff .d2h-del.d2h-change { 295 | background-color: #fdf2d0; 296 | } 297 | .theme-dark .d2h-file-diff .d2h-del.d2h-change { 298 | background-color: #55492480; 299 | } 300 | .theme-light .d2h-file-diff .d2h-ins.d2h-change { 301 | background-color: #ded; 302 | } 303 | .theme-dark .d2h-file-diff .d2h-ins.d2h-change { 304 | background-color: rgba(37, 78, 37, 0.418); 305 | } 306 | .d2h-file-list-wrapper { 307 | margin-bottom: 10px; 308 | } 309 | .d2h-file-list-wrapper a { 310 | color: #3572b0; 311 | text-decoration: none; 312 | } 313 | .d2h-file-list-wrapper a:visited { 314 | color: #3572b0; 315 | } 316 | .d2h-file-list-header { 317 | text-align: left; 318 | } 319 | .d2h-file-list-title { 320 | font-weight: 700; 321 | } 322 | .d2h-file-list-line { 323 | display: -webkit-box; 324 | display: -ms-flexbox; 325 | display: flex; 326 | text-align: left; 327 | } 328 | .d2h-file-list { 329 | display: block; 330 | list-style: none; 331 | margin: 0; 332 | padding: 0; 333 | } 334 | .d2h-file-list > li { 335 | border-bottom: 1px solid var(--background-modifier-border); 336 | margin: 0; 337 | padding: 5px 10px; 338 | } 339 | .d2h-file-list > li:last-child { 340 | border-bottom: none; 341 | } 342 | .d2h-file-switch { 343 | cursor: pointer; 344 | display: none; 345 | font-size: 10px; 346 | } 347 | .d2h-icon { 348 | fill: currentColor; 349 | margin-right: 10px; 350 | vertical-align: middle; 351 | } 352 | .d2h-deleted { 353 | color: #c33; 354 | } 355 | .d2h-added { 356 | color: #399839; 357 | } 358 | .d2h-changed { 359 | color: #d0b44c; 360 | } 361 | .d2h-moved { 362 | color: #3572b0; 363 | } 364 | .d2h-tag { 365 | background-color: var(--background-primary); 366 | display: -webkit-box; 367 | display: -ms-flexbox; 368 | display: flex; 369 | font-size: 10px; 370 | margin-left: 5px; 371 | padding: 0 2px; 372 | } 373 | .d2h-deleted-tag { 374 | border: 2px solid #c33; 375 | } 376 | .d2h-added-tag { 377 | border: 1px solid #399839; 378 | } 379 | .d2h-changed-tag { 380 | border: 1px solid #d0b44c; 381 | } 382 | .d2h-moved-tag { 383 | border: 1px solid #3572b0; 384 | } 385 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------