Upload of pre-existing files

This commit is contained in:
Marcello Lamonaca 2021-01-31 11:05:37 +01:00
commit 4c21152830
150 changed files with 730703 additions and 0 deletions

115
Java/DAO.md Normal file
View file

@ -0,0 +1,115 @@
# Database Access Object
## DB
Connection to the DB.
```java
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DB {
private Connection conn; // db connection obj
private final String URL = "jdbc:<dbms>:<db_url>/<database>";
private final String USER = "";
private final String PWD = "";
public DB() {
this.conn = null;
}
public void connect() {
try {
this.conn = DriverManager.getConnection(URL, USER, PWD);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void disconnect() {
if(conn != null) {
try {
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public Connection getConn() {
return conn;
}
}
```
## `I<Type>DAO`
Interface for CRUD methods on a database.
```java
package dao;
import java.sql.SQLException;
import java.util.List;
public interface I<Type>DAO {
String RAW_QUERY = "SELECT * ..."
public Type Query() throws SQLException;
}
```
## `<Type>DAO`
Class implementing `I<Type>DAO` and handling the comunication with the db.
```java
package dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class <Type>DAO implements I<Type>DAO {
private <Type> results;
private Statement statement; // SQL instruction contenitor
private ResultSet rs; // Query results contenitor
private DB db;
public <Type>DAO() {
db = new DB();
}
@Override
public Type Query() throws SQLException {
// 1. connection
db.connect();
// 2. instruction
statement = db.getConn().createStatement(); // statement creation
// 3. query
rs = statement.executeQuery(RAW_QUERY); // set the query
// 4. results
while(rs.next()) {
// create and valorize Obj
// add to results
}
// 5. disconnection
db.disconnect()
// 6. return results
return results;
}
}
```

View file

@ -0,0 +1,122 @@
# Java Collection Framework - JCF
All classes that permit the handling of groups of objects constituite the Java Collection Framework.
A Collection is a *container* in which several objects are grouped in a *single entity*.
The **Java Collection Framework** is constituited by:
- **Interfaces** the define the operations of a generic collection. They can be split into two categories:
- **Collection**: used to optimize operations of insertion, modification and deletion of elements in a group of objects.
- **Map**: optimized for look-up operations.
- **Classes** that implement the interfaces using different data structures.
- **Algorithms** consistng in methods to operate over a collection.
![Java Collection Hierarchy](https://upload.wikimedia.org/wikipedia/commons/a/ab/Java.util.Collection_hierarchy.svg "Java Collection Hierarchy")
## java.util.Collections
### Collection Functions
```java
boolean add (Object o) e.g., <x>.add (<y>) //append to colelction, false if fails
boolean add (int index, Object o) //insertion at given index
boolean addAll (Collection c) //appends a collection to another
void clear() //remove items from container
boolean contains (Object o) //true if object is in collection
boolean containsAll (Collection c) //true if all items of collectio are in another
boolean isEmpty (Object o) e.g., if (<x>.isEmpty()) ... //true if collection is empty
boolean remove (Object o) //remove object from collection
Object remove (int index) //remove object at given index
void removeAll (Collection c) //remove all items form collection
int size () //number og items in collection
Object [] toArray() //transform collection in array
Iterator iterator() //returns iterator to iterate over the collection
```
### Collections Methods
```java
Collection<E>.forEach(Consumer<? super T> action);
```
### Iterator
Abstracts the problem of iterating over all the elements of a collection;
- `public Iterator (Collection c)` creates the Iterator
- `public boolean hasNext()` checks if there is a successive element
- `public Object next()` extracts the successive element
### ArrayList
**Note**: ArrayLists can't contain *primitive* values. *Use wrapper classes* instead.
```java
import java.util.ArrayList;
ArrayList<Type> ArrayListName = new ArrayList<Type>(starting_dim); //resizable array
ArrayList<Type> ArrayListName = new ArrayList<Type>(); //resizable array
ArrayList<Type> ArrayListName = new ArrayList<>(); //resizable array (JAVA 1.8+)
ArrayListName.add(item); //append item to collection
ArrayListName.add(index, item); // add item at positon index, shift all item from index and successive towards the end af the ArrayList
ArrayListName.set(index, item); // substitute EXISTING item
ArrayListName.get(index); //access to collection item
ArrayListName.remove(item) //remove first occurence of item from collection
ArrayListName.remove(index) //remove item at position index
ArrayListName.clear() //emties the ArrayList
ArrayListName.contains(object); // check if object is in the ArrayList
ArrayListName.IndexOf(object); // returns the index of the object
ArrayListName.isEmpty(); // check wether the list is empty
ArrayListName.size(); //dimension of the ArrayList
ArrayListName.tirmToSize(); // reduce ArrayList size to minimum needed
// ArrayList size doubles when a reseize is needed.
//run through to the collection with functional programming (JAVA 1.8+)
ArrayListName.forEach(item -> function(v));
```
### Collection Sorting
To sort a collection it's items must implement `Comparable<T>`:
```java
class ClassName implements Comparable<ClassName> {
@override
public int compareTo(Classname other){
//compare logic
return <int>;
}
}
List<ClassName> list;
//valorize List
Collections.sort(list); //"natuarl" sorting uses compareTo()
```
Otherwise a `Comparator()` must be implemented:
```java
class Classname {
//code here
}
// Interface object (!) implements directly a method
Comparator<ClassName> comparator = new Comparator<ClassName>() {
@Override
public int compare(ClassName o1, Classname o2) {
//compare logic
return <int>;
}
};
List<ClassName> list;
//valorize List
Collections.sort(list, comparator); //"natuarl" sorting uses compareTo()
```
`Comparator<T>` and `Conmparable<T>` are functional interfaces

115
Java/Java Web/JSP.md Normal file
View file

@ -0,0 +1,115 @@
# Java Server Pages Cheat Sheet
Java embedded in html.
Codice + JSP salvati in file `.war`
[TEMP Notes Source](https://github.com/maboglia/CorsoJava/blob/master/appunti/057_JSP_appunti.md#corso-jsp---le-direttive)
## Directives
Le direttive Le direttive permettono di definire la struttura di tutto il documento JSP. Indicano gli aspetti principali del *servlet* in cui sarà convertito il file JSP.
Sono processati al momento della conversione in servlet, a compile-time.
Le direttive esistenti sono: *page*, *include* e *taglib*.
- `<%@ page attribute="value" %>`
- `<%@ include file="path" %>`
- `<%@ taglib ...%>`
Introdotte dal simbolo `@` possono contenere diversi attributi, in alcuni casi concatenabili come per la direttiva import.
### Attributi Direttiva `Page`
**`import="package.class"`**
Lista di package o classes, separati da virgola, che saranno importati per essere utilizzati nel codice java.
**`session ="true | false"`**
Specifica se la pagina fa parte di una sessione HTTP. Se si inizializza a true, è disponibile l'oggetto implicito sessione.
**`buffer ="dimensione-kb"`**
Specifica la dimensione di un buffer di uscita di tipo stream, per il client.
**`errorPage="url"`**
Specifica una pagina JSP che sarà processata nel caso si verifichi un errore.
**`isErrorPage="true|false"`**
Indica che la pagina è una pagina di errore JSP e può mostrare a video l'output dell'errore verificatosi. Per default è settata false.
**`contentType="MIME-Type"`**, **`contentType="MIME-Type; charset=Character-Set"`**
valore MIME di default è text/html
### Direttiva `Include`
Indica al motore JSP di includere il contenuto del file corrispondente, inserendolo al posto della direttiva nella pagina JSP. Il contenuto del file incluso è analizzato al momento della traduzione del file JSP e si include una copia del file stesso nel servlet generato. Una volta incluso, se si modifica il file non sarà ricompilato nel servlet. Il tipo di file da includere può essere un file html (*statico*) o un file jsp (*dinamico*).
```jsp
<html>
<head>
<title> pagina di prova Direttive </title>
</head>
<body>
<h1>pagina di prova Direttive inclusione</h1>
<%@ include file="/hello_world.html" %>
<%@ include file=”/login.jsp” %>
</body>
</html>
```
### Direttiva `Taglib`
Permette estendere i marcatori di JSP con etichette o marcatori generati dall'utente (etichette personalizzate).
Sintassi: `<%@ taglib uri="taglibraryURI" prefix="tagPrefix" %>`
Esempi librerie standard:
- JSTL core
- JSTL sql
- JSTL function
## Implicit Objects
JSP utilizza gli oggetti impliciti (built-in).
Gli oggetti impliciti sono oggetti istanziati automaticamente dallambiente JSP, non dobbiamo preoccuparci di importarli e istanziarli.
Per utilizzarli è sufficiente usare la sintassi `nomeOggetto.nomeMetodo`.
Oggetti disponibili per luso in pagine JSP:
- **out**: per scrivere codice HTML nella risposta (System.out di Java)
- **session**: dati specifici della sessione utente corrente
- **request**: richiesta HTTP ricevuta e i suoi attributi, header, cookie, parametri, etc.
- **page**: la pagina e le sue proprietà.
- **config**: dati di configurazione
- **response**: risposta HTTP e le sue proprietà.
- **application**: dati condivisi da tutte le pagine della web application
- **exception**: eventuali eccezioni lanciate dal server; utile per pagine di errore
- **pageContext**: dati di contesto per lesecuzione della pagina
Gli oggetti impliciti possono essere:
- oggetti legati alla servlet relativa alla pagina JSP
- oggetti legati allinput e alloutput della pagina JSP
- oggetti che forniscono informazioni sul contesto in cui la JSP viene eseguita
- oggetti risultanti da eventuali errori
Ambito Definisce dove e per quanto tempo saranno accessibili gli oggetti (oggetti impliciti, JavaBeans, ...):
- di pagina: l'oggetto è accessibile dal servlet che rappresenta la pagina
- di richiesta: l'oggetto viene creato e poi distrutto dopo l'uso
- di sessione: l'oggetto è accessibile durante tutta la sessione
- di applicazione: l'oggetto è accessibile dal servlet che rappresenta la pagina
---
## Code in JSP Page
`<% /* code here */ %>` is used to embed java code in a JSP page.
`<%= var %>` is used to get a value from a variable to be displayed.
### Request Parameters
```java
Type variable = request.getParameter("request_parameter"); // parameter of a GET request
```

51
Java/Java Web/Servlet.md Normal file
View file

@ -0,0 +1,51 @@
# Servlet
A Java servlet is a Java software component that extends the capabilities of a server.
Although servlets can respond to many types of requests, they most commonly implement web containers for hosting web applications on web servers and thus qualify as a server-side servlet web API.
## Basic Structure
```java
package <package>;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/route")
public class <className> extends HttpServlet {
private static final long serialVersionUID = 1L;
/** handle get request */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// GET REQUEST: load and display page (forward to JSP)
// OPTIONAL: add data to request (setAttribute())
}
/** handle post request */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// POST REQUEST: add stuff to DB, page, ...
doGet(request, response); // return same page with new conted added (default case)
}
}
```
## Servlet Instructions
```java
request.getParameter() // read request parameter
response.setContentType("text/html"); // to return HTML in the response
response.getWriter().append(""); //append content to the http response
request.setAttribute(attributeName, value); // set http attribute of the request
request.getRequestDispatcher("page.jsp").forward(request, response); // redirect the request to another page
```

1231
Java/Java.md Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,203 @@
# Spring Project
## Libs
- MySql Driver
- Spring Data JPA (data persistance)
- Spring Boot Dev Tools
- Jersey (Serializzazione)
- Spring Web
## application.properties
```ini
spring.datasource.url=DB_url
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.show-sql=true
server.port=server_port
```
## Package `entities`
Model of a table of the DB
```java
package <base_pakcage>.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity // set as DB Entity (DB record Java implementation)
public class Entity {
@Id // set as Primary Key
@GeneratedValue(strategy = GenerationType.IDENTITY) // id is autoincremented by the DB
private int id;
// no constructor (Spring requirement)
// table columns attributes
// getters & setters
// toString()
}
```
## Package `dal`
Spring Interface for DB connection and CRUD operations.
```java
package <base_package>.dal // or .repository
import org.springframework.data.repository.JpaRepository;
import org.springframework.data.repository.Query;
import org.springframework.data.repository.query.Param;
// interface for spring Hibernate JPA
// CrudRepository<Entity, PK_Type>
public interface IEntityDAO extends JpaRepository<Entity, Integer> {
// custom query
@Query("FROM <Entity> WHERE param = :param")
Type query(@Param("param") Type param);
}
```
## Package `services`
Interfaces and method to access the Data Access Layer (DAL).
In `IEntityService.java`:
```java
package <base_package>.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import <base_package>.Entity;
import <base_package>.IEntityRepository;
// CRUD method implemented on Entity
public interface IEntityService {
String FIND_ALL = "SELECT * FROM <table>"
String FIND_ONE = "SELECT * FROM <table> WHERE id = ?"
List<Entity> findAll();
Entity findOne(int id);
void addEntity(Entity e);
void updateEntity(int id, Entity e);
void deleteEntity(Entity e);
void deleteEntity(int id);
}
```
In `EntityService.java`:
```java
package com.lamonacamarcello.libri.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import <base_package>.entities.Entity;
import <base_package>.repos.ILibriRepository;
// implementation of IEntityService
@Service
public class EntityService implements IEntityService {
@Autowired // connection to db (obj created by spring as needed: Inversion Of Control)
private IEntityDAO repo;
@Override
public List<Entity> findAll() {
return repo.findAll();
}
@Override
public Entity findOne(int id) {
return repo.findById(id).get();
}
@Override
public void addEntity(Entity e) {
repo.save(e);
}
@Override
public void updateEntity(int id, Entity e) {
}
@Override
public void deleteEntity(Entity e) {
}
@Override
public void deleteEntity(int id) {
}
// custom query
Type query(Type param) {
return repo.query(param);
}
}
```
## Package `integration`
REST API routes & endpoints to supply data as JSON.
```java
package com.lamonacamarcello.libri.integration;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import <base_package>.entities.Entity;
import <base_package>.services.IEntityService;
@RestController // returns data as JSON
@RequestMapping("/api") // controller route
public class EntityRestCtrl {
@Autowired // connection to service (obj created by spring as needed: Inverion Of Control)
private IEntityService service;
@GetMapping("entities") // site route
public List<Entity> findAll(){
return service.findAll();
}
@GetMapping("/entities/{id}")
public Entity findOne(@PathVariable("id") int id) { // use route variable
return service.findOne(id);
}
@PostMapping("/entities")
public void addEntity(@RequestBody Entity e) { // added entity is in the request body
return service.addEntity(e)
}
// PUT / PATCH -> updateEntity(id, e)
// DELETE -> deleteEntity(id)
}
```

View file

@ -0,0 +1,45 @@
# pom.xml
File specifing project dependencies.
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>major.minor.patch</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>major.minor.patch.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>base_package</groupId>
<artifactId>Project_Name</artifactId>
<version>major.minor.patch</version>
<name>Project_Name</name>
<description>...</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
```