### Install and Install Hooks for Pre-commit Source: https://github.com/jabrena/cursor-rules-java/blob/main/CLAUDE.md Install the pre-commit tool using pip or brew, then install the git hooks. This setup is required once per clone. ```bash pip install pre-commit # or: brew install pre-commit pre-commit install --install-hooks ``` -------------------------------- ### Install Skills with npx Source: https://github.com/jabrena/cursor-rules-java/blob/main/site-generator/content/blog/2026/03/release-0.12.0.md Install skills from a repository using the npx skills command. This example shows how to list all skills and add a specific one. ```bash brew install node npx skills add jabrena/cursor-rules-java --list ``` ```bash npx skills add https://github.com/jabrena/cursor-rules-java \ --skill 110-java-maven-best-practices ``` -------------------------------- ### Setup Async Profiler for Java Applications Source: https://context7.com/jabrena/cursor-rules-java/llms.txt Use these scripts to set up async-profiler for Java applications. The `run-java-process-for-profiling.sh` script starts the application with profiling JVM flags, while `profile-java-process.sh` attaches the profiler to a running JVM, offering an interactive menu for CPU, memory, lock, GC, or I/O profiling. ```bash # Start application with profiling JVM flags: ./run-java-process-for-profiling.sh ``` ```bash # Attach profiler to running JVM (interactive menu): ./profiler/scripts/profile-java-process.sh # Menu: 1) CPU 2) Memory 3) Lock 4) GC 5) I/O # Output: profiler/results/cpu-flamegraph-20260115-143022.html # profiler/results/recording-20260115-143022.jfr ``` -------------------------------- ### Install and List Skills with npx Source: https://github.com/jabrena/cursor-rules-java/blob/main/documentation/GETTING-STARTED-SKILLS.md Use npx commands to manage Skills. Ensure Node.js and npm are installed first. ```bash #To install npx brew install node sudo apt install nodejs npm npx skills --help npx skills add jabrena/cursor-rules-java --list npx skills add jabrena/cursor-rules-java --all --agent cursor npx skills add jabrena/cursor-rules-java --all --agent claude-code ``` -------------------------------- ### Example System Prompt Structure for Java Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/courses/system-prompts-java/module-1-foundations.html Illustrates the typical structure of a system prompt for Java development, including role, goal, constraints, and output format. Useful for guiding AI assistants in tasks like pom.xml modifications. ```markdown ## Role You are a Senior Java Developer... ## Goal Your task is to... ## Constraints - Follow Maven best practices - Use Java 21+ features - Ensure backward compatibility ## Output Format - Generate pom.xml modifications - Provide explanation of changes - Include validation steps ``` -------------------------------- ### Sakila Database Setup and API Interaction Source: https://github.com/jabrena/cursor-rules-java/blob/main/examples/spring-boot-demo/requirements/original/README.md This sequence of bash commands demonstrates how to run the Sakila PostgreSQL database in a Docker container, start the Spring Boot application, fetch films via a cURL request, and stop the database container. ```bash docker run -e POSTGRES_PASSWORD=sakila --rm --name sakiladb -p 5432:5432 -d "sakiladb/postgres" ./mvnw spring-boot:run curl http://localhost:8080/api/v1/films docker stop sakiladb ``` -------------------------------- ### Install Jira CLI on Linux Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/044-planning-jira/references/044-planning-jira.md Install the Jira CLI on Linux using the apt package manager or by downloading and manually installing the binary. ```bash sudo apt-get install jira-cli ``` ```bash chmod +x jira /usr/local/bin/jira ``` -------------------------------- ### Install OpenSpec CLI using npm Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/042-planning-openspec/SKILL.md Provides installation guidance for the OpenSpec CLI on different operating systems using npm. Use this when the CLI is not found. ```bash npm install -g @openspec/cli ``` -------------------------------- ### File Checklist Table Example Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills-generator/src/main/resources/skill-references/assets/java-design-plan-template.md Example structure for the File Checklist table, listing the order and file path for project files. ```markdown | Order | File | |-------|------| | 1 | `path/to/File1.java` | | 2 | `path/to/Test.java` | | 3 | `path/to/Impl.java` | ``` -------------------------------- ### Install and Use Pre-commit Hooks Source: https://github.com/jabrena/cursor-rules-java/blob/main/CONTRIBUTING.md Install pre-commit for local development. This ensures code quality and adherence to commit message conventions before committing. ```bash pip install pre-commit pre-commit install --install-hooks ``` ```bash brew install pre-commit pre-commit install --install-hooks ``` -------------------------------- ### Install All Cursor Rules Java Skills with Agent Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/blog/2026/03/release-0.12.0.html Install all available Skills from the Cursor Rules Java repository and associate them with the 'cursor' agent using 'npx skills install'. ```bash npx skills install jabrena/cursor-rules-java --all --agent cursor ``` -------------------------------- ### Run Local Blog Preview Source: https://github.com/jabrena/cursor-rules-java/blob/main/DEVELOPER.md Builds and serves the project's blog locally for previewing changes. ```bash # Run blog in local ./mvnw clean generate-resources jbake:inline -pl site-generator -P local-preview ``` -------------------------------- ### Setup Timer and Clock Source: https://github.com/jabrena/cursor-rules-java/blob/main/documentation/conferences/codemotion-madrid-2026/plugin/notes/speaker-view.html Initializes and starts updating the timer and clock elements, including pacing information, by fetching slide timings. ```javascript function setupTimer() { var start = new Date(), timeEl = document.querySelector( '.speaker-controls-time' ), clockEl = timeEl.querySelector( '.clock-value' ), hoursEl = timeEl.querySelector( '.hours-value' ), minutesEl = timeEl.querySelector( '.minutes-value' ), secondsEl = timeEl.querySelector( '.seconds-value' ), pacingTitleEl = timeEl.querySelector( '.pacing-title' ), pacingEl = timeEl.querySelector( '.pacing' ), pacingHoursEl = pacingEl.querySelector( '.hours-value' ), pacingMinutesEl = pacingEl.querySelector( '.minutes-value' ), pacingSecondsEl = pacingEl.querySelector( '.seconds-value' ); var timings = null; getTimings( function ( _timings ) { timings = _timings; if (_timings !== null) { pacingTitleEl.style.removeProperty('display'); pacingEl.style.removeProperty('display'); ``` -------------------------------- ### Skill File Structure Example Source: https://github.com/jabrena/cursor-rules-java/blob/main/site-generator/content/blog/2026/03/release-0.12.0.md Illustrates the standard directory structure for a Skill, including required and optional components. ```bash my-skill/ ├── SKILL.md # Required: instructions + metadata ├── scripts/ # Optional: executable code ├── references/ # Optional: documentation └── assets/ # Optional: templates, resources ``` -------------------------------- ### Quarkus Integration Test Source: https://context7.com/jabrena/cursor-rules-java/llms.txt Example of a Quarkus integration test using `@QuarkusTest`. This setup verifies REST endpoint behavior and response validation. ```java import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; // Skill 422 — Quarkus integration test: @QuarkusTest class GodAnalysisIT { @Test void shouldReturn200() { given().when().get("/api/v1/gods/Zeus/analysis") .then().statusCode(200).body("origin", equalTo("Greek")); } } ``` -------------------------------- ### Setup Timer and Clock Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/codemotion-madrid-2026/plugin/notes/speaker-view.html Initializes and starts updating the timer and clock elements. It retrieves slide timings first and then sets up intervals for updating the display. ```javascript function setupTimer() { var start = new Date(), timeEl = document.querySelector( '.speaker-controls-time' ), clockEl = timeEl.querySelector( '.clock-value' ), hoursEl = timeEl.querySelector( '.hours-value' ), minutesEl = timeEl.querySelector( '.minutes-value' ), secondsEl = timeEl.querySelector( '.seconds-value' ), pacingTitleEl = timeEl.querySelector( '.pacing-title' ), pacingEl = timeEl.querySelector( '.pacing' ), pacingHoursEl = pacingEl.querySelector( '.hours-value' ), pacingMinutesEl = pacingEl.querySelector( '.minutes-value' ), pacingSecondsEl = pacingEl.querySelector( '.seconds-value' ); var timings = null; getTimings( function ( _timings ) { timings = _timings; if (_timings !== null) { pacingTitleEl.style.removeProperty('display'); pacingEl.style.removeProperty('display'); // ... rest of the timer setup ``` -------------------------------- ### Install Cursor Rules Java CLI Source: https://github.com/jabrena/cursor-rules-java/blob/main/site-generator/content/blog/2026/03/release-0.12.0.md Use this command to initialize the project with System prompts from the repository. ```bash jbang setup@jabrena init \ --cursor https://github.com/jabrena/cursor-rules-java ``` -------------------------------- ### Micronaut Integration Test with Testcontainers Source: https://context7.com/jabrena/cursor-rules-java/llms.txt Example of a Micronaut integration test using `@MicronautTest` and `TestPropertyProvider` to integrate with Testcontainers for PostgreSQL. This requires the `postgres` container to be started. ```java import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import io.micronaut.test.support.TestPropertyProvider; import org.junit.jupiter.api.extension.ExtensionContext; import org.testcontainers.containers.PostgreSQLContainer; import java.util.Map; // Skill 522 — Micronaut integration test: @MicronautTest class GodAnalysisIT implements TestPropertyProvider { @Override public Map getProperties() { postgres.start(); return Map.of("datasources.default.url", postgres.getJdbcUrl()); } static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16"); } ``` -------------------------------- ### Run Profiling Script with Help Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/courses/profile-memory-leak/module-1-foundations.html Execute the main profiling script with the --help flag to display available options and usage instructions. ```bash ./run-java-process-for-profiling.sh --help ``` -------------------------------- ### Ambiguous Flyway Configuration Example Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/413-frameworks-quarkus-db-migrations-flyway/references/413-frameworks-quarkus-db-migrations-flyway.md Illustrates a problematic configuration where multiple datasources are defined but only a single, shared Flyway location is specified, leading to ambiguity in which schema gets migrated. ```properties # Bad: two datasources but only one Flyway location — ambiguous or wrong schema gets migrated quarkus.datasource.orders.jdbc.url=jdbc:postgresql://localhost/orders quarkus.datasource.audit.jdbc.url=jdbc:postgresql://localhost/audit quarkus.flyway.locations=classpath:db/migration ``` -------------------------------- ### Spring Boot Demo Application README.md Structure Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/courses/system-prompts-java/module-6-documentation.html This is an example structure for a README.md file generated for a Spring Boot demo application, including overview, features, and quick start instructions. ```markdown # Spring Boot Demo Application ## Overview A comprehensive Spring Boot demonstration application showcasing enterprise-grade development practices including REST APIs, data persistence, security, and testing. ## Features - RESTful API endpoints for user management - JPA-based data persistence with H2 database - Spring Security integration - Comprehensive test coverage - Docker support for containerization ## Quick Start ### Prerequisites - Java 21 or higher - Maven 3.8+ - Docker (optional) ### Running the Application ```bash # Clone the repository git clone cd spring-boot-demo # Run with Maven ./mvnw spring-boot:run # Or build and run JAR ./mvnw clean package java -jar target/spring-boot-demo-*.jar ``` -------------------------------- ### Build Plan and Help Commands Source: https://github.com/jabrena/cursor-rules-java/blob/main/DEVELOPER.md These commands help in understanding the build plan and retrieving project information, such as available profiles. ```bash ./mvnw buildplan:list-plugin ./mvnw buildplan:list-phase ./mvnw help:all-profiles ./mvnw help:active-profiles ``` -------------------------------- ### Initialize OpenSpec Project Source: https://github.com/jabrena/cursor-rules-java/blob/main/site-generator/content/blog/2026/04/release-0.14.0.md Use this command to set up a new OpenSpec project structure in your workspace. ```bash openspec init ``` -------------------------------- ### Incorrect Main Application Class: Missing @SpringBootApplication Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/301-frameworks-spring-boot-core/references/301-frameworks-spring-boot-core.md This example demonstrates an incorrect setup where `@SpringBootApplication` is missing, leading to the loss of Spring Boot conveniences. Manual context creation is shown. ```java import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MainApplication { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(); } } ``` -------------------------------- ### Setup Presentation Timer and Clock Source: https://github.com/jabrena/cursor-rules-java/blob/main/documentation/conferences/dvbe25/plugin/notes/speaker-view.html Initializes and updates the presentation timer and clock elements. It retrieves slide timings and starts an interval to update the displayed time, hours, minutes, and seconds. ```javascript function setupTimer() { var start = new Date(), timeEl = document.querySelector( '.speaker-controls-time' ), clockEl = timeEl.querySelector( '.clock-value' ), hoursEl = timeEl.querySelector( '.hours-value' ), minutesEl = timeEl.querySelector( '.minutes-value' ), secondsEl = timeEl.querySelector( '.seconds-value' ), pacingTitleEl = timeEl.querySelector( '.pacing-title' ), pacingEl = timeEl.querySelector( '.pacing' ), pacingHoursEl = pacingEl.querySelector( '.hours-value' ), pacingMinutesEl = pacingEl.querySelector( '.minutes-value' ), pacingSecondsEl = pacingEl.querySelector( '.seconds-value' ); var timings = null; getTimings( function ( _timings ) { timings = _timings; if (_timings !== null) { pacingTitleEl.style.removeProperty('display'); pacingEl.style.removeProperty('display'); ``` -------------------------------- ### Execute Profiling Script with Help Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/courses/profile-memory-leak/module-1-foundations.html Run the specific Java process profiling script with the --help flag to understand its options and how to initiate a profiling session. ```bash ./profile-java-process.sh --help ``` -------------------------------- ### Setup Timer and Clock Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/dvbe25/plugin/notes/speaker-view.html Initializes and updates the presentation timer and clock display. It retrieves slide timings and starts an interval to update the elapsed time, remaining time, and pacing information. ```javascript function setupTimer() { var start = new Date(), timeEl = document.querySelector( '.speaker-controls-time' ), clockEl = timeEl.querySelector( '.clock-value' ), hoursEl = timeEl.querySelector( '.hours-value' ), minutesEl = timeEl.querySelector( '.minutes-value' ), secondsEl = timeEl.querySelector( '.seconds-value' ), pacingTitleEl = timeEl.querySelector( '.pacing-title' ), pacingEl = timeEl.querySelector( '.pacing' ), pacingHoursEl = pacingEl.querySelector( '.hours-value' ), pacingMinutesEl = pacingEl.querySelector( '.minutes-value' ), pacingSecondsEl = pacingEl.querySelector( '.seconds-value' ); var timings = null; getTimings( function ( _timings ) { timings = _timings; if (_timings !== null) { pacingTitleEl.style.removeProperty('display'); pacingEl.style.removeProperty('display'); // ... rest of the timer setup ``` -------------------------------- ### Start CPU Hotspot Identification JFR Recording Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/blog/2025/09/jfr-modern-java-profiling.html Begin a JFR recording to identify CPU hotspots. This setup focuses on execution samples, CPU time, and thread CPU load. ```shell jcmd JFR.start name=cpu-analysis duration=60s \ "jdk.ExecutionSample#enabled=true" \ "jdk.CPUTimeSample#enabled=true" \ "jdk.ThreadCPULoad#enabled=true" \ filename=cpu-hotspots.jfr ``` -------------------------------- ### Good Example: Paginated, Sorted, and Filtered Product List Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/302-frameworks-spring-boot-rest/references/302-frameworks-spring-boot-rest.md Demonstrates proper handling of pagination, sorting, and filtering for product listings. Enforces page size limits and whitelists sortable properties to prevent injection vulnerabilities. Optionally includes Link headers for discoverability. ```java import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Set; @RestController @RequestMapping("/api/v1/products") class ProductQueryController { private static final int MAX_PAGE_SIZE = 100; private static final Set ALLOWED_SORT = Set.of("createdAt", "name", "price"); @GetMapping ResponseEntity> list( @RequestParam(required = false) String category, @PageableDefault(size = 20, sort = "createdAt") Pageable pageable) { if (pageable.getPageSize() > MAX_PAGE_SIZE) { throw new IllegalArgumentException("page size exceeds maximum of " + MAX_PAGE_SIZE); } pageable.getSort().forEach(order -> { if (!ALLOWED_SORT.contains(order.getProperty())) { throw new IllegalArgumentException("sort by '" + order.getProperty() + "' is not allowed"); } }); Page page = Page.empty(pageable); return ResponseEntity.ok() .header(HttpHeaders.LINK, "; rel=\"next\"") .body(page); } } class ProductDTO { } ``` -------------------------------- ### Execute Profiling Script with Help Source: https://github.com/jabrena/cursor-rules-java/blob/main/site-generator/content/courses/profile-memory-leak/module-1-foundations.md Navigate to the profiler scripts directory and execute the main profiling script with the --help flag. This displays the available profiling options and configurations. ```bash cd profiler/scripts ./profile-java-process.sh --help ``` -------------------------------- ### Generated Task List Example Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/blog/2026/03/release-0.13.0.html Shows a detailed task list generated by an agent, including phases, TDD status, milestones, and parallel execution information. This list guides the development process. ```markdown ## Task List | # | Task | Phase | TDD | Milestone | Parallel | Status | |---|------|-------|-----|-----------|----------|--------| | 1 | Extend **implementation2** `pom.xml`: `quarkus-rest`, JDBC PostgreSQL, Flyway, scheduler, SmallRye OpenAPI, outbound HTTP client dep (or JDK client only), `rest-assured`, Testcontainers, Failsafe for `*IT`; plan `%test` datasource | Setup | | | A1 | Done | | 2 | **RED:** `GreekGodsApiIT` — REST Assured `GET /api/v1/gods/greek` expects **200**, JSON array, 20 canonical names (set equality), no duplicates (fails until slice exists) | RED | Test | | A1 | Done | | 3 | **GREEN:** Flyway migration matching [schema.sql](../design/schema.sql); seed 20 names (Flyway test data / IT setup); JDBC repository `findAllNamesOrdered()`; Jakarta REST resource; no external call on read path | GREEN | Impl | | A1 | Done | | 4 | **Refactor:** Structured logging (read path): request or repo boundaries per team standard | Refactor | | | A1 | Done | | 5 | **Refactor:** `ExceptionMapper` for persistence failures → 500 `application/problem+json`; empty DB IT → 200 `[]`; invalid JDBC / container stop for 500 shape; external base URL property (no hard-coded URL) | Refactor | | | A1 | Done | | 6 | **Verify:** `./mvnw clean verify` in **implementation2**; fix failures before M2 | Verify | | milestone | A1 | Done | ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/courses/system-prompts-java/index.html Clone the project repository to your local machine and navigate into the project directory. ```bash git clone https://github.com/jabrena/cursor-rules-java.git cd cursor-rules-java ``` -------------------------------- ### Add Cursor Rules Java Skills using 'npx skills' Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/blog/2026/03/release-0.12.0.html Install Skills from the Cursor Rules Java repository using the 'npx skills' command. This example shows how to add a specific skill. ```bash brew install node npx skills add jabrena/cursor-rules-java --list ``` -------------------------------- ### Application Bootstrap with Micronaut.run Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/501-frameworks-micronaut-core/references/501-frameworks-micronaut-core.md Start the embedded Netty server and application context with `Micronaut.run`. Avoid embedding business logic in `main`. ```java import io.micronaut.runtime.Micronaut; public final class Application { public static void main(String[] args) { Micronaut.run(Application.class, args); } } ``` ```java import io.micronaut.runtime.Micronaut; public final class Application { public static void main(String[] args) { // Bad: business work in main — untestable and couples startup to domain new OrderBacklogProcessor().drainAllQueues(); Micronaut.run(Application.class, args); } } ``` -------------------------------- ### Base Quarkus Acceptance Test Setup Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/423-frameworks-quarkus-testing-acceptance-tests/references/423-frameworks-quarkus-testing-acceptance-tests.md Abstract base class for Quarkus acceptance tests. It uses `@QuarkusTest` to start the application once per test suite and integrates `PostgreSQLLifecycleManager` and `WireMockLifecycleManager` to provide real infrastructure dependencies. ```java // Base acceptance test: Quarkus starts once; containers and WireMock are shared across tests @QuarkusTest @QuarkusTestResource(PostgreSQLLifecycleManager.class) @QuarkusTestResource(WireMockLifecycleManager.class) abstract class BaseAcceptanceTest { @BeforeEach void resetWireMock() { WireMockLifecycleManager.wireMockServer.resetAll(); // isolate stubs between test methods } } ``` -------------------------------- ### Incorrect Test Suffix with Spring Boot Example Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/322-frameworks-spring-boot-testing-integration-tests/references/322-frameworks-spring-boot-testing-integration-tests.md Illustrates a test class named `*Test` but configured with `@SpringBootTest` and a real container. This incorrect setup leads to Surefire executing it in the wrong phase and bypasses Failsafe's verification. ```java // Bad: class name ends in "Test" but uses @SpringBootTest with a real container — // Surefire will execute it in the wrong phase; Failsafe's "verify" safety net is bypassed, // so a container failure won't fail the build at the right gate. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @Testcontainers class OrderApiTest { // ← should be OrderApiIT @Container @ServiceConnection static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @Test void shouldCreateOrder() { ... } } ``` -------------------------------- ### Good Test Example: CORRECT Boundary Conditions in Java Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/130-java-testing-strategies/references/130-java-testing-strategies.md Demonstrates comprehensive boundary condition testing using the CORRECT principles (Conformance, Ordering, Range, Existence, Cardinality, Time) for user validation. ```java public class UserValidationTest { private final UserValidation validator = new UserValidation(); // Testing Range for age @Test void isAgeValid_ageAtLowerBound_returnsTrue() { assertThat(validator.isAgeValid(18)).isTrue(); } @Test void isAgeValid_ageAtUpperBound_returnsTrue() { assertThat(validator.isAgeValid(120)).isTrue(); } @Test void isAgeValid_ageBelowLowerBound_returnsFalse() { assertThat(validator.isAgeValid(17)).isFalse(); } // Testing Conformance for email @ParameterizedTest @ValueSource(strings = {"user@example.com", "user.name@sub.example.co.uk"}) void isValidEmailFormat_validEmails_returnsTrue(String email) { assertThat(validator.isValidEmailFormat(email)).isTrue(); } @ParameterizedTest @ValueSource(strings = {"userexample.com", "user@", "@example.com"}) void isValidEmailFormat_invalidEmails_returnsFalse(String email) { assertThat(validator.isValidEmailFormat(email)).isFalse(); } // Testing Existence for username @Test void processUsername_nullUsername_returnsFalse() { assertThat(validator.processUsername(null)).isFalse(); } @Test void processUsername_emptyUsername_returnsFalse() { assertThat(validator.processUsername("")).isFalse(); } } ``` -------------------------------- ### Create Comprehensive Solutions Document Source: https://github.com/jabrena/cursor-rules-java/blob/main/site-generator/content/courses/profile-memory-leak/module-3-analysis.md Generates a markdown file for profiling solutions and recommendations. It includes quick wins and medium-term improvements, with placeholders for date and specific code changes. ```bash # Create comprehensive solutions document DATE_SUFFIX=$(date +%Y%m%d) cat > solutions/profiling-solutions-${DATE_SUFFIX}.md << 'EOF' # Profiling Solutions and Recommendations - [DATE] ## Quick Wins (Low effort, High impact) ### Solution 1: Enable Fixed Controller Implementation - **Problem**: Critical memory leaks in CocoController causing unbounded growth - **Solution**: Switch to NoCocoController using coco=false configuration - **Expected Impact**: Eliminate memory leaks immediately, stabilize memory usage - **Implementation Effort**: 5 minutes (configuration change) - **Code Changes**: ```properties # application.properties coco=false ``` - **Validation**: Memory usage should stabilize within 30 minutes of change ### Solution 2: Implement Collection Bounds - **Problem**: ArrayList grows without limits leading to memory exhaustion - **Solution**: Add MAX_OBJECTS constant and bounds checking - **Expected Impact**: Cap memory usage, provide graceful degradation - **Implementation Effort**: 30 minutes (add bounds checking) - **Code Changes**: ```java private static final int MAX_OBJECTS = 10000; if (objects.size() >= MAX_OBJECTS) { return ResponseEntity.badRequest() .body("Maximum objects limit reached: " + MAX_OBJECTS); } ``` ## Medium-term Improvements EOF ``` -------------------------------- ### Serve Website Locally with Maven Source: https://github.com/jabrena/cursor-rules-java/blob/main/CLAUDE.md Run this command to serve the project's website locally, mirroring the GitHub Pages setup. It uses JBake to generate and serve the site from the `site-generator` module. ```bash ./mvnw clean generate-resources jbake:inline -pl site-generator -P local-preview ``` -------------------------------- ### Navigate to Demo Project Directory Source: https://github.com/jabrena/cursor-rules-java/blob/main/docs/courses/profile-memory-leak/module-1-foundations.html Change the current directory to the root of the demo project to execute subsequent commands. ```bash cd ./cursor-rules-java/examples/spring-boot-memory-leak-demo ``` -------------------------------- ### Incomplete Spring Boot slice test without mock dependencies Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/321-frameworks-spring-boot-testing-unit-tests/references/321-frameworks-spring-boot-testing-unit-tests.md This example demonstrates a failing slice test where essential mock dependencies are missing. The test context will fail to start if required beans like OrderService or PaymentService are not provided via @MockBean or similar mechanisms. ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest(OrderController.class) class OrderControllerTest { @Autowired private MockMvc mockMvc; @Test void shouldCreateOrder() throws Exception { mockMvc.perform(post("/api/orders") .contentType(MediaType.APPLICATION_JSON) .content("{}")) .andExpect(status().isCreated()); } } ``` -------------------------------- ### Semantic HTTP Methods Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/502-frameworks-micronaut-rest/references/502-frameworks-micronaut-rest.md This example demonstrates the correct usage of HTTP methods (GET, POST, PUT, PATCH, DELETE) for CRUD operations in a Micronaut controller. It maps operations to the appropriate HTTP verb to ensure server state is managed correctly and to follow RESTful principles. ```APIDOC ## GET /users/{id} ### Description Retrieves a user by their ID. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (String) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **UserDto** (Object) - The user data transfer object. ### Response Example ```json { "id": "user-123" } ``` ## POST /users ### Description Creates a new user. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **UserCreateDto** (Object) - Required - The data for creating a new user. - **username** (String) - Required - The username for the new user. - **email** (String) - Required - The email address for the new user. ### Response #### Success Response (201) - **UserDto** (Object) - The created user data transfer object. ### Response Example ```json { "id": "user-456" } ``` ## PUT /users/{id} ### Description Updates an existing user by their ID. ### Method PUT ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (String) - Required - The unique identifier of the user to update. #### Request Body - **UserUpdateDto** (Object) - Required - The updated user data. - **username** (String) - Required - The updated username. - **email** (String) - Required - The updated email address. ### Response #### Success Response (200) - **UserDto** (Object) - The updated user data transfer object. ### Response Example ```json { "id": "user-123" } ``` ## PATCH /users/{id} ### Description Partially updates an existing user by their ID. ### Method PATCH ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (String) - Required - The unique identifier of the user to partially update. #### Request Body - **UserPatchDto** (Object) - Required - The partial update data for the user. - **username** (String) - Optional - The updated username. - **email** (String) - Optional - The updated email address. ### Response #### Success Response (200) - **UserDto** (Object) - The updated user data transfer object. ### Response Example ```json { "id": "user-123" } ``` ## DELETE /users/{id} ### Description Deletes a user by their ID. ### Method DELETE ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (String) - Required - The unique identifier of the user to delete. ### Response #### Success Response (204) No content is returned on successful deletion. ``` -------------------------------- ### Run Maven Integration Tests Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/112-java-maven-plugins/references/112-java-maven-plugins.md Command-line examples for running Maven tests. Use './mvnw verify' to run both unit and integration tests, or './mvnw failsafe:integration-test' to run only integration tests. ```bash # Run only unit tests ./mvnw test ``` ```bash # Run both unit and integration tests ./mvnw verify ``` ```bash # Run only integration tests ./mvnw failsafe:integration-test ``` -------------------------------- ### Inefficient JDBC Repository Test with @SpringBootTest Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/311-frameworks-spring-jdbc/references/311-frameworks-spring-jdbc.md Avoid using @SpringBootTest for testing JDBC repositories as it loads the entire application context, leading to slow startup times and unnecessary overhead. This example also shows a test that lacks fixture setup, making it dependent on pre-existing database state. ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; // Bad: full application context loaded just to test a JDBC repository — // slow startup, loads web layer and all beans unnecessarily @SpringBootTest class ProductRepositoryTest { @Autowired ProductRepository productRepository; @Test void findActive() { // Bad: no fixture setup — test depends on pre-existing database state List active = productRepository.findActive(); assertThat(active).isNotEmpty(); } } ``` -------------------------------- ### Verify OpenSpec Installation Source: https://github.com/jabrena/cursor-rules-java/blob/main/skills/042-planning-openspec/references/042-planning-openspec.md Check if OpenSpec is installed and accessible. If not, provides installation instructions using npm. ```bash openspec --version ``` ```bash npm install -g @fission-ai/openspec@latest openspec --version ```