An online markdown blog and knowledge repository.
31-May through 3-June 2022
For the next 2 weeks: Working on building servers in Java.
Lots of assignments / calendar will be shifted around a bit due to Memorial Day.
Using URL Params to make sites reactive.
Personal Pitches:
Whenever doing data structures make them generic it just makes sense.
When using a built-in Class or 3rd Party Package you should at least review its description, usage, etc. This could be good if asked about it while reviewing code.
When opening HttpUrlConnection in Java, remember to call '.close()' method or use Try with resources so that when done, memory resources are freed.
Career Coaching Friday! Get your plan in now.
Midterm Project: Does not have to be a website! Could be a cool tool.
This week:
Difference between a Framework and a Library:
Spring MVC is a Framework.
MVC is a design pattern.
Spring has pretty thorough documentation so use it!
Spring enables creating Java Servers.
Model: A description of the data that will be read, written, and transformed (or transported between functions and components).
View: A template that defines a graphical interface (UI).
Controller: Handles logic of a resources.
In Spring MVC only one Model can be injected into each View so it is critical to create Models that properly model the expected data returned from the DB.
Controllers are defined following Separation of Responsibility coding practices.
Mongo is a non-relational database, so scalability can be a limitation.
SQL is a relational database and is very scalable.
SQL implements it's own ID field in data.
UUID is a user-defined ID that might be a good idea to implement depending on app and dev requirements.
Fields must be defined specifically e.g. String Name, and FK Colors.ID.
1:1 => The data just goes into the record directly.
1:Many => Use an FK (Foreign Key) to point to the table and ID where the data resides.
Note: Domain Model these relationships every time before implementing a SQL DB.
Spring Initializr website
We will be using this going forward with Spring-based development.
Enables setting:
Metadata:
DO: Click Generate => Zip is downloaded to your localhost. THEN: Unzip to your project location and then open your IDE to the root of the project. ALSO: Verify '.gitignore' has the correct additions to avoid sharing built code and other Project details related to your IDE settings.
application.properties: Synonymous with '.env' file.
main resources static: CSS, Images, and non-dynamic HTML files like 'index.html'.
Create new Folders and Files to store CSS etc e.g. 'resources/static.css/style.css'.
src main java com.ProjectName.Name => Add a '$name$Controller' file.
Yes BOOTSTRAP CAN BE USED!! Import Bootstrap to Spring MVC: TBD
Resource: Bootstrap CSS in Spring MVC on StackOverflow
Tomcat gets launched for you using a default port 8080.
Note: Use 'kill pid' to get rid of a lingering Tomcat instance.
This enables dynamic web pages.
Define the controller with '@Controller' to describe the Class.
Set the Map using '@RequestMapping(String)` to describe the Class.
For now: Make all Controllers using public access modifiers.
Process:
Set the request method
Set either a Response Body or use A Model:
Set up a View for the results to be sent to (else WhiteLabel Error)
Use RESTful commands for these Controllers: GET, POST, PUT, and DELETE
Think of Controllers as the logic for your resource.
Domain Model your Controllers to define:
Use '@PathVariable' keyword with the method definition like public String doThing(@PathVariable String paramName){}
Use '@RequestParam';' keyword to extract query parameters, form parameters, or files from the web Request.
Manual reload is just the Reload button in the IDE.
TBD
URL Parameters can be captured by Controllers.
POST Calls will include data (TBD).
Do NOT use '@ResponseBody' because a Model will do this for us.
Return type is still String.
Return statement will include "model" i.e. return "model"
so that the model itself is returns (this is a Spring MVC implementation detail).
Thymeleaf looks at directory 'templates' when return "model"
is used e.g. 'model.html'.
Thymeleaf will allow you to point to a template page within a folder using return "parentfolder/mymodel
will point to '.../templates/parentfolder/mymodel.html'.
Thymeleaf looks to the 'templates' folder to find the return type.
Thymeleaf attributes are th:name
which can be used within HTML elements.
Thymeleaf 'th' attributes use a template literal style notation: ${model.name}
<span th:text="${model.name}"></span>
In Spring, the actual Model is what is passed-in as params to a Controller (route).
Think of these Models as a data Schema.
MVC Model .addAttribute()
method accepts an Object Instance and is used as the Controller return type.
Fat Controller: Defines ALL or MOST processing and functionality within it.
Skinny Controller: Relies on other Modules, Packages, and internal Code to do the work, and the Controller's only purpose is to manage the path, parameters, and returning the correct View template.
NPM uses DI in terms of creating a dependency list and so on.
DI is more than what NPM does => Essentially it creates a dependency-filled object out-of-the-gate so that the object instance is ready for you when you need it within the App.
Common Dependencies We Will Use in Class:
Note: Images go into the resources folder in the project hierarchy.
Create a pseudo Queue that implements a standard Stack interface.
Create a pseudo Stack that implements a standard Queue interface.
Challenges include limited functionality use.
Hint: Use TWO Stack instances.
Note: Tests are required in this Code Challenge.
RESTful Routing with Spring MVC.
PostgreSQL as a relational DB.
JPA - Persistence API? Persist data into the DB.
JDBC - Connects to Postgres local or remote.
DB Connection String required (like everywhere else).
Midterm Prep starts on Monday 1-Jun-22.
Linux info follows:
psql --version
or which psql
sudo -u postgres psql
On my Ubuntu 20.04 system, psql installed to:
There are other config files that will be added here when I rediscover them.
Postgres instructions:
\l # returns a list of databases
CREATE DATABASE name # creates a new database named 'name'
; # ends a command line if multi-lined or ambiguous
\password
then it will prompt for new password.@RequestMapping("/path")
is OPTIONAL and should only be used if all other functionality in the Controller should be behind this mapping path decorator.
Schema and Class are similar, however they are syntactically different:
Rest architecture allows interacting with other REST APIs.
Architectural constraints are put in place.
Client Server architecture => made RESTful via HTTP.
Stateless: No data is stored between Req-Res.
No @RequestMapping("/...")
path in his SalmonCookiesStoresController.
th:each
enables iterating through an array of Attributes passed-in by the Controller.
Persisting Data: PJA
RESTful methods: Get, Post, Put, Delete
To implement CRUD operations we will need to:
JPA: Java Persistence API, retains/persists data.
JPA belongs on our Spring MVC Controller(s).
Other persistence APIs persist data between refresh, app close, caching data across sessions, cookies, and many more.
ORM: Object Relational Mapping => Describes relationships within a DB.
ORM Hibernate: ORM Framework for use with Java, Sring.
Recall: Frameworks have constraints, unless Libraries that do not.
ORM Hibernate enables similar functionality to Mongoose:
JDBC: Java Database Controller => Makes it easy to implement repositories for our DB.
JDBC belongs between JPA/Controller and the Database.
JDBC provides CRUD Services (to abstract-away the Database Interfacee?).
Services:
@Autowired
Dependency Injection:
Create a Repository:
Beans: Injected service representations withh nccionality e.g. repo methods and access.
Autowired: Part of DI system in Spring
PGAdmin => GUI Administrative tool for PostGres SQL installation instructions
PosteGresQL => PSQL is like PGAdmin
ORD: Object Relational Database => Extends SQL (the language)
JPA will be used to handle all the SQL Language details!
JDBC connects JPA to PostGres.
Once installed, set up a new SuperUser with your known password so you have access.
Do: Use SpringInitializr to simplify this process.
Build.Gradle:
application.properties:
After udpating Build.Gradle run ./gradlew build
to bring in the changes.
Define a Controller method with a return type of RedirectView.
And then the return statement: return new RedirectView("/");
Code Challenge 12: stack-queue-animal-shelter.
Manage Dequeue and Re-Enqueue animals.
Whiteboard this prior to doing ANY CODE.
File application.properties should NOT be pushed to GitHub.
Variable management will be necessary.
For now just gitignore it and shared GH pullers need to have their own application.properties.
Update Album so it can be stored in a database.
<form action="/" method="post">...
tells the Submit event where to send the data.
Call for TA help and get through this so that this does not become a blocking lab!
This stuff is hard but we've done it before. - Alex, basically
Focus on the Songr Controller.
Wiring-up the Controller with the DB is complicated: Lots of moving parts:
Thymeleaf is an MPA framework: Multi-page.
React is an SPA framework: Single-page.
Big O CheatSheet
Image Tag <img/>
must include a closing slash.
JPA turns your Class into an Entity.
Your classes only need to be attributed as @Entity
when it needs to be database related data.
An Entity needs an @Id
and the type is the Type that the Id column values are stored as (Long enables a HUGE number of item IDs).
Extending JpaRepository<T, U>
enables utilizing methods in the Repository, by calling your defined Repository.
A Repository represents a Table in your database!
Repository-to-table relationship is a one-to-one relationship.
SpringBoot Test: @SpringBootTest
Moch MVC: An un-real MVC version of an MVC, emulating YOUR IMPLEMENTAION. Decorate with @AutoConfigureMockMvc
Autowired: Dependancy Injection @Autowired
preceding the Type var_name;
statement.
The Baeldung reading assignment walks through Integration Testing in Spring.
Define each test the same way as before.
The 'Action' will be done on a Mock e.g. mockMvc.perform(get("/")).andDo(print()).andExpect(content().string(containsString("<h1>exact text match</h1>")));
Display data on console within a test: print()
Assert for a condition: .andExpect(condition_expression)
Check the returned content from the mock: content()
Test that content contains a specific String: string(containsString(substring))
Check out this Hava Ham Crest Tutorial
View <--> Controller Classes <--> Database <==> [Tables]
@Entity
, @Id
, @GeneratedValue(key=val)
to make them Identities.List<Employee> employees;
and decorate it with Attribute @OneToMay(mappedBy|cascade|others...="stringStoreName")
@ManyToOne
followed by the child-Entity Property e.g. SalmonCookiesStore salmonCookiesStore;
JpaRepository<ConcreteClass, ID-Type>{ // only add custom queries in here}
e.g. Store repo and Employee repo.@ManyToOne StoreNameProp storeName;
Fat vs. Skinny Controllers:
@Controller
attribute.@Autowired
followed by thingClassRepository thingClassRepositoryName;
@PostMapping("/path")
preceding the method to call when POST (in this example) is called public RedirectView methodName(args){ new-up an object, supply args to give it props, then return (a redirect?)}
@AutoWired
to define the Properties that are the Repositories (local and remote), and use the ParentRepository's .findByName(String)
(or find by ID, etc), create a new Parent instance, then pass that in to the new Child instance, then call the child Repository to save the data e.g. employeeRepository.save(newEmployee);
Cascading Deletions can be done with @Cascade
? TODO: Research for one of the stretch goals.
Names must match the expected input variable names.
You must use for=forName
and make it equal to id=forName
in order to capture data from, and supply data to, input elements.
Use type="hidden"
to track specific variables that must be maintained for submission (for a preloaded Form, right?).
Heap memory: How the computer stores data in RAM. Nodes of data insert themselves into the Heap.
Queue: The most important rule is FIFO.
Stack: The most important rule is LIFO.
Nodes: This really could be anything, but the properties and functionality of Top, Front, Rear, and Push/Pop, Enqueue/Dequeue, are all capabilities that are referred to as Nodes, but do not have to be.
Trees Have-A:
Other terminology:
Time: Big O(h) => Height Space: Big O(w) => Width
Iteration: Breadth First Search (BFS) is an Iterative traversal method. Horizoantally traversing the nodes.
Recursion: Depth First Search (DFS) is a Recursive traversal method. Vertically traversing the nodes.
Always traverse child nodes from Parent's Left-to-Right.
Pre- In- and Post-Order methods describe your data logic:
Return to Parent Readme.md