java-rules
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "java-rules" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-533d627df5f338c90708dfa7d803c09d87af4312be95dc3ae258b31e3876fab9. Verify the upstream source and version against https://github.com/softspark/ai-toolkit before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Java coding standards covering style, design patterns, security, and testing practices, targeting .java, pom.xml, build.gradle and common ecosystem tools (Spring, Spring Boot, JPA, Hibernate, JUnit, Maven, Gradle). Trigger conditions example: .java, pom.xml, build.gradle, Spring, Spring Boot, JPA, Hibernate, JUnit, Maven, Gradle.
Introduction source: third_party · softspark · 0.0.1 Reference
SkillPi interpretation
- Tasks
- Java coding rules: style, patterns, security, testing. Triggers: .java, pom.xml, build.gradle, Spring, Spring Boot, JPA, Hibernate, JUnit, Maven, Gradle.
- Inputs and outputs
- Validate all input with Jakarta Bean Validation (`@NotNull`, `@Size`, `@Email`). Use `@Valid` on controller parameters to trigger validation automatically. Create custom validators for domain-specific rules. Never trust client-provided IDs. Verify resource ownership server-side.
- Testing
- Not tested
Browse files
Frontmatter
name: java-rules
description: "Java coding rules: style, patterns, security, testing. Triggers: .java, pom.xml, build.gradle, Spring, Spring Boot, JPA, Hibernate, JUnit, Maven, Gradle."
effort: medium
user-invocable: false
allowed-tools: ReadJava Rules
These rules come from app/rules/java/ in ai-toolkit. They cover
the project's standards for coding style, frameworks, patterns,
security, and testing in Java. Apply them when writing or
reviewing Java code.
Java Coding Style
Naming
- PascalCase: classes, interfaces, enums, records, annotations.
- camelCase: methods, variables, parameters.
- UPPER_SNAKE: constants (
static final). - Package names: lowercase, dot-separated, reverse domain (
com.company.project). - No Hungarian notation. No
Iprefix on interfaces.
Modern Java (17+)
- Use
recordfor immutable data carriers. No need for Lombok in most cases. - Use
sealedclasses/interfaces for restricted hierarchies. - Use pattern matching:
if (obj instanceof String s)instead of cast. - Use
switchexpressions with arrow syntax and exhaustiveness. - Use text blocks (
""") for multiline strings (SQL, JSON, HTML).
Types
- Use
varfor local variables when the type is obvious from the right-hand side. - Use
Optional<T>for return types that may be absent. Never for fields or params. - Prefer
List.of(),Map.of(),Set.of()for immutable collections. - Use
Streamfor collection transformations. Avoid streams for simple iterations.
Classes
- Prefer composition over inheritance. Use interfaces for abstraction.
- Keep classes focused: single responsibility.
- Use
finalon classes not designed for extension. - Use
privateconstructors + static factory methods for controlled instantiation. - Records over POJOs for value types. Lombok only if records are insufficient.
Methods
- Max 20-30 lines per method. Extract when longer.
- Use
@Overrideon every overridden method. - Return empty collections over
null. UseCollections.emptyList()orList.of(). - Avoid checked exceptions for programming errors. Use runtime exceptions.
Formatting
- Use project formatter (Google Java Format or IDE-configured).
- Use
@SuppressWarningssparingly and with specific warning names. - Use
finalfor parameters and local variables where practical.
Nullability
- Annotate with
@Nullable/@NonNullfrom JSpecify or JetBrains. - Use
Objects.requireNonNull()at public API boundaries. - Never return
nullfrom collections or arrays. Return empty. - Use
Optionalfor genuinely optional return values.
Documentation
- Javadoc on all public classes and methods.
- Use
@param,@return,@throwstags for public API methods. - Skip Javadoc for obvious getters,
toString(), andequals().
Java Frameworks
Spring Boot
- Use Spring Boot 3+ with Java 17+ minimum.
- Use
@RestControllerfor REST APIs. ReturnResponseEntityfor status control. - Use
@Valid+ Jakarta Bean Validation for request validation. - Use profiles (
@Profile) for environment-specific configuration. - Use
application.ymloverapplication.propertiesfor readability. - Externalize config: env vars > config files > hardcoded defaults.
Spring Data JPA
- Use repository interfaces extending
JpaRepository. - Use
@Querywith JPQL for custom queries. Use native queries only when needed. - Use
@EntityGraphto prevent N+1 queries in associations. - Use
Specificationfor dynamic query building. - Always use
@Transactionalat the service layer, not repository.
Spring Security
- Use
SecurityFilterChainbean configuration (notWebSecurityConfigurerAdapter). - Use
@PreAuthorize/@Securedfor method-level authorization. - Use BCrypt for password encoding:
new BCryptPasswordEncoder(). - Configure CORS, CSRF, and session management explicitly.
- Use OAuth2 Resource Server for JWT validation in APIs.
Hibernate / JPA
- Use
FetchType.LAZYby default on all associations. - Use
@BatchSizeor@Fetch(FetchMode.SUBSELECT)to avoid N+1. - Use
@Versionfor optimistic locking on entities. - Use DTOs (records) for read queries. Do not expose entities in APIs.
- Use Flyway or Liquibase for schema migrations.
Quarkus / Micronaut
- Use for microservices and serverless where startup time matters.
- Use compile-time DI (Micronaut) or build-time optimization (Quarkus).
- Use reactive patterns with Mutiny (Quarkus) or Reactor (Micronaut).
- Use native image builds with GraalVM for production deployments.
Build Tools
- Use Gradle (Kotlin DSL) for new projects. Maven for enterprise legacy.
- Use dependency management to unify versions across modules.
- Use Bill of Materials (BOM) imports for consistent Spring versions.
- Use Spotless or Checkstyle for enforced code formatting.
Logging
- Use SLF4J facade with Logback or Log4j2 backend.
- Use structured logging with MDC for correlation IDs.
- Use parameterized logging:
log.info("User {} created", userId). - Never log sensitive data (passwords, tokens, PII).
Java Patterns
Error Handling
- Use unchecked exceptions for programming errors (
IllegalArgumentException). - Use checked exceptions only for recoverable conditions the caller must handle.
- Create domain exception hierarchy:
AppException->NotFoundException, etc. - Never catch
ExceptionorThrowablebroadly. Catch specific types. - Use
try-with-resourcesfor allAutoCloseableresources.
Immutability
- Use
recordfor immutable value objects (Java 16+). - Use
List.copyOf(),Map.copyOf()to create unmodifiable copies. - Make fields
private final. No setters unless mutation is required. - Return defensive copies of mutable collections from getters.
- Use builder pattern for constructing immutable objects with many fields.
Optional
- Use
Optional<T>as return type for methods that may not return a value. - Chain:
optional.map(...).orElseThrow(...). AvoidisPresent()+get(). - Never use
Optionalfor fields, method parameters, or collection elements. - Use
Optional.empty()overnull. UseOptional.ofNullable()at boundaries.
Streams
- Use streams for transformations:
filter,map,collect. - Avoid side effects in stream operations. Keep them pure.
- Use
Collectors.toUnmodifiableList()for immutable results. - Prefer
forloop for simple iterations that do not transform data. - Use
Stream.of()orIntStream.range()for generating sequences.
Dependency Injection
- Use constructor injection exclusively. No field or setter injection.
- Accept interfaces in constructors, not implementations.
- Use
@Component,@Service,@Repositoryfor Spring-managed beans. - Keep the number of constructor dependencies under 5. Split if more.
Concurrency
- Use
ExecutorServiceandCompletableFuturefor async operations. - Use
virtual threads(Java 21+) for I/O-bound concurrent work. - Use
ConcurrentHashMap,AtomicIntegerfor thread-safe operations. - Avoid
synchronizedblocks when possible -- use higher-level concurrency. - Use
ReentrantReadWriteLockfor read-heavy shared state.
Design Patterns
- Use Strategy pattern (via interfaces) over switch/if-else chains.
- Use Factory methods for flexible object creation.
- Use Decorator pattern for composable behavior augmentation.
- Avoid Singleton pattern -- use DI container for lifecycle management.
Anti-Patterns
- Returning
nullfrom methods -- useOptionalor empty collections. - Mutable DTOs with getters/setters -- use records.
- God classes with 20+ dependencies -- split by responsibility.
- String typing for domain values -- use types, enums, or value objects.
Java Security
Input Validation
- Validate all input with Jakarta Bean Validation (
@NotNull,@Size,@Email). - Use
@Validon controller parameters to trigger validation automatically. - Create custom validators for domain-specific rules.
- Never trust client-provided IDs. Verify resource ownership server-side.
SQL Injection
- Use JPA/Hibernate parameterized queries. Never concatenate input into JPQL/SQL.
- Use
CriteriaBuilderor Specifications for dynamic queries. - For native queries, use named parameters:
@Query(value = "... WHERE id = :id", nativeQuery = true). - Use
PreparedStatementif using JDBC directly. NeverStatementwith concatenation.
Authentication
- Use Spring Security with BCrypt (
BCryptPasswordEncoder) for password hashing. - Use JWT with short expiration (15 min) + refresh tokens for APIs.
- Implement account lockout after N failed attempts.
- Use
@AuthenticationPrincipalto access the current user in controllers.
Authorization
- Use
@PreAuthorize("hasRole('ADMIN')")for role-based access control. - Use method security for fine-grained authorization.
- Check resource ownership in service layer, not just role membership.
- Default deny: require explicit authorization for every endpoint.
XSS and CSRF
- Spring auto-escapes Thymeleaf output. Do not use
th:utextwith user data. - Enable CSRF protection for session-based auth. Disable only for stateless JWT APIs.
- Set
Content-Typeheaders explicitly on responses. - Use CSP headers to restrict script sources.
Serialization
- Do not deserialize untrusted data with
ObjectInputStream(RCE risk). - Use Jackson with
@JsonIgnoreProperties(ignoreUnknown = true). - Disable default typing in Jackson: never use
enableDefaultTyping(). - Validate deserialized objects with Bean Validation after parsing.
Dependencies
- Run OWASP Dependency-Check in CI:
mvn verify -P owasp-check. - Update Spring Boot regularly -- security patches are frequent.
- Use
dependencyManagementto control transitive dependency versions. - Audit
mvn dependency:treefor unexpected transitive dependencies.
Secrets
- Use Spring Cloud Config or Vault for secrets management.
- Use
@Value("${secret}")with env var placeholders, not hardcoded values. - Never log request headers containing
Authorizationor session tokens. - Use separate config profiles for dev/staging/prod with different secrets.
Logging Security
- Use parameterized logging to prevent log injection.
- Sanitize user input before logging: remove newlines and control characters.
- Never log stack traces to API responses. Return generic error messages.
Java Testing
Framework
- Use JUnit 5 (Jupiter) for all new tests. No JUnit 4.
- Use AssertJ for fluent, readable assertions.
- Use Mockito for mocking dependencies.
- Use Testcontainers for integration tests with databases/services.
File Naming
- Test classes:
FooTest.javainsrc/test/java/mirroring source package. - Integration tests:
FooIT.javaor use@Tag("integration"). - Test utilities:
src/test/java/.../support/orTestUtils.java.
Structure
- Use
@Nestedclasses to group related tests within a test class. - Use
@DisplayNamefor human-readable test descriptions. - Use
@BeforeEachfor setup,@AfterEachfor cleanup. - Use
@ParameterizedTestwith@ValueSource,@CsvSource,@MethodSource.
Assertions (AssertJ)
- Use
assertThat(actual).isEqualTo(expected)over JUnit assertions. - Use
assertThatThrownBy(() -> ...).isInstanceOf(FooException.class). - Use
assertThat(list).hasSize(3).extracting("name").contains("Ada"). - Chain assertions for readable, self-documenting tests.
Mocking (Mockito)
- Use
@Mock+@ExtendWith(MockitoExtension.class)for injection. - Use
when().thenReturn()for stubbing.verify()for interaction checking. - Use
@InjectMocksto auto-inject mocks into the class under test. - Prefer constructor injection in production code for testability.
- Use
ArgumentCaptorto inspect complex arguments.
Integration Testing
- Use Testcontainers for PostgreSQL, Redis, Kafka, etc.
- Use
@SpringBootTestsparingly -- it starts the full context. Prefer slices. - Use
@WebMvcTestfor controller tests,@DataJpaTestfor repository tests. - Use
@TestConfigurationfor test-specific bean overrides.
Test Data
- Use test builders or factory methods for creating test objects.
- Use
@Sqlannotation to load test data from SQL files. - Keep test data minimal. Only set fields relevant to the behavior under test.
- Use random UUIDs for IDs in tests to avoid collision.
Performance
- Run tests in parallel: configure
junit.jupiter.execution.parallel.enabled=true. - Use
@SpringBootTestonly when integration context is needed. - Mock external dependencies in unit tests for speed.
- Keep the full test suite under 5 minutes.
Version history
-
v6.2.0
GitHub ↗
Original release notes
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0
-
v6.1.0
GitHub ↗
Original release notes
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0
-
v6.0.0
GitHub ↗
Original release notes
## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0
-
v5.5.0
GitHub ↗
Original release notes
### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0
-
v5.4.2
GitHub ↗
Original release notes
## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2
Only the five most recent versions are shown. View full version history at the source ↗
Current listing version
0.0.1
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供全面的 Java 编码规范,涵盖风格、框架、安全、测试等关键领域
- 适用于广泛的 Java 开发者,具有明确的实用价值和通用性
Highlights
- 触发条件明确列出 .java、pom.xml、build.gradle 等文件类型及 Spring、JUnit 等关键词
- 覆盖合理,边界清晰
Highlights
- 文档结构清晰,分章节覆盖 Style、Frameworks、Patterns、Security、Testing
- 每部分有具体条目和示例,frontmatter 完整
Highlights
- 内容为静态规则文档,无动态执行逻辑,工具来源为通用 Java 生态标准
- 参数建议合理,覆盖主要异常处理和安全实践
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.