Initial commit :

Last change made - Inserted Flask API section
This commit is contained in:
Nikola
2026-07-11 19:33:44 +02:00
commit 9bc7ba9166
63 changed files with 18740 additions and 0 deletions
Binary file not shown.
+718
View File
@@ -0,0 +1,718 @@
# List of contents
1. [[#REST API with Spring]]
2. [[#DOCKER]]
3. [[#gRPC]]
4.
<div class="page-break"></div>
# REST API in Java with Spring
## Making REST API Requests
### With ***WebClient*** object:
(e.g Spring WebFlux)
#### GET
```java
public void getAllPersons(CustomerSortingOptions sortingOptions, Consumer<List<Customer>> customerConsumer) {
webClient.get()
.uri(uriBuilder -> uriBuilder
.path("customers")
.queryParam("sortField", sortingOptions.getSortField())
.queryParam("sortingOrder", sortingOptions.getSortingOrder())
.build())
.retrieve()
.bodyToMono(new ParameterizedTypeReference<List<Customer>>() {
})
.onErrorStop()
.subscribe(newPersons -> {
customers.clear();
customers.addAll(newPersons);
customerConsumer.accept(customers);
});
}
```
#### POST
```java
public void addPerson(Customer customer, Consumer<List<Customer>> customerConsumer) {
// TODO Part 2: Complete the http post request to the server
webClient.post()
.uri("customers")
.bodyValue(customer)
.retrieve()
.bodyToMono(Customer.class)
.onErrorStop()
.subscribe(newCustomer -> {
customers.add(newCustomer);
customerConsumer.accept(customers);
});
}
```
#### PUT
```java
public void updatePerson(Customer customer, Consumer<List<Customer>> customerConsumer) {
// TODO Part 2: Complete the http put request to the server
webClient.put()
.uri("customers/" + customer.getId())
.bodyValue(customer)
.retrieve()
.bodyToMono(Customer.class)
.onErrorStop()
.subscribe(newCustomer -> {
customers.replaceAll(x -> x.getId().equals(customer.getId()) ? newCustomer : x);
customerConsumer.accept(customers);
});
}
```
#### DELETE
```java
public void deletePerson(Customer customer, Consumer<List<Customer>> customerConsumer) {
// TODO Part 2: Make an http delete request to the server
webClient.delete()
.uri("customers/" + customer.getId())
.retrieve()
.toBodilessEntity()
.onErrorStop()
.subscribe(deletedCustomer -> {
customers.remove(customer);
customerConsumer.accept(customers);
});
}
```
#### Just in case: webClient Constructor
```java
public CustomerController() {
this.webClient = WebClient.builder()
.baseUrl("http://localhost:8080/")
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
this.customers = new ArrayList<>();
}
```
#### With Request Parameters:
Endpoint:
```java
@GetMapping("persons")
public ResponseEntity<List<Person>> getAllPersons(PersonSortingOptions sortingOptions) { // Don't use @RequestParams unless object is simple(for example String), for more complex objects Spring parses the object by itself
List<Person> persons = personService.getAllPersons(sortingOptions);
return ResponseEntity.ok(persons);
}
```
Request:
```java
public void getAllPersons(PersonSortingOptions sortingOptions, Consumer<List<Person>> personsConsumer) {
this.webClient.get()
.uri(uriBuilder -> uriBuilder // Use uriBuilder to build the path
.path("persons")
.queryParam("sortingOrder",sortingOptions.getSortingOrder()) // The fields are passed separately
.queryParam("sortField",sortingOptions.getSortField()) // In the format: ("Name",value)
.build()
)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<List<Person>>() {
})
.onErrorStop()
.subscribe(persons -> {
this.persons = persons;
personsConsumer.accept(this.persons);
});
}
```
### With *RestTemplate*:
```java
GetMapping("/getTimeLine/{id}")
public List<Tweet> getTimeLine(@PathVariable("id") int userID) {
headers.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<List<Tweet>> response = restTemplate.exchange(
getActivityURL + userID, // Set the uri HttpMethod.GET,
null, // requestEntity = null as there is no body,
new ParameterizedTypeReference<List<Tweet>>(){} // response body type );
return response.getBody();
}
```
## REST API Endpoints
Example Java class:
```java
@RestController
@RequestMapping("/activity")
public class ActivityController {
private Map<Integer, List<Tweet>> userActivityMap = new HashMap<>();
private Map<Integer, List<User>> userFollowedMap = new HashMap<>();
@GetMapping("/getActivity/{id}")
public List<Tweet> getActivity(@PathVariable("id") int userID) {
List<Tweet> userTweets = userActivityMap.get(userID);
if(userTweets == null) return new ArrayList<>();
return userTweets;
}
@PostMapping("/addActivity")
public void addActivity(@RequestBody Tweet tweet) {
userActivityMap.computeIfAbsent(tweet.getUser().getUserID(), x -> new LinkedList<>());
userActivityMap.get(tweet.getUser().getUserID()).add(tweet);
}
@PostMapping("/addFollower")
public void addFollower(@RequestBody FollowRequest followRequest) {
User follower = followRequest.getFollower();
User followed = followRequest.getFollowed();
userFollowedMap.computeIfAbsent(follower.getUserID(),x -> new LinkedList<>())
.add(followed);
}
@DeleteMapping("/deleteActivity")
public void deleteActivity(@RequestBody Tweet tweet) {
List<Tweet> userTweets = userActivityMap.get(tweet.getUser().getUserID());
if(userTweets == null) return;
userTweets.remove(tweet);
}
@DeleteMapping("/deleteFollower")
public void deleteFollower(@RequestBody FollowRequest followRequest) {
User follower = followRequest.getFollower();
User followed = followRequest.getFollowed();
List<User> followedUsers = userFollowedMap.get(follower.getUserID());
if(followedUsers == null) return;
followedUsers.remove(followed);
}
@GetMapping("/getFollowedList/{id}")
public List<User> getFollowedList(@PathVariable("id") int userID) {
// TODO: this method is also not complete, so you have to implement it accordingly :)
List<User> followed = userFollowedMap.get(userID);
if(followed == null) return new ArrayList<>();
return followed;
}
}
```
<div class="page-break"></div>
# Flask API in Python
## *Server side* endpoints
#### GET
```python
@api.route("/<key>", methods=["GET"])
def get(key: str) -> Response:
"""
Retrieve the file-content associated with the given key owned by the user.
If there is no user-id `uid` given in the request body or the user-id does not match, return error message and status.
Otherwise, return the file-content and success status.
"""
request_body: dict = request.json
ff: FileFolder = current_app.ff # type: ignore
user_id = request_body.get("uid")
if user_id is None:
return Response(NO_UID_IN_REQUEST_BODY,BAD_REQUEST)
file = ff.get(key)
if file is None:
return Response(response=KEY_DOES_NOT_EXIST % key, status=NOT_FOUND)
if file.uid != user_id:
return Response(response=NO_ACCESS_TO_ENTRY % key, status=BAD_REQUEST)
return Response(response=file.content,status=OK)
pass
```
#### PUT
```python
@api.route("/<key>", methods=["PUT"])
def put(key: str) -> Response:
"""
Upsert a file-content associated with the given key owned by the user.
If there is no user-id `uid` or file-content `content` given in the request body, return error message and status.
Otherwise, return the success message and success status
"""
request_body: dict = request.json
ff: FileFolder = current_app.ff
if "uid" not in request_body:
return Response(NO_UID_IN_REQUEST_BODY,BAD_REQUEST)
if "content" not in request_body:
return Response(NO_CONTENT_IN_REQUEST_BODY,BAD_REQUEST)
uid = request_body["uid"]
file_content = request_body["content"]
old_entry = ff.get(key)
if old_entry is None:
entry = Entry(uid,file_content)
success = ff.put(key,entry)
if success:
return Response(PUT_SUCCESS,OK)
else:
return Response(NO_SPACE_IN_FILE_FOLDER,BAD_REQUEST)
if uid != old_entry.uid:
return Response(NO_ACCESS_TO_ENTRY % key,status=BAD_REQUEST)
entry = Entry(uid,file_content)
ff.put(key,entry)
return Response(PUT_SUCCESS,OK)
pass
```
#### DELETE
```python
@api.route("/<key>", methods=["DELETE"])
def remove(key: str) -> Response:
"""
Remove the file-content associated with the given key owned by the user.
If there is no user-id `uid` given in the request body or the user-id does not match, return error message and status.
Otherwise, return the removed file-content and success status
"""
request_body: dict = request.json
ff: FileFolder = current_app.ff
if "uid" not in request_body:
return Response(NO_UID_IN_REQUEST_BODY,BAD_REQUEST)
uid = request_body["uid"]
entry = ff.get(key)
if entry is None:
return Response(KEY_DOES_NOT_EXIST % key,NOT_FOUND)
if entry.uid != uid:
return Response(NO_ACCESS_TO_ENTRY % key,BAD_REQUEST)
ff.remove(key)
return Response(entry.content,OK)
pass
```
#### GET - all
```python
@api.route("/", methods=["GET"])
def list() -> Response:
"""
List all (key, file-content) tuples owned by the user.
If there is no user-id `uid` given in the request body, return error message and status.
Otherwise, return the list of file-content and success status.
"""
request_body: dict = request.json
ff: FileFolder = current_app.ff
if "uid" not in request_body:
return Response(NO_UID_IN_REQUEST_BODY,BAD_REQUEST)
uid = request_body["uid"]
items = ff.items()
output = []
for key, entry in items:
output.append(f"{key}:{entry.content}")
output_string = ".".join(output)
return Response(output_string,OK)
pass
```
## Making requests on the *client side*
#### Helper method
```python
# make json request to server
def json_request(self, method: str, path: str, body: dict):
self.conn.request(method, path, json.dumps(body), headers={"Content-Type": "application/json"})
flask_response = self.conn.getresponse()
return flask_response.read().decode()
```
#### PUT
```python
def put(self, key, content):
"""
Upsert (key, content) tuple into the file folder.
Return the server response
"""
request_body = {"uid": self.user_id, "content": content}
return self.json_request("PUT", f"/{key}",request_body)
pass
```
#### GET
```python
def read(self, key):
"""
Retrieve the file-content associated with the given key owned by the user.
Return the server response
"""
request_body = {"uid": self.user_id}
return self.json_request("GET",f"/{key}",request_body)
pass
```
#### DELETE
```python
def remove(self, key):
"""
Remove the file-content associated with the given key owned by the user.
Return the server response
"""
request_body = {"uid": self.user_id}
return self.json_request("DELETE",f"/{key}",request_body)
pass
```
#### GET - ALL
```python
def list(self):
"""
List all file-content owned by the user.
Return the server response
"""
request_body = {"uid": self.user_id}
return self.json_request("GET","/",request_body)
pass
```
# DOCKER
**Docker reference: https://docs.docker.com/**
### Dockerfiles
https://docs.docker.com/get-started/docker-concepts/building-images/writing-a-dockerfile/
https://docs.docker.com/reference/dockerfile/
```dockerfile
FROM python:3.13
WORKDIR /usr/local/app
# Install the application dependencies
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
# Copy in the source code
COPY src ./src
EXPOSE 8080
# Setup an app user so the container doesn't run as the root user
RUN useradd app
USER app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"]
```
### Building docker
```bash
docker build -t <tag>
```
### Docker processes
```bash
docker ps
```
#### Exercises
- [L09P01 - Registry Office Service Deployment](file:///home/nikola/Documents/EIST/eist26l09p01-go38coz)
- [L09P02 - Garching Best Software](file:///home/nikola/Documents/EIST/eist26l09p02-go38coz)
- [L08PE04 - Spaceship](file:///home/nikola/Documents/EIST/eist26l0pe04-go38coz)
<div class="page-break"></div>
# gRPC
**gRPC reference: https://grpc.io/docs/**
**gRPC Java basics: https://grpc.io/docs/languages/java/basics/**
## Protobuf files
#### Defining classes:
Important tips:
* Array in protobuf means ```repeated``` field
```protobuf
message Date {
int32 day = 1; // Number specifies order
int32 month = 2;
int32 year = 3;
}
message Location {
string city = 1;
string country = 2;
}
message LocationDate {
Location location = 1;
Date date = 2;
}
```
#### Defining services:
```protobuf
service WeatherReporter {
//Returning one object
rpc GetCityWeatherSingleDay(LocationDate) returns (CityWeatherData) {}
// Returning a stream of objects
rpc GetCityWeatherMultipleDays(LocationDatePeriod) returns (stream CityWeatherData) {}
}
```
#### Example of services and objects with **repeated** fields
This will be utilized by some of the client side examples underneath
```protobuf
service MetadataService {
rpc getTrackMetadata(EntitiesRequest) returns (Tracks) {}
rpc getAlbumMetadata(EntitiesRequest) returns (Albums) {}
}
message EntitiesRequest {
repeated uint32 id = 1;
}
message Track {
uint64 id = 1;
string name = 2;
string album = 3;
string artist = 4;
uint32 duration = 5;
}
message Tracks {
repeated Track track = 1;
}
message Album {
uint64 id = 1;
string name = 2;
string artist = 3;
repeated uint32 tracks = 4;
}
message Albums {
repeated Album album = 1;
}
```
#### Generating classes from *.proto* files
1. Gradle tab in IDE and press "Tasks > other > generateProto")
2. The generated classes from the proto file should be in build/generated/source/proto/main folder
## Server side
In practice can be done with streams or with simple iteration
```java
public void getCityWeatherSingleDay(LocationDate request, StreamObserver<CityWeatherData> responseObserver) {
var data = allWeatherData.stream().filter(cityWeatherData -> cityWeatherData.getLocationDate().equals(request)).findFirst().orElse(null);
if(data != null)responseObserver.onNext(data);
responseObserver.onCompleted();
}
```
#### For returning a *stream* of data just call onNext multiple times
With iteration:
```Java
public void getCityWeatherMultipleDays(LocationDatePeriod request, StreamObserver<CityWeatherData> responseObserver) {
for(CityWeatherData data : allWeatherData) {
if(data.getLocationDate().getLocation().equals(request.getLocation())) {
if(compareDate(data.getLocationDate().getDate(), request.getStartDate()) >= 0 && compareDate(data.getLocationDate().getDate(), request.getEndDate()) <= 0)
{
responseObserver.onNext(data);
}
}
}
responseObserver.onCompleted();
}
```
With streams:
```java
public void getCityWeatherMultipleDays(LocationDatePeriod request, StreamObserver<CityWeatherData> responseObserver) {
var startDate = request.getStartDate();
var endDate = request.getEndDate();
allWeatherData.stream()
.filter(cityWeatherData -> cityWeatherData.getLocationDate().getLocation().equals(request.getLocation()))
.filter(cityWeatherData -> compareDate(cityWeatherData.getLocationDate().getDate(),startDate) >= 0)
.filter(cityWeatherData -> compareDate(cityWeatherData.getLocationDate().getDate(),endDate) <= 0)
.forEach(responseObserver::onNext);
responseObserver.onCompleted();
}
```
#### For returning an object which contains array of other objects (stupid???)
```java
public void getAlbumMetadata(EntitiesRequest request, StreamObserver<Albums> responseObserver) {
Albums.Builder albumsBuilder = Albums.newBuilder();
for(int i = 0; i < request.getIdCount();i++) {
// Find the album by its id
Album album = database.findAlbumById(request.getId(i));
if(album != null) {
albumsBuilder.addAlbum(album);
}
}
// In case that an album isn't found builder builds empty list
Albums albums = albumsBuilder.build();
responseObserver.onNext(albums);
responseObserver.onCompleted();
}
```
## Client Side
#### Setup
The **blocking stub** is a placeholder on which the functions are called. It needs to be received from the gRPC object in some way.
```java
public WeatherClient(Channel channel) {
// Get blocking stub from the gRPC object
blockingStub = WeatherReporterGrpc.newBlockingStub(channel);
}
```
or
```java
public SpotifyClient(Channel channel) {
// spotifyConnection is a wrapper defined in the excercise
// this is just an example that there can be other ways to get the stub
this.spotifyConnection = new SpotifyConnection(channel);
this.blockingStub = spotifyConnection.getStub();
}
```
#### Calling method with ***single object*** return value
```java
public void getCityWeatherSingleDay(int day, int month, int year, String city, String country) {
// Need to use builders to create the objects for the request
Date date = Date.newBuilder().setDay(day).setMonth(month).setYear(year).build();
Location location = Location.newBuilder().setCity(city).setCountry(country).build();
// Building the locationDate which will be passed as a parameter
LocationDate locationDate = LocationDate.newBuilder().setDate(date).setLocation(location).build();
// Getting the returned object from calling the method on the stub
CityWeatherData cityWeatherData = blockingStub.getCityWeatherSingleDay(locationDate);
System.out.println(cityWeatherData.toString());
}
```
#### Calling method which returns ***stream***
```java
public void getCityWeatherMultipleDays(int startDay, int startMonth, int startYear, int endDay, int endMonth, int endYear, String city, String country) {
// Building objects for the request
Date startDate = Date.newBuilder()
.setDay(startDay)
.setMonth(startMonth)
.setYear(startYear)
.build();
Date endDate = Date.newBuilder()
.setDay(endDay)
.setMonth(endMonth)
.setYear(endYear)
.build();
Location location = Location.newBuilder().setCity(city).setCountry(country).build();
// Building LocationDatePeriod object to be passed as parameter
LocationDatePeriod locationDatePeriod = LocationDatePeriod.newBuilder()
.setStartDate(startDate)
.setEndDate(endDate)
.setLocation(location)
.build();
// Method call returns Iterator<CityWeatherData> for the stream of CityWeatherData
Iterator<CityWeatherData> iterator = blockingStub.getCityWeatherMultipleDays(locationDatePeriod);
// Iterating over the objects
while (iterator.hasNext()) {
CityWeatherData cityWeatherData = iterator.next();
System.out.println(cityWeatherData.toString());
}
}
```
#### Calling method which has *parameter with **repeated** field*
```java
public String displayPlaylist(int[] playlist) throws SpotifyClientException {
StringBuilder stringBuilder = new StringBuilder();
EntitiesRequest.Builder builder = EntitiesRequest.newBuilder();
// IMPORTANT for REPEATED fields
// Add all id's to request
for(int id : playlist) {
builder.addId(id);
}
EntitiesRequest request = builder.build();
// Unlike in earlier examplese returns OBJECT which contains multiple Tracks
Tracks tracks;
tracks = blockingStub.getTrackMetadata(request);
if(tracks.getTrackCount() != playlist.length) throw new SpotifyClientException("Failed to get track metadata");
for(int i = 0; i < tracks.getTrackCount();i++) {
Track track = tracks.getTrack(i);
int durationInSeconds = track.getDuration();
int durationInMinutes = durationInSeconds / 60;
durationInSeconds = durationInSeconds % 60;
stringBuilder.append(String.format("%d. %s - %s (%d:%02d)%n", i+1,track.getName(), track.getArtist(), durationInMinutes, durationInSeconds));
}
return stringBuilder.toString();
}
```
<div class="page-break"></div>
## ALL RESOURCE LINKS:
- **Lecture slides (PDF)**
- **Your own homework solutions (cloned)**
- **Cheat-sheets/self-written notes (printed/on paper/PDF)**
- **C reference:** https://en.cppreference.com/w/c/language
- **Python reference:** https://docs.python.org/3/reference/index.html
- **Java reference:** https://www.baeldung.com/get-started-with-java-series
- **Java reference:** https://docs.oracle.com/en/java/javase/22/
- **gRPC reference:** https://grpc.io/docs/
- **Spotbugs**: https://spotbugs.readthedocs.io
- **AddressSanitizer**: https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html
- **Spring Boot:** https://www.baeldung.com/spring-boot
- **Spring Boot:** https://spring.io/projects/spring-boot
- **Docker:** https://docs.docker.com/
- **JavaFX:** https://openjfx.io/openjfx-docs
- **Gradle:** https://docs.gradle.org/current/userguide/userguide.html
- **Git:** https://git-scm.com/docs
- **JUnit:** https://junit.org/junit5/docs/current/user-guide/
- **Mockito:** https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html
- **EasyMock:** https://easymock.org/user-guide.html
- **man pages (command line, not online)**
<div class="page-break"></div>
Binary file not shown.
Binary file not shown.
+79
View File
@@ -0,0 +1,79 @@
- [ ] **Lecture 1:**
- [x] L01PE01
- [ ] **Lecture 2:**
- [x] L02PB01
- [x] L02PB02
- [x] L02P01
- [x] L02P02
- [x] L02PE01
- [x] L02PE02
- [x] L02PE03
- [ ] **Lecture 3:**
- [x] L03PB01
- [x] L03PB02
- [x] L03P01
- [ ] L03P02
- [ ] L03PE01
- [ ] L03PE02
- [ ] L03PE03
- [ ] L03PE04
- [ ] **Lecture 4:**
- [ ] L04PB01
- [ ] L04PB02
- [ ] L04P01
- [ ] L04P02
- [ ] L04PE01
- [ ] L04PE02
- [ ] L04PE03
- [ ] L04PE04
- [ ] L04PE05
- [ ] **Lecture 5:**
- [ ] L05PB01
- [ ] L05PB02
- [ ] L05P01
- [ ] L05P02
- [ ] L05P03
- [ ] L05PE01
- [ ] L05PE02
- [ ] L05PE03
- [ ] Lecture 6:
- [ ] L06PB01
- [ ] L06PB02
- [ ] L06P01
- [ ] L06P02
- [ ] L06PE01
- [ ] L06PE02
- [ ] L06PE03
- [ ] Lecture 7:
- [ ] L07PB01
- [ ] L07PB02
- [ ] L07P01
- [ ] L07P02
- [ ] L07PE01
- [ ] L07PE02
- [ ] L07PE03
- [ ] Lecture 8:
- [ ] L08PB01
- [ ] L08PB02
- [ ] L08P01
- [ ] L08P02
- [ ] L08PE01
- [ ] L08PE02
- [ ] L08PE03
- [ ] L08PE04
- [ ] Lecture 9:
- [ ] L09PB01
- [ ] L09PB02
- [ ] L09P01
- [ ] L09P02
- [ ] L09PE01
- [ ] L09PE02
- [ ] L09PE03
- [ ] Lecture 10:
- [ ] L10PE01
+366
View File
@@ -0,0 +1,366 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>EIST CHEATSHEET</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
/* The extra [class] is a hack that increases specificity enough to
override a similar rule in reveal.js */
ul.task-list[class]{list-style: none;}
ul.task-list li input[type="checkbox"] {
font-size: inherit;
width: 0.8em;
margin: 0 0.8em 0.2em -1.6em;
vertical-align: middle;
}
.display.math{display: block; text-align: center; margin: 0.5rem auto;}
/* CSS for syntax highlighting */
html { -webkit-text-size-adjust: 100%; }
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { color: #008000; } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { color: #008000; font-weight: bold; } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>
<link rel="stylesheet" href="obsidian.css" />
</head>
<body>
<nav id="TOC" role="doc-toc">
<ul>
<li><a href="#list-of-contents" id="toc-list-of-contents">List of
contents</a>
<ul>
<li><a href="#making-rest-api-requests"
id="toc-making-rest-api-requests">Making REST API Requests</a>
<ul>
<li><a href="#just-in-case-webclient-constructor"
id="toc-just-in-case-webclient-constructor">Just in case: webClient
Constructor</a></li>
</ul></li>
</ul></li>
<li><a href="#docker" id="toc-docker">DOCKER</a>
<ul>
<li><a href="#dockerfiles" id="toc-dockerfiles">Dockerfiles</a></li>
<li><a href="#building-docker" id="toc-building-docker">Building
docker</a></li>
<li><a href="#docker-processes" id="toc-docker-processes">Docker
processes</a></li>
</ul></li>
<li><a href="#grpc" id="toc-grpc">gRPC</a>
<ul>
<li><a href="#implementing-grpc-server-methods"
id="toc-implementing-grpc-server-methods">Implementing gRPC server
methods</a></li>
<li><a href="#all-resource-links" id="toc-all-resource-links">ALL
RESOURCE LINKS:</a></li>
</ul></li>
</ul>
</nav>
<h1 id="list-of-contents">List of contents</h1>
<ol type="1">
<li>[[#Making REST API Requests]]</li>
<li>[[#DOCKER]]</li>
<li>[[#gRPC]]</li>
</ol>
<h2 id="making-rest-api-requests">Making REST API Requests</h2>
<h4 id="get">GET</h4>
<div class="sourceCode" id="cb1"><pre
class="sourceCode java"><code class="sourceCode java"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">public</span> <span class="dt">void</span> <span class="fu">getAllPersons</span><span class="op">(</span>CustomerSortingOptions sortingOptions<span class="op">,</span> Consumer<span class="op">&lt;</span><span class="bu">List</span><span class="op">&lt;</span>Customer<span class="op">&gt;&gt;</span> customerConsumer<span class="op">)</span> <span class="op">{</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a> webClient<span class="op">.</span><span class="fu">get</span><span class="op">()</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">uri</span><span class="op">(</span>uriBuilder <span class="op">-&gt;</span> uriBuilder</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">path</span><span class="op">(</span><span class="st">&quot;customers&quot;</span><span class="op">)</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">queryParam</span><span class="op">(</span><span class="st">&quot;sortField&quot;</span><span class="op">,</span> sortingOptions<span class="op">.</span><span class="fu">getSortField</span><span class="op">())</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">queryParam</span><span class="op">(</span><span class="st">&quot;sortingOrder&quot;</span><span class="op">,</span> sortingOptions<span class="op">.</span><span class="fu">getSortingOrder</span><span class="op">())</span></span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">build</span><span class="op">())</span></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">retrieve</span><span class="op">()</span></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">bodyToMono</span><span class="op">(</span><span class="kw">new</span> ParameterizedTypeReference<span class="op">&lt;</span><span class="bu">List</span><span class="op">&lt;</span>Customer<span class="op">&gt;&gt;()</span> <span class="op">{</span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a> <span class="op">})</span></span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">onErrorStop</span><span class="op">()</span></span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">subscribe</span><span class="op">(</span>newPersons <span class="op">-&gt;</span> <span class="op">{</span></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a> customers<span class="op">.</span><span class="fu">clear</span><span class="op">();</span></span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a> customers<span class="op">.</span><span class="fu">addAll</span><span class="op">(</span>newPersons<span class="op">);</span></span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a> customerConsumer<span class="op">.</span><span class="fu">accept</span><span class="op">(</span>customers<span class="op">);</span></span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a> <span class="op">});</span></span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span></code></pre></div>
<h4 id="post">POST</h4>
<div class="sourceCode" id="cb2"><pre
class="sourceCode java"><code class="sourceCode java"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">public</span> <span class="dt">void</span> <span class="fu">addPerson</span><span class="op">(</span>Customer customer<span class="op">,</span> Consumer<span class="op">&lt;</span><span class="bu">List</span><span class="op">&lt;</span>Customer<span class="op">&gt;&gt;</span> customerConsumer<span class="op">)</span> <span class="op">{</span></span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a> <span class="co">// </span><span class="al">TODO</span><span class="co"> Part 2: Complete the http post request to the server</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a> webClient<span class="op">.</span><span class="fu">post</span><span class="op">()</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">uri</span><span class="op">(</span><span class="st">&quot;customers&quot;</span><span class="op">)</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">bodyValue</span><span class="op">(</span>customer<span class="op">)</span></span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">retrieve</span><span class="op">()</span></span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">bodyToMono</span><span class="op">(</span>Customer<span class="op">.</span><span class="fu">class</span><span class="op">)</span></span>
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">onErrorStop</span><span class="op">()</span></span>
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">subscribe</span><span class="op">(</span>newCustomer <span class="op">-&gt;</span> <span class="op">{</span></span>
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a> customers<span class="op">.</span><span class="fu">add</span><span class="op">(</span>newCustomer<span class="op">);</span></span>
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a> customerConsumer<span class="op">.</span><span class="fu">accept</span><span class="op">(</span>customers<span class="op">);</span></span>
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a> <span class="op">});</span></span>
<span id="cb2-13"><a href="#cb2-13" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<h4 id="put">PUT</h4>
<div class="sourceCode" id="cb3"><pre
class="sourceCode java"><code class="sourceCode java"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">public</span> <span class="dt">void</span> <span class="fu">updatePerson</span><span class="op">(</span>Customer customer<span class="op">,</span> Consumer<span class="op">&lt;</span><span class="bu">List</span><span class="op">&lt;</span>Customer<span class="op">&gt;&gt;</span> customerConsumer<span class="op">)</span> <span class="op">{</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a> <span class="co">// </span><span class="al">TODO</span><span class="co"> Part 2: Complete the http put request to the server</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a> webClient<span class="op">.</span><span class="fu">put</span><span class="op">()</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">uri</span><span class="op">(</span><span class="st">&quot;customers/&quot;</span> <span class="op">+</span> customer<span class="op">.</span><span class="fu">getId</span><span class="op">())</span></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">bodyValue</span><span class="op">(</span>customer<span class="op">)</span></span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">retrieve</span><span class="op">()</span></span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">bodyToMono</span><span class="op">(</span>Customer<span class="op">.</span><span class="fu">class</span><span class="op">)</span></span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">onErrorStop</span><span class="op">()</span></span>
<span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">subscribe</span><span class="op">(</span>newCustomer <span class="op">-&gt;</span> <span class="op">{</span></span>
<span id="cb3-10"><a href="#cb3-10" aria-hidden="true" tabindex="-1"></a> customers<span class="op">.</span><span class="fu">replaceAll</span><span class="op">(</span>x <span class="op">-&gt;</span> x<span class="op">.</span><span class="fu">getId</span><span class="op">().</span><span class="fu">equals</span><span class="op">(</span>customer<span class="op">.</span><span class="fu">getId</span><span class="op">())</span> <span class="op">?</span> newCustomer <span class="op">:</span> x<span class="op">);</span></span>
<span id="cb3-11"><a href="#cb3-11" aria-hidden="true" tabindex="-1"></a> customerConsumer<span class="op">.</span><span class="fu">accept</span><span class="op">(</span>customers<span class="op">);</span></span>
<span id="cb3-12"><a href="#cb3-12" aria-hidden="true" tabindex="-1"></a> <span class="op">});</span></span>
<span id="cb3-13"><a href="#cb3-13" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<h4 id="delete">DELETE</h4>
<div class="sourceCode" id="cb4"><pre
class="sourceCode java"><code class="sourceCode java"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="kw">public</span> <span class="dt">void</span> <span class="fu">deletePerson</span><span class="op">(</span>Customer customer<span class="op">,</span> Consumer<span class="op">&lt;</span><span class="bu">List</span><span class="op">&lt;</span>Customer<span class="op">&gt;&gt;</span> customerConsumer<span class="op">)</span> <span class="op">{</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a> <span class="co">// </span><span class="al">TODO</span><span class="co"> Part 2: Make an http delete request to the server</span></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a> webClient<span class="op">.</span><span class="fu">delete</span><span class="op">()</span></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">uri</span><span class="op">(</span><span class="st">&quot;customers/&quot;</span> <span class="op">+</span> customer<span class="op">.</span><span class="fu">getId</span><span class="op">())</span></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">retrieve</span><span class="op">()</span></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">toBodilessEntity</span><span class="op">()</span></span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">onErrorStop</span><span class="op">()</span></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">subscribe</span><span class="op">(</span>deletedCustomer <span class="op">-&gt;</span> <span class="op">{</span></span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a> customers<span class="op">.</span><span class="fu">remove</span><span class="op">(</span>customer<span class="op">);</span></span>
<span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a> customerConsumer<span class="op">.</span><span class="fu">accept</span><span class="op">(</span>customers<span class="op">);</span></span>
<span id="cb4-11"><a href="#cb4-11" aria-hidden="true" tabindex="-1"></a> <span class="op">});</span></span>
<span id="cb4-12"><a href="#cb4-12" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<h3 id="just-in-case-webclient-constructor">Just in case: webClient
Constructor</h3>
<div class="sourceCode" id="cb5"><pre
class="sourceCode java"><code class="sourceCode java"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">public</span> <span class="fu">CustomerController</span><span class="op">()</span> <span class="op">{</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="fu">webClient</span> <span class="op">=</span> WebClient<span class="op">.</span><span class="fu">builder</span><span class="op">()</span></span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">baseUrl</span><span class="op">(</span><span class="st">&quot;http://localhost:8080/&quot;</span><span class="op">)</span></span>
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">defaultHeader</span><span class="op">(</span>HttpHeaders<span class="op">.</span><span class="fu">ACCEPT</span><span class="op">,</span> MediaType<span class="op">.</span><span class="fu">APPLICATION_JSON_VALUE</span><span class="op">)</span></span>
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">defaultHeader</span><span class="op">(</span>HttpHeaders<span class="op">.</span><span class="fu">CONTENT_TYPE</span><span class="op">,</span> MediaType<span class="op">.</span><span class="fu">APPLICATION_JSON_VALUE</span><span class="op">)</span></span>
<span id="cb5-6"><a href="#cb5-6" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">build</span><span class="op">();</span></span>
<span id="cb5-7"><a href="#cb5-7" aria-hidden="true" tabindex="-1"></a> <span class="kw">this</span><span class="op">.</span><span class="fu">customers</span> <span class="op">=</span> <span class="kw">new</span> <span class="bu">ArrayList</span><span class="op">&lt;&gt;();</span></span>
<span id="cb5-8"><a href="#cb5-8" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<div class="page-break">
</div>
<h1 id="docker">DOCKER</h1>
<p><strong>Docker reference: https://docs.docker.com/</strong></p>
<h3 id="dockerfiles">Dockerfiles</h3>
<p>https://docs.docker.com/get-started/docker-concepts/building-images/writing-a-dockerfile/
https://docs.docker.com/reference/dockerfile/</p>
<div class="sourceCode" id="cb6"><pre
class="sourceCode dockerfile"><code class="sourceCode dockerfile"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="kw">FROM</span> python:3.13</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="kw">WORKDIR</span> /usr/local/app</span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a><span class="co"># Install the application dependencies</span></span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a><span class="kw">COPY</span> requirements.txt ./</span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a><span class="kw">RUN</span> <span class="ex">pip</span> install <span class="at">--no-cache-dir</span> <span class="at">-r</span> requirements.txt</span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a><span class="co"># Copy in the source code</span></span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a><span class="kw">COPY</span> src ./src</span>
<span id="cb6-10"><a href="#cb6-10" aria-hidden="true" tabindex="-1"></a><span class="kw">EXPOSE</span> 8080</span>
<span id="cb6-11"><a href="#cb6-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-12"><a href="#cb6-12" aria-hidden="true" tabindex="-1"></a><span class="co"># Setup an app user so the container doesn&#39;t run as the root user</span></span>
<span id="cb6-13"><a href="#cb6-13" aria-hidden="true" tabindex="-1"></a><span class="kw">RUN</span> <span class="ex">useradd</span> app</span>
<span id="cb6-14"><a href="#cb6-14" aria-hidden="true" tabindex="-1"></a><span class="kw">USER</span> app</span>
<span id="cb6-15"><a href="#cb6-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-16"><a href="#cb6-16" aria-hidden="true" tabindex="-1"></a><span class="kw">CMD</span> [<span class="st">&quot;uvicorn&quot;</span>, <span class="st">&quot;app.main:app&quot;</span>, <span class="st">&quot;--host&quot;</span>, <span class="st">&quot;0.0.0.0&quot;</span>, <span class="st">&quot;--port&quot;</span>, <span class="st">&quot;8080&quot;</span>]</span></code></pre></div>
<h3 id="building-docker">Building docker</h3>
<div class="sourceCode" id="cb7"><pre
class="sourceCode bash"><code class="sourceCode bash"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="ex">docker</span> build <span class="at">-t</span> <span class="op">&lt;</span>tag<span class="op">&gt;</span></span></code></pre></div>
<h3 id="docker-processes">Docker processes</h3>
<div class="sourceCode" id="cb8"><pre
class="sourceCode bash"><code class="sourceCode bash"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="ex">docker</span> ps</span></code></pre></div>
<h4 id="exercises">Exercises</h4>
<ul>
<li><a
href="file:///home/nikola/Documents/EIST/eist26l09p01-go38coz">L09P01 -
Registry Office Service Deployment</a></li>
<li><a
href="file:///home/nikola/Documents/EIST/eist26l09p02-go38coz">L09P02 -
Garching Best Software</a></li>
<li><a
href="file:///home/nikola/Documents/EIST/eist26l0pe04-go38coz">L08PE04 -
Spaceship</a></li>
</ul>
<div class="page-break">
</div>
<h1 id="grpc">gRPC</h1>
<p><strong>gRPC reference: https://grpc.io/docs/</strong> <strong>gRPC
Java basics: https://grpc.io/docs/languages/java/basics/</strong></p>
<h4 id="defining-classes">Defining classes:</h4>
<div class="sourceCode" id="cb9"><pre
class="sourceCode protobuf"><code class="sourceCode protobuf"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="kw">message</span> Date {</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a> <span class="dt">int32</span> day <span class="op">=</span> <span class="dv">1</span>; <span class="co">// Number specifies order</span></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a> <span class="dt">int32</span> month <span class="op">=</span> <span class="dv">2</span>;</span>
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a> <span class="dt">int32</span> year <span class="op">=</span> <span class="dv">3</span>;</span>
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-7"><a href="#cb9-7" aria-hidden="true" tabindex="-1"></a><span class="kw">message</span> Location {</span>
<span id="cb9-8"><a href="#cb9-8" aria-hidden="true" tabindex="-1"></a> <span class="dt">string</span> city <span class="op">=</span> <span class="dv">1</span>;</span>
<span id="cb9-9"><a href="#cb9-9" aria-hidden="true" tabindex="-1"></a> <span class="dt">string</span> country <span class="op">=</span> <span class="dv">2</span>;</span>
<span id="cb9-10"><a href="#cb9-10" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb9-11"><a href="#cb9-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-12"><a href="#cb9-12" aria-hidden="true" tabindex="-1"></a><span class="kw">message</span> LocationDate {</span>
<span id="cb9-13"><a href="#cb9-13" aria-hidden="true" tabindex="-1"></a> Location location <span class="op">=</span> <span class="dv">1</span>;</span>
<span id="cb9-14"><a href="#cb9-14" aria-hidden="true" tabindex="-1"></a> Date date <span class="op">=</span> <span class="dv">2</span>;</span>
<span id="cb9-15"><a href="#cb9-15" aria-hidden="true" tabindex="-1"></a>}</span></code></pre></div>
<h4 id="defining-services">Defining services:</h4>
<div class="sourceCode" id="cb10"><pre
class="sourceCode protobuf"><code class="sourceCode protobuf"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="kw">service</span> WeatherReporter {</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a> <span class="co">//Returning one object</span></span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a> <span class="kw">rpc</span> GetCityWeatherSingleDay(LocationDate) <span class="kw">returns</span> (CityWeatherData) {}</span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a> <span class="co">// Returning a stream of objects</span></span>
<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a> <span class="kw">rpc</span> GetCityWeatherMultipleDays(LocationDatePeriod) <span class="kw">returns</span> (stream CityWeatherData) {}</span>
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a>}</span></code></pre></div>
<h4 id="generating-classes-from-.proto-files">Generating classes from
<em>.proto</em> files</h4>
<ol type="1">
<li>Gradle tab in IDE and press “Tasks &gt; other &gt;
generateProto”)</li>
<li>The generated classes from the proto file should be in
build/generated/source/proto/main folder</li>
</ol>
<h3 id="implementing-grpc-server-methods">Implementing gRPC server
methods</h3>
<p>In practice can be done with streams or with simple iteration</p>
<div class="sourceCode" id="cb11"><pre
class="sourceCode java"><code class="sourceCode java"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="kw">public</span> <span class="dt">void</span> <span class="fu">getCityWeatherSingleDay</span><span class="op">(</span>LocationDate request<span class="op">,</span> StreamObserver<span class="op">&lt;</span>CityWeatherData<span class="op">&gt;</span> responseObserver<span class="op">)</span> <span class="op">{</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a> <span class="dt">var</span> data <span class="op">=</span> allWeatherData<span class="op">.</span><span class="fu">stream</span><span class="op">().</span><span class="fu">filter</span><span class="op">(</span>cityWeatherData <span class="op">-&gt;</span> cityWeatherData<span class="op">.</span><span class="fu">getLocationDate</span><span class="op">().</span><span class="fu">equals</span><span class="op">(</span>request<span class="op">)).</span><span class="fu">findFirst</span><span class="op">().</span><span class="fu">orElse</span><span class="op">(</span><span class="kw">null</span><span class="op">);</span></span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span><span class="op">(</span>data <span class="op">!=</span> <span class="kw">null</span><span class="op">)</span>responseObserver<span class="op">.</span><span class="fu">onNext</span><span class="op">(</span>data<span class="op">);</span></span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a> responseObserver<span class="op">.</span><span class="fu">onCompleted</span><span class="op">();</span></span>
<span id="cb11-5"><a href="#cb11-5" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<p>For returning a <em>stream</em> of data just call onNext multiple
times:</p>
<h5 id="with-iteration">With iteration</h5>
<div class="sourceCode" id="cb12"><pre
class="sourceCode java"><code class="sourceCode java"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="kw">public</span> <span class="dt">void</span> <span class="fu">getCityWeatherMultipleDays</span><span class="op">(</span>LocationDatePeriod request<span class="op">,</span> StreamObserver<span class="op">&lt;</span>CityWeatherData<span class="op">&gt;</span> responseObserver<span class="op">)</span> <span class="op">{</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a> <span class="cf">for</span><span class="op">(</span>CityWeatherData data <span class="op">:</span> allWeatherData<span class="op">)</span> <span class="op">{</span></span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span><span class="op">(</span>data<span class="op">.</span><span class="fu">getLocationDate</span><span class="op">().</span><span class="fu">getLocation</span><span class="op">().</span><span class="fu">equals</span><span class="op">(</span>request<span class="op">.</span><span class="fu">getLocation</span><span class="op">()))</span> <span class="op">{</span></span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span><span class="op">(</span><span class="fu">compareDate</span><span class="op">(</span>data<span class="op">.</span><span class="fu">getLocationDate</span><span class="op">().</span><span class="fu">getDate</span><span class="op">(),</span> request<span class="op">.</span><span class="fu">getStartDate</span><span class="op">())</span> <span class="op">&gt;=</span> <span class="dv">0</span> <span class="op">&amp;&amp;</span> <span class="fu">compareDate</span><span class="op">(</span>data<span class="op">.</span><span class="fu">getLocationDate</span><span class="op">().</span><span class="fu">getDate</span><span class="op">(),</span> request<span class="op">.</span><span class="fu">getEndDate</span><span class="op">())</span> <span class="op">&lt;=</span> <span class="dv">0</span><span class="op">)</span></span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a> <span class="op">{</span></span>
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a> responseObserver<span class="op">.</span><span class="fu">onNext</span><span class="op">(</span>data<span class="op">);</span></span>
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span>
<span id="cb12-8"><a href="#cb12-8" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span>
<span id="cb12-9"><a href="#cb12-9" aria-hidden="true" tabindex="-1"></a> <span class="op">}</span></span>
<span id="cb12-10"><a href="#cb12-10" aria-hidden="true" tabindex="-1"></a> responseObserver<span class="op">.</span><span class="fu">onCompleted</span><span class="op">();</span></span>
<span id="cb12-11"><a href="#cb12-11" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<h5 id="with-streams">With streams</h5>
<div class="sourceCode" id="cb13"><pre
class="sourceCode java"><code class="sourceCode java"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="kw">public</span> <span class="dt">void</span> <span class="fu">getCityWeatherMultipleDays</span><span class="op">(</span>LocationDatePeriod request<span class="op">,</span> StreamObserver<span class="op">&lt;</span>CityWeatherData<span class="op">&gt;</span> responseObserver<span class="op">)</span> <span class="op">{</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a> <span class="dt">var</span> startDate <span class="op">=</span> request<span class="op">.</span><span class="fu">getStartDate</span><span class="op">();</span></span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a> <span class="dt">var</span> endDate <span class="op">=</span> request<span class="op">.</span><span class="fu">getEndDate</span><span class="op">();</span></span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a> allWeatherData<span class="op">.</span><span class="fu">stream</span><span class="op">()</span></span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">filter</span><span class="op">(</span>cityWeatherData <span class="op">-&gt;</span> cityWeatherData<span class="op">.</span><span class="fu">getLocationDate</span><span class="op">().</span><span class="fu">getLocation</span><span class="op">().</span><span class="fu">equals</span><span class="op">(</span>request<span class="op">.</span><span class="fu">getLocation</span><span class="op">()))</span></span>
<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">filter</span><span class="op">(</span>cityWeatherData <span class="op">-&gt;</span> <span class="fu">compareDate</span><span class="op">(</span>cityWeatherData<span class="op">.</span><span class="fu">getLocationDate</span><span class="op">().</span><span class="fu">getDate</span><span class="op">(),</span>startDate<span class="op">)</span> <span class="op">&gt;=</span> <span class="dv">0</span><span class="op">)</span></span>
<span id="cb13-7"><a href="#cb13-7" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">filter</span><span class="op">(</span>cityWeatherData <span class="op">-&gt;</span> <span class="fu">compareDate</span><span class="op">(</span>cityWeatherData<span class="op">.</span><span class="fu">getLocationDate</span><span class="op">().</span><span class="fu">getDate</span><span class="op">(),</span>endDate<span class="op">)</span> <span class="op">&lt;=</span> <span class="dv">0</span><span class="op">)</span></span>
<span id="cb13-8"><a href="#cb13-8" aria-hidden="true" tabindex="-1"></a> <span class="op">.</span><span class="fu">forEach</span><span class="op">(</span>responseObserver<span class="op">::</span>onNext<span class="op">);</span></span>
<span id="cb13-9"><a href="#cb13-9" aria-hidden="true" tabindex="-1"></a> responseObserver<span class="op">.</span><span class="fu">onCompleted</span><span class="op">();</span></span>
<span id="cb13-10"><a href="#cb13-10" aria-hidden="true" tabindex="-1"></a><span class="op">}</span></span></code></pre></div>
<div class="page-break">
</div>
<h2 id="all-resource-links">ALL RESOURCE LINKS:</h2>
<ul>
<li><strong>Lecture slides (PDF)</strong></li>
<li><strong>Your own homework solutions (cloned)</strong></li>
<li><strong>Cheat-sheets/self-written notes (printed/on
paper/PDF)</strong></li>
<li><strong>C reference:</strong>
https://en.cppreference.com/w/c/language</li>
<li><strong>Python reference:</strong>
https://docs.python.org/3/reference/index.html</li>
<li><strong>Java reference:</strong>
https://www.baeldung.com/get-started-with-java-series</li>
<li><strong>Java reference:</strong>
https://docs.oracle.com/en/java/javase/22/</li>
<li><strong>gRPC reference:</strong> https://grpc.io/docs/</li>
<li><strong>Spotbugs</strong>: https://spotbugs.readthedocs.io</li>
<li><strong>AddressSanitizer</strong>:
https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html</li>
<li><strong>Spring Boot:</strong>
https://www.baeldung.com/spring-boot</li>
<li><strong>Spring Boot:</strong>
https://spring.io/projects/spring-boot</li>
<li><strong>Docker:</strong> https://docs.docker.com/</li>
<li><strong>JavaFX:</strong> https://openjfx.io/openjfx-docs</li>
<li><strong>Gradle:</strong>
https://docs.gradle.org/current/userguide/userguide.html</li>
<li><strong>Git:</strong> https://git-scm.com/docs</li>
<li><strong>JUnit:</strong>
https://junit.org/junit5/docs/current/user-guide/</li>
<li><strong>Mockito:</strong>
https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html</li>
<li><strong>EasyMock:</strong> https://easymock.org/user-guide.html</li>
<li><strong>man pages (command line, not online)</strong>
<div class="page-break">
</div></li>
</ul>
</body>
</html>
Binary file not shown.