Skip to content

About

A robust JAX-RS RESTful API for managing smart campus facilities and IoT sensors, featuring an in-memory HashMap architecture and advanced HTTP exception handling.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

Smart Campus Sensor & Room Management API

API Overview

The "Smart Campus" API is a robust, RESTful web service built using JAX-RS (Jakarta RESTful Web Services). It is designed to manage university facilities by providing a seamless interface to track Rooms, diverse hardware Sensors, and historical Sensor Readings. To adhere to strict architectural constraints, the API utilizes a centralized, in-memory data store (HashMaps) rather than a persistent SQL database, and leverages advanced error handling to map Java exceptions to standard HTTP status codes.

Build and Launch Instructions

  1. Clone the Repository: git clone [Insert your GitHub Repo URL here]
  2. Open in IDE: Open the cloned directory as a Maven project in Apache NetBeans (or your preferred IDE).
  3. Build the Project: Right-click the project in the IDE and select Clean and Build to allow Maven to download the required Jersey and Jackson dependencies.
  4. Deploy: Run the project on a local Apache Tomcat or TomEE server.
  5. Access the API: The base URL for the API is http://localhost:8080/SmartCampusAPI/api/v1/.

Sample cURL Commands

Here are five commands demonstrating successful interactions with the API:

1. Create a New Room

curl -X POST http://localhost:8080/SmartCampusAPI/api/v1/rooms 
-H "Content-Type: application/json" 
-d '{"name": "Main Hall", "capacity": 250}'

2. Fetch All Rooms

curl -X GET http://localhost:8080/SmartCampusAPI/api/v1/rooms

3. Register a New Sensor (Requires a valid Room ID from Command 1)

curl -X POST http://localhost:8080/SmartCampusAPI/api/v1/sensors 
-H "Content-Type: application/json" 
-d '{"type": "CO2", "status": "ACTIVE", "currentValue": 400.5, "roomId": "PASTE_ROOM_ID_HERE"}'

4. Append a Sensor Reading (Requires a valid Sensor ID from Command 3)

curl -X POST http://localhost:8080/SmartCampusAPI/api/v1/sensors/PASTE_SENSOR_ID_HERE/readings 
-H "Content-Type: application/json" 
-d '{"value": 415.2}'

5. Attempt to Delete an Occupied Room (Demonstrates 409 Conflict Error Handling)

curl -X DELETE http://localhost:8080/SmartCampusAPI/api/v1/rooms/PASTE_ROOM_ID_HERE

Conceptual Report

Part 1.1: JAX-RS Lifecycle and In-Memory Data Synchronization

By default JAX-RS Resource classes are per-request, meaning that the runtime creates a new instance for each incoming HTTP request and destroys it afterwards. Instance variables are not appropriate for persistency data due to this ephemeral lifecycle. We need to declare our in-memory data structures (Maps) as static in a central DatabaseClass to avoid data loss. In a production environment with high traffic, these structures would also need to be thread-safe (e.g. ConcurrentHashMap) to prevent race conditions when multiple requests try to modify the data at the same time.

Part 1.2: HATEOAS and Hypermedia

A hallmark of advanced RESTful design is the provision of "Hypermedia" (HATEOAS), which allows clients to dynamically discover actions and navigate the API via hyperlinks embedded directly within the responses. This is useful for client developers, since it removes the need for hardcoded, static URI structures in their applications. If the backend routing changes, the client won’t break because it will just follow the dynamic links provided by the server, greatly reducing the dependence on static documentation.

Part 2.1: Returning IDs vs. Full Objects

When returning a list of rooms, only returning the IDs saves network bandwidth and reduces the server-side serialization overhead, which is very efficient for large datasets. But it pushes the client into the “N+1 problem” where it needs to make multiple follow-up requests to get the detailed metadata for each ID. Returning the full room objects increases payload size, but gives the client all the context it needs up front so UI components can render with a single network request.

Part 2.2: Idempotency of the DELETE Operation

Yes, DELETE is idempotent. So if a client accidentally sends the same DELETE request for a given room multiple times, the first one will remove the room and return a 204 No Content code. Subsequent identical requests will search for the room that has already been deleted, will fail to find it and will return a 404 Not Found. The HTTP status code might change, but the server state will be the same (the room will be deleted) no matter how many times the operation is performed, which strictly adheres to the definition of idempotency.

Part 3.1: Technical Consequences of @Consumes Mismatch

@Consumes(MediaType.APPLICATION_JSON) to specify the expected format. If a client tries to send data in some other format (e.g., text/plain or application/xml), JAX-RS will automatically take care of the mismatch with its built-in content negotiation. It intercepts the request before it hits the Java method and immediately returns an HTTP 415 Unsupported Media Type error. This prevents the endpoint from accepting malformed data and eliminates the need to write manual format-checking logic.

Part 3.2: Query Parameters vs. Path Parameters for Filtering

The query parameter approach (?type=CO2) is better for filtering, as query strings are naturally optional, unordered and can be easily combined (e.g. ?type=CO2&status=ACTIVE). Path parameters (/type/CO2) indicate strict resource identity and structural hierarchy. Path parameters for filtering make rigid routing trees unmanageable and fragile at scale to support multiple, optional filter criteria.

Part 4.1: Architectural Benefits of the Sub-Resource Locator Pattern

The Sub-Resource Locator pattern significantly improves maintainability by adhering to the Single Responsibility Principle. Instead of bloating one massive SensorResource controller class with dozens of deeply nested path methods (e.g., managing both sensors and their granular reading histories), the routing logic delegates the reading-specific operations to a dedicated SensorReadingResource class. This keeps API code modular, prevents massive controller files, and allows the sub-resource to natively inherit the context (the parent sensor ID) without redundant path parsing.

Part 5.2: Semantic Accuracy of HTTP 422

A 404 Not Found implies that the requested URI target itself does not exist. However, when posting a new Sensor with a missing room ID, the URI (/api/v1/sensors) is perfectly valid. The JSON payload is also syntactically correct, meaning a 400 Bad Request is not entirely accurate either. HTTP 422 Unprocessable Entity is the most semantically accurate because it tells the client: "The server understands the content type, and the syntax is correct, but the instructions contained within the payload (the foreign key dependency) cannot be processed."

Part 5.4: Cybersecurity Risks of Exposing Stack Traces

Exposing internal Java stack traces to external API consumers is a severe security risk known as Information Leakage. An attacker can gather specific intelligence from a trace, including the exact versions of frameworks being used (e.g., Jersey, Jackson), the database driver types, and the internal package structure of the application code. Attackers use this detailed fingerprint to search for known, unpatched vulnerabilities (CVEs) associated with those specific library versions, allowing them to launch highly targeted exploits.

Part 5.5: Advantages of JAX-RS Filters for Logging

Using JAX-RS filters for cross-cutting concerns centralizes the logic, strictly adhering to the DRY (Don't Repeat Yourself) principle. If you manually insert Logger.info() inside every single resource method, it clutters the business logic, increases the risk of human error (forgetting to log a new endpoint), and makes it incredibly tedious to update the logging format globally. A filter guarantees that every single request and response is automatically intercepted and logged in a uniform manner without touching the core application code.

About

A robust JAX-RS RESTful API for managing smart campus facilities and IoT sensors, featuring an in-memory HashMap architecture and advanced HTTP exception handling.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages