Backend Documentation - bounswe/bounswe2025group5 GitHub Wiki

Spring Framework Notes

Spring In Usage:

  • Spring Boot: 3.4.4
  • Maven
  • Java 21 JDK
  • MySQL Driver
  • Spring Web
  • Spring DATA JPA

Spring Beans

A Spring Bean is a Java object that is created and managed by the Spring Container. It is eligible for dependency injection.

  • Normally, the programmer takes care of object creation.
  • In Spring, the framework creates the object, injects its dependencies, and controls its lifecycle.

Bean:

An instance of a class managed by the Spring container.

Manual Creation:

MyService myService = new MyService();
@Component
public class MyService {
    // some logic
}

With Spring:

Inject its to the another class
@Autowired
private MyService myService;

Spring Container

  • Spring Container: Holds all beans, resolves dependencies between them, and controls their lifecycle.

@Component: Marks a class as bean @Autowired : Tells Spring to inject the required bean

Principles:

  • IoC(Inversion of Control):You give up control of creating and managing objects to a framework or container (like Spring), instead of doing it manually in your own code.

  • Dependency Inversion: design principle that Code should depend on abstractions, not concrete implementations

  • Dependency Injection: is a technique where an object gets its dependencies from outside, rather than creating them itself.

Example :

public class Car {
    private Engine engine = new Engine(); // tightly coupled
}

public class Car {
    private Engine engine;

    public Car(Engine engine) { // dependency is injected from outside
        this.engine = engine;
    }
}

Dependency Injection (DI) types:

  • Constructor injection
  • Field injection (@Autowired)
  • Setter injection

Mockito Testing:

Mockito is a Java library that helps you mock dependencies. In unit testing, we do not use real dependencies like databases or services. Instead, we simulate their behavior using mocks.

Mocks are like fake collaborators that behave exactly how program tells them.

It does:

  • Create mock objects of classes and interfaces.
  • Stub methods to return specific values.
  • Verify method interactions (e.g., whether a method was called, how many times, etc.).
  • Avoid depending on actual implementations (e.g., real databases, services, etc.).

Examples:

@Mock
private UserRepository userRepository;
(This tells Mockito to create a fake version of UserRepository.)

@InjectMocks
private AuthService authService;
(Tells Mockito to inject the mocked dependencies (userRepository, passwordEncoder, etc.) into the authService.)

@BeforeEach
void setup() {
    MockitoAnnotations.openMocks(this);
}
(Initializes all the mocks before each test case.)
  • when(...).thenReturn(...): tell the mock what to return when a method is called.
  • assertEquals(...): check if the output is what you expect.
  • Only the mocked versions of the database and services are used.

Spring Entity

Lombok reduce boilerplate code through compile-time code generation.

Boilerplate code:are sections of code that are repeated in multiple places with little to no variation.

  • @Data Getters, setters, toString(), equals(), hashCode()
  • @Getter Getters for all fields
  • @Setter Setters for all non-final fields
  • @ToString toString() method
  • @EqualsAndHashCode equals() and hashCode() methods
  • @NoArgsConstructor No-args constructor
  • @AllArgsConstructor Constructor with all fields

It reduces the code clutter, improves readability

  • OrphanRemoval: is an important cascade operation in JPA (Java Persistence API) that controls what happens to child entities when they're removed from a parent relationship
  • orphanRemoval is a JPA annotation attribute that:
    • When set to true, automatically deletes child entities when they're removed from their parent's collection
    • Only applies to @OneToMany and @OneToOne relationships

Use orphanRemoval=true when:

  • Child entities have no meaning without their parent (composition)
  • You want to automatically clean up "orphaned" children
  • You're modeling a true parent-child relationship where children shouldn't exist independently

Cloud Database Setup (Google Cloud SQL)

We will use Google Cloud Service to deploy our database. You can connect to it from your local environment.

Important Rules:

  • โš ๏ธ DO NOT CHANGE ANYTHING IN THE TABLES without permission
  • Everyone can use it for:
    • SELECT queries
    • Running applications locally
    • Examining the database structure

Connecting to Remote MySQL Server

MySQL Workbench Setup:

  1. Create a new connection by clicking the "+" button next to "MySQL Connections"
  2. Configure with these details:
    • Connection Name: wasteless
    • Hostname: [server IP provided to you]
    • Username: [username provided to you]
    • Password: [password provided to you] (store in vault)
  3. Click "Test Connection" to verify
  4. Once successful, save and close the configuration
  5. Open the connection to run queries

Spring Application Configuration:

Update your application.properties file:

spring.datasource.url=jdbc:mysql://<service_ip>/<database_name>?useSSL=false&serverTimezone=UTC
spring.datasource.username=<givenusername>
spring.datasource.password=<givenpassword>

Running Spring Application Locally

Setup Instructions:

  1. Open Project in IntelliJ:

    • Create new project using VCS (Version Control System)
    • Copy the GitHub URL: https://github.com/bounswe/bounswe2025group5.git
  2. Project Configuration:

    • When prompted in the bottom-right corner:
      • Click "Load as Maven Project" (to recognize Maven structure)
      • Enable annotations processing for Lombok (when suggested)
  3. Database Connection:

    • Configure application.properties file with MySQL server details:
      spring.datasource.url=jdbc:mysql://<provided_server_ip>/waste_less?useSSL=false&serverTimezone=UTC
      spring.datasource.username=<provided_username>
      spring.datasource.password=<provided_password>
  4. Launch Application:

    • Click the Debug button in IntelliJ
    • Spring application will start running locally
  5. Testing with Postman:

    • Use the provided Postman collections to:
      • Send requests to your locally running application
      • Test API endpoints
      • Verify application behavior

Wikidata API Endpoint Explanation

** Search Entity Endpoint:**

  • Example endpoint
https://www.wikidata.org/w/api.php?action=wbsearchentities&format=json&language=en&uselang=en&search=Plastic&limit=10

Purpose: This API endpoint is used to search for entities in Wikidata that match a given search term. It returns a list of matching Wikidata items (entities), such as concepts, topics, people, etc.

Parameters Breakdown:

Parameter Value Description
action wbsearchentities Specifies the action to perform, in this case searching for entities.
format json Specifies the format of the response. json is commonly used for APIs.
language en The language of the search query and entity labels to return.
uselang en The language used for user-facing messages and labels in the response.
search Plastic The search keyword. The API will look for entities related to "Plastic".
limit 10 Limits the number of search results returned to 10.

Example Response (simplified):

{
  "search": [
    {
      "id": "Q11435",
      "label": "Plastic",
      "description": "material of a wide range of synthetic or semi-synthetic organic compounds",
      "match": {
        "type": "label",
        "language": "en",
        "text": "Plastic"
      }
    },
    ...
  ]
}

Usage: You are able to use this endpoint in a semantic search system to help users find Wikidata entities based on text input, such as integrating it into a knowledge graph application or a forum tagging feature.

  • In our system we put the input user gave us to this and get the id of the entity from wikidata to use it in the second endpoint.

Wikidata SPARQL Query Explanation

  • Example endpoint Endpoint:
https://query.wikidata.org/sparql

Full Query (formatted for readability):

SELECT DISTINCT ?relatedEntity ?relatedLabel WHERE {
  VALUES ?appContextEntity {
      wd:Q45701       # Waste
      wd:Q180388      # Waste management
      wd:Q131201      # Sustainable development
  }
  BIND(wd:Q11474 AS ?userInputEntity)  # Plastic

  {
    BIND(?userInputEntity AS ?relatedEntity)
  }
  UNION
  {
    BIND(?appContextEntity AS ?relatedEntity)
  }
  UNION { ?userInputEntity wdt:P279 ?relatedEntity . FILTER(?relatedEntity != ?userInputEntity) }   # Plastic subclass of ...
  UNION { ?userInputEntity wdt:P361 ?relatedEntity . FILTER(?relatedEntity != ?userInputEntity) }   # Plastic part of ...
  UNION { ?userInputEntity wdt:P1269 ?relatedEntity . FILTER(?relatedEntity != ?userInputEntity) }  # Plastic facet of ...
  UNION { ?relatedEntity wdt:P279* ?userInputEntity . FILTER(?relatedEntity != ?userInputEntity) }  # ... subclass of Plastic
  UNION { ?relatedEntity wdt:P31 ?userInputEntity . FILTER(?relatedEntity != ?userInputEntity) }    # ... instance of Plastic
  UNION { ?relatedEntity wdt:P527 ?userInputEntity . FILTER(?relatedEntity != ?userInputEntity) }   # ... has part Plastic
  UNION { ?relatedEntity wdt:P279* wd:Q180374 . }  # ... subclass of Environmental issue
  UNION { ?relatedEntity wdt:P31 wd:Q180374 . }    # ... instance of Environmental issue
  UNION { ?relatedEntity wdt:P279* wd:Q45701 . }   # ... subclass of Waste

  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en,und".
    ?relatedEntity rdfs:label ?relatedLabel .
  }
}
LIMIT 150

Purpose: This SPARQL query finds entities related to "Plastic" (Q11474) and environmental context concepts such as:

  • Waste (Q45701)
  • Waste Management (Q180388)
  • Sustainable development(Q131201)

It gathers items based on semantic relationships like:

  • Subclass (P279)
  • Part of (P361)
  • Facet of (P1269)
  • Instance of (P31)
  • Has part (P527)

Key Concepts in Query:

SPARQL Element Meaning
VALUES Defines a fixed list of context entities.
BIND Assigns a value (like Plastic) to a variable (?userInputEntity).
UNION Combines multiple query patterns to gather a broad set of relationships.
FILTER Avoids self-links (e.g., avoids Plastic linking to itself).
SERVICE wikibase:label Fetches human-readable English labels for each result entity.

Return Format: The query returns a JSON response with:

  • ?relatedEntity โ†’ the Wikidata entity ID
  • ?relatedLabel โ†’ the human-readable label (e.g., "Plastic pollution")

Usage:

  • In our system, we will put the id of entity we get in the former endpoint, then take the related terms and search it in the content of the posts.

Digital Ocean VM

After creating an environment on DigitalOcean, I followed these steps to set up the backend:

๐Ÿ”‘ Add SSH Key to Connect From the PC

  1. Generate SSH key:

    ssh-keygen -t rsa -b 4096 -C "-------"
    • Press Enter to accept default file location and no passphrase.
    • This creates public/private key pair in ~/.ssh.
  2. Display your public key:

    cat ~/.ssh/id_rsa.pub
  3. Copy and paste the output into your VMโ€™s authorized keys file (via the DigitalOcean dashboard or manually).


๐Ÿ”— Connect to the VM from the PC.

ssh root@<ip_address>

๐Ÿณ Deploy with Docker

Once connected to the VM , I did these steps to create the container and run the backend application:

git clone <repo_url>
cd <project_folder>
docker-compose up --build -d
  • This builds the Docker image and runs the container in detached mode.

๐Ÿงพ Check Logs

To see logs from the running container:

docker logs <container_name>

๐ŸŒ Access the Backend

  • Spring Boot application is running on the VM inside a Docker container.
  • Everyone can access it via:
http://<ip_address>:8080
  • You can send requests using Postman or any other REST client.

๐Ÿ“ Notes

  • The IP address is shared with you via WhatsApp.
  • The VM and container are not always running, you can reach out to me if you want to try it.
  • Usage of backend from the postman is enough for you for local development and no dealing with backend.
  • When you deploy your part **Front-end and **Mobile to it, you need to connect to VM, so you need to create ssh key and give it to me so that I can add your key to the VM authorized keys file.
โš ๏ธ **GitHub.com Fallback** โš ๏ธ