mirror of
https://github.com/apache/struts.git
synced 2026-08-31 19:35:40 +00:00
6.9 KiB
6.9 KiB
Claude Code Best Practices for Apache Struts
This document outlines essential practices for working with Claude Code on the Apache Struts project, based on security improvements and testing implementations.
Project Context
- Framework: Apache Struts 2 (Java-based web framework)
- Technology Stack: Jakarta EE, Maven, Java 17
- Key Libraries: OGNL, Commons FileUpload2, Log4j2, JUnit, AssertJ
- Build System: Maven with standard lifecycle
Security-First Development
Critical Security Principles
- Never create files in system temp directories - always use controlled application directories
- Use UUID-based naming for temporary files to prevent collisions and path traversal
- Implement proper resource cleanup with try-with-resources and finally blocks
- Track all temporary resources for explicit cleanup (security critical)
- Validate all user inputs and sanitize filenames before processing
Security Implementation Patterns
// GOOD: Secure temporary file creation
protected File createTemporaryFile(String fileName, Path location) {
String uid = UUID.randomUUID().toString().replace("-", "_");
File file = location.resolve("upload_" + uid + ".tmp").toFile();
LOG.debug("Creating temporary file: {} (originally: {})", file.getName(), fileName);
return file;
}
// BAD: Insecure system temp usage
File tempFile = File.createTempFile("struts_upload_", "_" + item.getName());
Resource Management
- Always use tracking collections for cleanup:
List<File> temporaryFiles,List<DiskFileItem> diskFileItems - Implement protected cleanup methods for extensibility
- Make cleanup idempotent and exception-safe
- Use try-with-resources for streams and I/O operations
Testing Implementation
Test Structure & Coverage
- Unit Tests: Test individual methods with mocked dependencies
- Integration Tests: Test complete workflows with real file I/O
- Security Tests: Verify directory traversal prevention, secure naming
- Error Handling Tests: Test exception scenarios and error reporting
- Cleanup Tests: Verify resource cleanup and tracking
Testing Commands
# Run all tests
mvn test -DskipAssembly
# Run specific test class
mvn test -Dtest=JakartaMultiPartRequestTest
# Run tests with specific method pattern
mvn test -Dtest=*MultiPartRequestTest#temporal*
use -DskipAssembly to avoid building zip files with docs, examples, etc.
Test Implementation Patterns
@Test
public void securityTestExample() throws Exception {
// given - malicious input
String maliciousFilename = "malicious../../../etc/passwd";
// when - process input
processFile(maliciousFilename);
// then - verify security measures
assertThat(tempFile.getParent()).isEqualTo(saveDir);
assertThat(tempFile.getName()).doesNotContain("..");
}
Reflection-Based Testing for Private Members
Field privateField = ClassName.class.getDeclaredField("fieldName");
privateField.setAccessible(true);
@SuppressWarnings("unchecked")
List<Type> values = (List<Type>) privateField.get(instance);
JavaDoc Documentation Standards
Class-Level Documentation
/**
* Brief description of the class purpose and functionality.
*
* <p>Detailed description with multiple paragraphs explaining:</p>
* <ul>
* <li>Key features and capabilities</li>
* <li>Security considerations</li>
* <li>Resource management approach</li>
* <li>Usage patterns and examples</li>
* </ul>
*
* <p>Usage example:</p>
* <pre>
* ClassName instance = new ClassName();
* try {
* instance.process(data);
* } finally {
* instance.cleanUp(); // Always clean up resources
* }
* </pre>
*
* @see RelatedClass
* @see org.apache.package.ImportantInterface
*/
Method-Level Documentation
/**
* Brief description of what the method does.
*
* <p>Detailed description explaining:</p>
* <ol>
* <li>Step-by-step process</li>
* <li>Security considerations</li>
* <li>Error handling behavior</li>
* <li>Resource management</li>
* </ol>
*
* <p>Security note: This method creates files in controlled directory
* to prevent security vulnerabilities.</p>
*
* @param paramName description of parameter and constraints
* @param saveDir the directory where files will be created (must exist)
* @return description of return value
* @throws IOException if file creation fails or I/O error occurs
* @see #relatedMethod(Type)
* @see #cleanUpMethod()
*/
Documentation Best Practices
- Always document security implications in methods handling files/user input
- Include usage examples for complex methods and classes
- Document exception conditions and error handling behavior
- Reference related methods using
@seetags - Explain resource management responsibilities
- **Use
<p>,<ol>,<ul>,<li>for structured content - Include
<pre>blocks for code examples
Error Handling & Logging
Error Message Patterns
// Localized error messages
LocalizedMessage errorMessage = buildErrorMessage(
e.getClass(),
e.getMessage(),
new Object[]{fileName}
);
if (!errors.contains(errorMessage)) {
errors.add(errorMessage);
}
Logging Best Practices
// Use parameterized logging for performance
LOG.debug("Processing file: {} in directory: {}",
normalizeSpace(fileName), saveDir);
// Log security-relevant operations
LOG.warn("Failed to delete temporary file: {}", tempFile.getAbsolutePath());
// Use appropriate log levels
LOG.debug() // Development details
LOG.info() // General information
LOG.warn() // Potential issues
LOG.error() // Serious problems
Code Quality Standards
Method Scope & Extensibility
- Use
protectedfor methods that subclasses might override - Implement cleanup methods as separate
protectedmethods - Make core functionality extensible while maintaining security
Exception Handling
- Catch specific exceptions rather than generic
Exception - Log exceptions with context but continue cleanup operations
- Use try-finally blocks to ensure cleanup always occurs
Code Organization
- Group related methods together (processing, cleanup, utilities)
- Keep security-critical code in dedicated methods
- Use clear, descriptive method and variable names
- Follow existing project conventions and patterns
Common Pitfalls to Avoid
- File Security: Never use
File.createTempFile()without directory control - Resource Leaks: Always track and clean up temporary files
- Test Coverage: Don't forget to test error conditions and cleanup
- Documentation: Always document security implications
- Exception Handling: Don't let cleanup failures affect main operations
- Path Validation: Always validate and sanitize file paths
- Reflection Testing: Use
@SuppressWarnings("unchecked")appropriately
This document should be updated as new patterns and practices emerge during development.