java
Java language (17+). Covers modern features, patterns, and best practices. Use when writing Java applications, Spring Boot backends, or enterprise systems. USE WHEN: user mentions "java", "records", "sealed classes", "streams", asks about "pattern matching", "switch expressions", "Optional", "collections", "generics" DO NOT USE FOR: Spring Boot specifics - use `backend-spring-boot` skill instead DO NOT USE FOR: Lombok annotations - use `lombok` skill instead DO NOT USE FOR: MapStruct - use `mapstruct` skill instead
What this skill does
# Java Core Knowledge
## Modern Java Features (17+)
```java
// Records (immutable data classes)
public record User(Long id, String name, String email) {}
// Sealed classes
public sealed interface Shape permits Circle, Rectangle {}
public final class Circle implements Shape { }
public final class Rectangle implements Shape { }
// Pattern matching for instanceof
if (obj instanceof String s) {
System.out.println(s.toUpperCase());
}
// Switch expressions
String result = switch (status) {
case ACTIVE -> "Active";
case INACTIVE -> "Inactive";
default -> "Unknown";
};
// Text blocks
String json = """
{
"name": "John",
"age": 30
}
""";
```
## Collections & Streams
```java
// Stream operations
List<String> names = users.stream()
.filter(u -> u.isActive())
.map(User::getName)
.sorted()
.collect(Collectors.toList());
// Grouping
Map<Status, List<User>> byStatus = users.stream()
.collect(Collectors.groupingBy(User::getStatus));
// Optional handling
Optional<User> user = findById(id);
String name = user.map(User::getName).orElse("Unknown");
```
## Common Patterns
```java
// Builder pattern
User user = User.builder()
.name("John")
.email("[email protected]")
.build();
// Factory method
public static User of(String name, String email) {
return new User(null, name, email);
}
// Dependency Injection (constructor)
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
}
```
## Exception Handling
```java
// Custom exception
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super("User not found: " + id);
}
}
// Try-with-resources
try (var reader = new BufferedReader(new FileReader(file))) {
return reader.lines().collect(Collectors.toList());
}
```
---
## Static Analysis & Linting
### Official Rules References
| Tool | Rules Count | Documentation |
|------|-------------|---------------|
| **SonarJava** | 733 | https://rules.sonarsource.com/java/ |
| **Checkstyle** | 200+ | https://checkstyle.org/checks.html |
| **PMD** | 400+ | https://pmd.github.io/latest/pmd_rules_java.html |
| **SpotBugs** | 400+ | https://spotbugs.readthedocs.io/en/latest/bugDescriptions.html |
### Style Guides
| Guide | Link |
|-------|------|
| **Google Java Style** | https://google.github.io/styleguide/javaguide.html |
| **Oracle Code Conventions** | https://www.oracle.com/java/technologies/javase/codeconventions-contents.html |
### Key Rules Categories
```xml
<!-- pom.xml - Maven Checkstyle Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.3.1</version>
<configuration>
<configLocation>google_checks.xml</configLocation>
</configuration>
</plugin>
```
### Critical Rules to Enable
| Category | Rule | Tool |
|----------|------|------|
| Bug | NullPointerException risks | SonarJava S2259 |
| Bug | Resource leaks | SonarJava S2095 |
| Security | SQL Injection | SonarJava S3649 |
| Security | Hardcoded credentials | SonarJava S2068 |
| Maintainability | Cognitive complexity | SonarJava S3776 |
| Maintainability | Too many parameters | Checkstyle |
---
## Production Readiness
### Error Handling
```java
// Custom exception hierarchy
public abstract class BaseException extends RuntimeException {
private final String errorCode;
private final int httpStatus;
protected BaseException(String message, String errorCode, int httpStatus) {
super(message);
this.errorCode = errorCode;
this.httpStatus = httpStatus;
}
public String getErrorCode() { return errorCode; }
public int getHttpStatus() { return httpStatus; }
}
public class EntityNotFoundException extends BaseException {
public EntityNotFoundException(String entity, Object id) {
super(
String.format("%s not found with id: %s", entity, id),
"NOT_FOUND",
404
);
}
}
// Global exception handler
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(BaseException.class)
public ResponseEntity<ErrorResponse> handleBaseException(BaseException ex) {
log.warn("Business error: {}", ex.getMessage());
return ResponseEntity
.status(ex.getHttpStatus())
.body(new ErrorResponse(ex.getErrorCode(), ex.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleUnexpected(Exception ex) {
log.error("Unexpected error", ex);
return ResponseEntity
.status(500)
.body(new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred"));
}
}
```
### Null Safety
```java
// Use Optional properly
public Optional<User> findById(Long id) {
return repository.findById(id);
}
// Never return null from Optional
public User getById(Long id) {
return findById(id)
.orElseThrow(() -> new EntityNotFoundException("User", id));
}
// Use @Nullable and @NonNull annotations
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
public User updateUser(@NonNull Long id, @Nullable String email) {
User user = getById(id);
if (email != null) {
user.setEmail(email);
}
return repository.save(user);
}
// Validation
import jakarta.validation.constraints.*;
public record CreateUserRequest(
@NotBlank @Size(min = 2, max = 100) String name,
@NotBlank @Email String email,
@NotNull @Min(0) Integer age
) {}
```
### Logging
```java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
@Service
public class UserService {
private static final Logger log = LoggerFactory.getLogger(UserService.class);
public User createUser(CreateUserRequest request) {
MDC.put("operation", "createUser");
MDC.put("email", request.email());
log.info("Creating user");
try {
User user = userRepository.save(User.from(request));
log.info("User created successfully: {}", user.getId());
return user;
} catch (Exception e) {
log.error("Failed to create user", e);
throw e;
} finally {
MDC.clear();
}
}
}
```
### Testing
```java
// Unit test with Mockito
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository repository;
@InjectMocks
private UserService service;
@Test
void shouldCreateUser() {
// Given
var request = new CreateUserRequest("John", "[email protected]", 30);
var expected = new User(1L, "John", "[email protected]", 30);
when(repository.save(any())).thenReturn(expected);
// When
var result = service.createUser(request);
// Then
assertThat(result).isEqualTo(expected);
verify(repository).save(any());
}
@Test
void shouldThrowWhenUserNotFound() {
// Given
when(repository.findById(1L)).thenReturn(Optional.empty());
// When/Then
assertThatThrownBy(() -> service.getById(1L))
.isInstanceOf(EntityNotFoundException.class)
.hasMessageContaining("User not found");
}
}
// Integration test
@SpringBootTest
@AutoConfigureMockMvc
@Testcontainers
class UserControllerIT {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
@Autowired
private MockMvc mockMvc;
@Test
void shouldCreateUser() throws Exception {
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name": "John",Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.