From 12f2caebf9625d135b5a41b5283462f1ccfdb05f Mon Sep 17 00:00:00 2001 From: ngirchev Date: Mon, 8 Dec 2025 22:42:49 +0200 Subject: [PATCH 1/3] Initial release of dotenv library with comprehensive features, including environment variable loading, support for comments, and logging. Added Checkstyle and PMD configurations for code quality, along with SonarCloud integration for project analysis. --- CHANGELOG.md | 30 +++++++++++ checkstyle.xml | 114 +++++++++++++++++++++++++++++++++++++++ pmd-ruleset.xml | 37 +++++++++++++ sonar-project.properties | 11 ++++ 4 files changed, 192 insertions(+) create mode 100644 CHANGELOG.md create mode 100644 checkstyle.xml create mode 100644 pmd-ruleset.xml create mode 100644 sonar-project.properties diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..783b192 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,30 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [1.0.0] - 2025-XX-XX + +### Added +- Initial release of dotenv library for Java +- `DotEnvLoader.loadDotEnv()` method to load environment variables from default `.env` file +- `DotEnvLoader.loadDotEnv(Path)` method to load environment variables from custom path +- `DotEnvLoader.getEnv(String)` method to retrieve environment variables +- Support for comments in `.env` files (lines starting with `#`) +- Automatic whitespace trimming for keys and values +- Safe loading: existing System properties and environment variables are never overwritten +- SLF4J logging support for debugging and monitoring +- Comprehensive JUnit 5 test suite +- Full JavaDoc documentation +- Maven Central publication support + +### Features +- Simple and lightweight library +- Safe: doesn't overwrite existing environment variables +- Supports comments in `.env` files +- Fully tested with JUnit 5 +- Logging support via SLF4J +- Compatible with Java 11+ + diff --git a/checkstyle.xml b/checkstyle.xml new file mode 100644 index 0000000..1417f5f --- /dev/null +++ b/checkstyle.xml @@ -0,0 +1,114 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pmd-ruleset.xml b/pmd-ruleset.xml new file mode 100644 index 0000000..7131413 --- /dev/null +++ b/pmd-ruleset.xml @@ -0,0 +1,37 @@ + + + + Custom PMD ruleset with adjusted thresholds + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 0000000..035b008 --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,11 @@ +sonar.projectKey=NGirchev_dotenv +sonar.organization=ngirchev +sonar.sources=src/main/java +sonar.tests=src/test/java +sonar.java.binaries=target/classes +sonar.java.test.binaries=target/test-classes +sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml +sonar.junit.reportPaths=target/surefire-reports +sonar.sourceEncoding=UTF-8 +sonar.host.url=https://sonarcloud.io + From 21179786342cc469a64c20a6198fec31a3067ba2 Mon Sep 17 00:00:00 2001 From: ngirchev Date: Mon, 8 Dec 2025 22:43:31 +0200 Subject: [PATCH 2/3] Refactor Checkstyle configuration and enhance documentation - Updated Checkstyle configuration in `checkstyle.xml` to use `accessModifiers` instead of `scope` for `JavadocMethod`. - Removed unnecessary `scope` properties from `JavadocType` and `JavadocVariable` modules. - Enhanced `CONTRIBUTING.md` with secure development practices, contribution requirements, and testing policies. - Updated `pom.xml` to include new plugins for static analysis (SpotBugs, JaCoCo, Checkstyle, PMD) and set coverage thresholds. - Improved README.md with detailed usage instructions, security vulnerability reporting process, and project build information. - Added CI configuration in `.github/workflows/ci.yml` for automated testing, code quality checks, and coverage reporting. --- .github/workflows/ci.yml | 30 +- CONTRIBUTING.md | 200 +++++++- README.md | 450 ++++++++++++++++-- checkstyle.xml | 10 +- pom.xml | 242 ++++++++++ pom.xml.releaseBackup | 197 ++++++++ release.properties | 27 ++ sonar-project.properties | 3 + .../github/ngirchev/dotenv/DotEnvLoader.java | 156 +++++- src/site/markdown/index.md | 24 + src/site/site.xml | 20 + 11 files changed, 1275 insertions(+), 84 deletions(-) create mode 100644 pom.xml.releaseBackup create mode 100644 release.properties create mode 100644 src/site/markdown/index.md create mode 100644 src/site/site.xml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6a51b03..3fbc7d0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,8 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 + with: + fetch-depth: 0 # Shallow clones should be disabled for better analysis - name: Set up JDK 11 uses: actions/setup-java@v4 @@ -26,5 +28,29 @@ jobs: java-version: '11' cache: maven - - name: Build and test - run: mvn -B -ntp test + - name: Build and test with coverage + run: mvn -B -ntp clean test jacoco:report + + - name: Run Checkstyle + run: mvn -B -ntp checkstyle:check + + - name: Run static code analysis + run: mvn -B -ntp spotbugs:check + + - name: SonarCloud Scan + uses: SonarSource/sonarcloud-github-action@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + continue-on-error: true + with: + projectBaseDir: . + + - name: Upload coverage reports + uses: codecov/codecov-action@v3 + with: + file: ./target/site/jacoco/jacoco.xml + flags: unittests + name: codecov-umbrella + fail_ci_if_error: false + if: always() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 60e2612..9f16889 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,6 +2,8 @@ Thank you for your interest in contributing to this project! We welcome any contributions. +**Language**: This project uses **English** for all documentation, code comments, commit messages, and issue discussions. Please submit all contributions, bug reports, and comments in English to ensure they can be understood and reviewed by the global developer community. + ## Development ### Requirements @@ -25,10 +27,36 @@ mvn clean install 4. Commit and push: `git push origin feature/your-feature-name` 5. Create a Pull Request on GitHub +**Note**: The project uses only FLOSS tools for building and testing (Maven, JUnit 5, OpenJDK). All tests must pass before submitting a Pull Request. + +**Development Workflow**: This project maintains a complete development history in the repository. **The repository includes interim versions for review between releases; it does NOT include only final releases.** + +All commits, branches, and Pull Requests are publicly available for collaborative review. This enables: +- **Transparent code review**: Contributors and reviewers can see the evolution of changes before they are included in a final release +- **Collaborative development**: All intermediate commits are visible, allowing for feedback and discussion during development +- **Complete history**: The full development process is documented, not just release snapshots + +**Note**: The project may choose to omit specific interim versions from the public repository only in exceptional cases (e.g., versions that fix non-public security vulnerabilities that may never be publicly released, or include material that cannot be legally posted and are not in the final release). + ## Release Process _Note: Only maintainers can publish releases._ +### Versioning + +This project uses [Semantic Versioning](https://semver.org/) (SemVer). Each release has a **unique version identifier** that is: + +- **Format**: `MAJOR.MINOR.PATCH` (e.g., `1.0.0`) +- **Git Tags**: Each release is tagged in Git with the format `v{version}` (e.g., `v1.0.0`) +- **Maven Central**: Published artifacts include the version identifier in their coordinates +- **Uniqueness**: Each version identifier is used exactly once and never reused + +The version identifier serves as a unique reference point for: +- Identifying specific releases +- Tracking changes between versions +- Reproducing builds +- Reporting bugs against specific versions + ### Prepare Release (version and tag) ```shell @@ -44,9 +72,11 @@ mvn -B release:prepare \ This will: - Remove `-SNAPSHOT` from current version -- Create a git tag +- **Create a Git tag** with the unique version identifier (format: `v{version}`, e.g., `v1.0.0`) - this identifies each release within the version control system - Update version to next development version +**Git Tags**: Each release is automatically tagged in Git using the format `v{version}`. These tags are pushed to the repository and can be viewed using `git tag -l` or on the [GitHub Releases](https://github.com/NGirchev/dotenv/releases) page. + #### 2. Switch to Release Tag ```shell @@ -177,13 +207,169 @@ Get your credentials from Central Portal: - [Central Portal](https://central.sonatype.com/) - [OpenSSF Security Scorecard](https://api.securityscorecards.dev/#/results/getResult) - Enter: `platform=github.com`, `org=NGirchev`, `repo=dotenv` -## Code Style +## Secure Development Knowledge + +This project follows secure development practices to ensure the security and safety of the software. Contributors should be familiar with secure coding principles and best practices. + +### Secure Coding Principles + +When contributing to this project, please follow these secure development practices: + +1. **Input Validation**: Always validate and sanitize inputs, especially when dealing with file paths and environment variables +2. **Error Handling**: Implement proper error handling without exposing sensitive information in error messages +3. **Least Privilege**: Follow the principle of least privilege - only request necessary permissions +4. **Defense in Depth**: Implement multiple layers of security controls +5. **Secure Defaults**: Use secure default configurations +6. **No Hardcoded Secrets**: Never commit secrets, passwords, API keys, or other sensitive information to the repository + +### Security Resources + +The following resources provide guidance on secure development practices: + +- **[OWASP Secure Coding Practices](https://owasp.org/www-project-secure-coding-practices-quick-reference-guide/)** - Comprehensive guide to secure coding practices +- **[OWASP Top 10](https://owasp.org/www-project-top-ten/)** - Most critical web application security risks +- **[CWE Top 25](https://cwe.mitre.org/top25/)** - Most dangerous software weaknesses +- **[OpenSSF Secure Software Development Fundamentals](https://openssf.org/curricula/)** - Free courses on secure software development +- **[Java Secure Coding Guidelines](https://www.oracle.com/java/technologies/javase/seccodeguide.html)** - Oracle's secure coding guidelines for Java + +### Security Considerations for This Project + +When working on this project, pay special attention to: + +- **File Path Security**: Validate file paths to prevent directory traversal attacks +- **Environment Variable Handling**: Ensure proper handling of environment variables without exposing sensitive data +- **System Property Security**: Be cautious when setting system properties that might affect other parts of the application +- **Logging Security**: Never log sensitive information (passwords, API keys, tokens) +- **Dependency Security**: Keep dependencies up to date and review security advisories + +### Security Review Process + +All code contributions are subject to security review. Maintainers will review: +- Potential security vulnerabilities +- Adherence to secure coding practices +- Proper handling of sensitive data +- Input validation and sanitization + +### Reporting Security Issues + +If you discover a security vulnerability in the codebase, **do not** open a public issue. Instead, follow the [Security Vulnerability Reporting](https://github.com/NGirchev/dotenv/blob/master/README.md#security-vulnerability-reporting) process outlined in the README. + +## Contribution Requirements + +### Code Style + +All contributions must follow these coding standards: + +- **Java Conventions**: Follow the [Oracle Java Code Conventions](https://www.oracle.com/java/technologies/javase/codeconventions-contents.html) and standard Java naming conventions +- **Language**: All code comments, JavaDoc, variable names, and commit messages must be in **English** +- **Naming**: Use meaningful variable and method names that clearly express their purpose +- **Comments**: Add JavaDoc comments for public methods and classes. Include comments for complex logic where necessary. All comments must be in English +- **Formatting**: Maintain consistent indentation (4 spaces) and formatting throughout the codebase +- **Testing**: Ensure all tests pass (`mvn test`). New features should include appropriate unit tests +- **Code Quality**: Write clean, readable, and maintainable code + +### Testing Policy + +**The project has a general policy that as major new functionality is added to the software, tests of that functionality MUST be added to the automated test suite.** -- Follow standard Java conventions -- Use meaningful variable and method names -- Add comments where necessary -- Ensure all tests pass +This policy applies to: +- New public methods and classes +- New features and functionality +- Bug fixes (regression tests) +- Edge cases and error handling + +**Evidence of adherence**: The project maintains comprehensive test coverage. For example, the `DotEnvLoader` class has corresponding tests in `DotEnvLoaderTest.java` that cover all major functionality including: +- Loading environment variables from files +- Handling comments, empty lines, and whitespace +- Error handling and edge cases +- Priority of System properties over environment variables + +When adding new functionality: +1. Write tests **before or alongside** the implementation (TDD approach is encouraged) +2. Ensure tests cover the happy path, edge cases, and error conditions +3. All tests must pass before submitting a Pull Request +4. Test coverage should be maintained or improved with each change + +### Compiler Warnings and Code Quality + +**The project enables compiler warning flags to look for code quality errors and common simple mistakes.** + +The project uses: +- **Java compiler warnings**: Enabled via `-Xlint:all` flag in Maven Compiler Plugin +- **Deprecation warnings**: Enabled to catch use of deprecated APIs +- **Treat warnings as errors**: Enabled via `failOnWarning=true` to ensure warnings are addressed + +**The project MUST address all compiler warnings.** Pull Requests with compiler warnings will not be accepted. + +**The project is maximally strict with warnings** - all warnings are treated as errors during the build process. This ensures: +- Code quality is maintained +- Common mistakes are caught early +- Deprecated APIs are avoided +- Best practices are followed + +To check for warnings locally: +```bash +mvn clean compile +``` + +All warnings must be resolved before submitting a Pull Request. + +### Static Code Analysis + +**The project uses static code analysis tools to detect potential bugs, security vulnerabilities, and code quality issues.** + +The project uses **[SpotBugs](https://spotbugs.github.io/)** (successor to FindBugs) for static code analysis. SpotBugs is: +- A FLOSS static analysis tool for Java +- Actively maintained and widely used +- Capable of detecting hundreds of bug patterns +- Integrated into the Maven build process + +**Static analysis is automatically run during the build process** and must pass before code can be merged. + +#### Running Static Analysis + +To run static code analysis locally: + +```bash +# Run SpotBugs analysis +mvn spotbugs:check + +# Generate HTML report +mvn spotbugs:gui +``` + +**All static analysis issues MUST be addressed** before submitting a Pull Request. The build will fail if SpotBugs finds any issues. + +#### Static Analysis Configuration + +- **Effort level**: Maximum (most thorough analysis) +- **Threshold**: Low (reports all issues, including minor ones) +- **Fail on error**: Enabled (build fails if issues are found) +- **Integration**: Runs automatically during `mvn compile` phase + +#### Common Issues to Address + +When SpotBugs reports issues, contributors should: +1. Review each reported issue +2. Fix legitimate problems +3. Suppress false positives with appropriate annotations if necessary +4. Document why suppression is needed + +For more information about SpotBugs, see the [SpotBugs documentation](https://spotbugs.github.io/). + +### Pull Request Requirements + +Before submitting a Pull Request, ensure: + +1. ✅ All tests pass locally (`mvn test`) +2. ✅ Code follows the style guidelines above +3. ✅ **New features include appropriate tests** (see [Testing Policy](#testing-policy)) +4. ✅ JavaDoc comments are added for public APIs +5. ✅ **No compilation warnings or errors** (warnings are treated as errors - see [Compiler Warnings](#compiler-warnings-and-code-quality)) +6. ✅ Commit messages are clear and descriptive ## Questions? -If you have any questions, please create an Issue on GitHub. +If you have any questions, please create an Issue on GitHub using the [GitHub Issues tracker](https://github.com/NGirchev/dotenv/issues). + +For bug reports and enhancement requests, see the [Reporting Issues and Suggesting Enhancements](https://github.com/NGirchev/dotenv/blob/master/README.md#reporting-issues-and-suggesting-enhancements) section in the README. diff --git a/README.md b/README.md index 195a318..6fd5967 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,10 @@ [![Maven Central](https://img.shields.io/maven-central/v/io.github.ngirchev/dotenv)](https://central.sonatype.com/namespace/io.github.ngirchev) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/ba880b66c6e848d7ac57505788a14d87)](https://app.codacy.com/gh/NGirchev/dotenv/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/11572/badge)](https://www.bestpractices.dev/projects/11572) +[![SonarCloud Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=NGirchev_dotenv&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=NGirchev_dotenv) +[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=NGirchev_dotenv&metric=coverage)](https://sonarcloud.io/summary/new_code?id=NGirchev_dotenv) -Simplest dotenv utility for Java applications. Load environment variables from `.env` files into System properties. +A simple Java library that helps you manage application configuration securely. Instead of hardcoding sensitive information like database passwords, API keys, or server addresses directly in your code, you can store them in a `.env` file. This keeps your secrets safe, prevents accidentally committing them to version control, and makes it easy to configure your application for different environments (development, testing, production). ## Features @@ -17,12 +19,23 @@ Simplest dotenv utility for Java applications. Load environment variables from ` ## Requirements -- Java 11 or higher -- Maven 3.6+ +**This project is buildable using only FLOSS (Free/Libre and Open Source Software) tools.** + +- **Java 11 or higher** (OpenJDK recommended - FLOSS) +- **Maven 3.6+** (Apache Maven - FLOSS) + +All build tools, dependencies, and test frameworks used are FLOSS. + +## Versioning + +This project uses **[Semantic Versioning](https://semver.org/)** (`MAJOR.MINOR.PATCH`, e.g. `1.0.0`). +Each release has a **unique version identifier**, is tagged in Git as `v{version}` (e.g. `v1.0.0`), and is published to Maven Central with the same version. +Development builds use the `-SNAPSHOT` suffix (e.g. `1.0.1-SNAPSHOT`) and are not intended for production use. +The current released version can be seen in the Maven Central badge above or on the GitHub Releases page. ## Installation -Add the dependency to your `pom.xml`: +The library is available on [Maven Central](https://central.sonatype.com/namespace/io.github.ngirchev). Add the dependency to your `pom.xml`: ```xml @@ -32,38 +45,62 @@ Add the dependency to your `pom.xml`: ``` -## Usage +For Gradle users, add to your `build.gradle`: + +```gradle +dependencies { + implementation 'io.github.ngirchev:dotenv:1.0.0' +} +``` + +After adding the dependency, rebuild your project to download the library from Maven Central. -### Basic Example +## Getting Started -1. Create a `.env` file in your project root: +### Quick Start Tutorial + +Follow these steps to get started with dotenv in your Java application: + +1. **Add the dependency** to your `pom.xml` or `build.gradle` (see Installation above) + +2. **Create a `.env` file** in your project root directory: ```env +# Database configuration DB_HOST=localhost DB_PORT=5432 -API_KEY=your-secret-key -DATABASE_URL=postgresql://localhost:5432/mydb +DB_NAME=mydatabase + +# API credentials +API_KEY=your-api-key-here ``` -2. Load the environment variables in your application: +3. **Load the environment variables** at the start of your application: ```java import io.github.ngirchev.dotenv.DotEnvLoader; -public class App { +public class MyApp { public static void main(String[] args) { - // Load from default .env file in project root + // Load .env file - call this before using any environment variables DotEnvLoader.loadDotEnv(); - - // Access variables + + // Now you can access the variables String dbHost = DotEnvLoader.getEnv("DB_HOST"); - String dbPort = DotEnvLoader.getEnv("DB_PORT"); - - System.out.println("Database: " + dbHost + ":" + dbPort); + String apiKey = DotEnvLoader.getEnv("API_KEY"); + + System.out.println("Connecting to database at: " + dbHost); + // Your application code here... } } ``` +4. **Run your application** as usual. The library will automatically load variables from the `.env` file. + +**Important**: Make sure to call `DotEnvLoader.loadDotEnv()` before accessing any environment variables, ideally at the very beginning of your `main` method or in a static initializer block. + +## Usage + ### Custom .env File Path ```java @@ -150,40 +187,127 @@ SECRET_TOKEN=abc123 ## API Reference -### `loadDotEnv()` +Public API is provided by a single class `io.github.ngirchev.dotenv.DotEnvLoader` with three static methods: -Loads environment variables from `.env` file in project root. +- `loadDotEnv()` – load variables from the default `.env` file in the current working directory. +- `loadDotEnv(Path envPath)` – load variables from the given `.env` file without overwriting existing System properties or environment variables. +- `getEnv(String key)` – read a value by key, first from System properties (loaded from `.env`), then from environment variables. -```java -DotEnvLoader.loadDotEnv(); -``` +For full JavaDoc (including parameter and exception details), see: -### `loadDotEnv(Path envPath)` +- Locally generated JavaDoc: `mvn javadoc:javadoc` → `target/site/apidocs/` +- JavaDoc JAR on Maven Central for this artifact -Loads environment variables from a specific `.env` file. +## Security Vulnerability Reporting -**Parameters:** -- `envPath` - path to `.env` file +### Vulnerability Report Process -**Example:** -```java -DotEnvLoader.loadDotEnv(Paths.get("config/.env")); -``` +**The project publishes the process for reporting security vulnerabilities on the project site.** -### `getEnv(String key)` +**Security Policy URL**: [https://github.com/NGirchev/dotenv/security/policy](https://github.com/NGirchev/dotenv/security/policy) -Gets environment variable value. First checks System properties (loaded from `.env`), then environment variables. +If you discover a security vulnerability, please report it responsibly. **Do not open a public GitHub issue** for security vulnerabilities. -**Parameters:** -- `key` - variable name +### How to Report Security Vulnerabilities -**Returns:** -- variable value or `null` if not found +**For Private Vulnerability Reports:** -**Example:** -```java -String apiKey = DotEnvLoader.getEnv("API_KEY"); -``` +This project supports **private vulnerability reporting** to allow security researchers to report vulnerabilities without making them public. + +To report a security vulnerability privately: + +1. Go to the [GitHub Security Advisories page](https://github.com/NGirchev/dotenv/security/advisories/new) +2. Click "Report a vulnerability" +3. Fill out the security advisory form with: + - Description of the vulnerability + - Steps to reproduce + - Potential impact + - Suggested fix (if any) +4. Submit the advisory + +**Alternative Method (Email):** + +If you prefer to report via email, you can contact the maintainer directly. However, GitHub Security Advisories is the preferred method as it provides better tracking and coordination. + +### Response Time + +**The project's initial response time for any vulnerability report received in the last 6 months is less than or equal to 14 days.** + +You will receive an acknowledgment of your report within 14 days, which may include: +- Confirmation that the vulnerability has been received +- Request for additional information if needed +- Initial assessment of the vulnerability +- Timeline for fix and disclosure (if applicable) + +### Disclosure Policy + +- Vulnerabilities will be addressed promptly +- A fix will be developed and tested before public disclosure +- Security advisories will be published when fixes are available +- Credit will be given to reporters (unless they prefer to remain anonymous) + +For more information, see GitHub's [Security Policy](https://github.com/NGirchev/dotenv/security/policy) page. + +## Security Best Practices + +When working with sensitive configuration data, follow these security guidelines: + +### ✅ DO: + +- **Add `.env` to `.gitignore`**: Never commit `.env` files containing secrets to version control. Add `.env` to your `.gitignore` file: + ``` + .env + .env.local + .env.*.local + ``` + +- **Use `.env.example` for templates**: Create a `.env.example` file with placeholder values (no real secrets) and commit it to help other developers: + ```env + DB_HOST=localhost + DB_PORT=5432 + API_KEY=your-api-key-here + ``` + +- **Set proper file permissions**: On Unix-like systems, restrict access to `.env` files: + ```bash + chmod 600 .env # Only owner can read/write + ``` + +- **Use environment variables in production**: For production deployments, prefer setting environment variables directly rather than using `.env` files, as they're more secure and easier to manage in containerized environments. + +- **Validate required variables**: Always check that required environment variables are present before using them: + ```java + String apiKey = DotEnvLoader.getEnv("API_KEY"); + if (apiKey == null || apiKey.isEmpty()) { + throw new IllegalStateException("API_KEY is required but not set"); + } + ``` + +### ❌ DON'T: + +- **Don't commit `.env` files**: Never commit files containing real secrets, passwords, or API keys to Git repositories. + +- **Don't share `.env` files**: Don't email, share via chat, or store `.env` files in insecure locations. + +- **Don't hardcode fallback secrets**: Avoid hardcoding default secrets in your code as fallbacks. + +- **Don't log sensitive values**: Be careful not to log environment variable values that contain secrets. + +- **Don't use `.env` for production secrets**: In production, use proper secret management systems (e.g., AWS Secrets Manager, HashiCorp Vault, Kubernetes Secrets) instead of `.env` files. + +For more information on secure configuration management, see [OWASP Secure Coding Practices](https://owasp.org/www-project-secure-coding-practices-quick-reference-guide/). + +### Secure Development Resources + +For contributors and developers working on this project, the following resources provide guidance on secure development practices: + +- **[OWASP Secure Coding Practices](https://owasp.org/www-project-secure-coding-practices-quick-reference-guide/)** - Comprehensive guide to secure coding practices +- **[OpenSSF Secure Software Development Fundamentals](https://openssf.org/curricula/)** - Free courses on secure software development +- **[Java Secure Coding Guidelines](https://www.oracle.com/java/technologies/javase/seccodeguide.html)** - Oracle's secure coding guidelines for Java +- **[CWE Top 25](https://cwe.mitre.org/top25/)** - Most dangerous software weaknesses +- **[OWASP Top 10](https://owasp.org/www-project-top-ten/)** - Most critical application security risks + +For detailed secure development guidelines for contributors, see the [Secure Development Knowledge](https://github.com/NGirchev/dotenv/blob/master/CONTRIBUTING.md#secure-development-knowledge) section in CONTRIBUTING.md. ## Behavior @@ -194,16 +318,164 @@ String apiKey = DotEnvLoader.getEnv("API_KEY"); ## Building +**This project is buildable using only FLOSS (Free/Libre and Open Source Software) tools.** + +The project uses: +- **Maven** (Apache Maven) - FLOSS build automation tool +- **Java** (OpenJDK) - FLOSS programming language and runtime +- **Maven Compiler Plugin** - FLOSS compiler plugin +- All build dependencies are FLOSS + +### Compiler Warnings + +**The project enables compiler warning flags to look for code quality errors and common simple mistakes.** + +The build configuration includes: +- **All compiler warnings enabled** (`-Xlint:all`) +- **Deprecation warnings enabled** +- **Warnings treated as errors** (`failOnWarning=true`) - the build fails if there are any warnings + +**The project addresses all compiler warnings** to maintain high code quality. This ensures that common mistakes are caught early and best practices are followed. + +### Static Code Analysis + +**The project uses static code analysis tools to detect potential bugs, security vulnerabilities, and code quality issues.** + +The project uses **[SpotBugs](https://spotbugs.github.io/)** for static code analysis. SpotBugs is: +- A FLOSS static analysis tool for Java +- Integrated into the Maven build process +- Automatically runs during compilation +- Detects hundreds of bug patterns including security vulnerabilities + +**Static analysis is automatically executed** during the build and must pass before code can be merged. The build will fail if SpotBugs finds any issues. + +To run static analysis manually: +```bash +mvn spotbugs:check +``` + +For more information, see the [Static Code Analysis](https://github.com/NGirchev/dotenv/blob/master/CONTRIBUTING.md#static-code-analysis) section in CONTRIBUTING.md. + +### Code Style Checking + +**The project uses [Checkstyle](https://checkstyle.sourceforge.io/) to enforce consistent code style.** + +Checkstyle is: +- A FLOSS development tool to help programmers write Java code that adheres to a coding standard +- Based on Google Java Style Guide +- Integrated into the Maven build process +- Automatically validates code style during the build + +**Code style validation is automatically executed** during the build and must pass before code can be merged. The build will fail if Checkstyle finds any style violations. + +To run Checkstyle manually: +```bash +mvn checkstyle:check +``` + +To generate a Checkstyle report: +```bash +mvn checkstyle:checkstyle +``` + +The report will be available at `target/site/checkstyle.html`. + +### SonarCloud Integration + +**The project uses [SonarCloud](https://sonarcloud.io/) for continuous code quality inspection.** + +SonarCloud provides: +- Automated code quality and security analysis +- Code coverage tracking +- Technical debt monitoring +- Quality gate enforcement + +The project is automatically analyzed on every push and pull request. View the analysis results and quality metrics on [SonarCloud](https://sonarcloud.io/summary/new_code?id=NGirchev_dotenv). + +To build the project: + ```bash mvn clean install ``` -## Running Tests +This will compile the source code (with strict warning checks), run tests, and package the library into a JAR file. The build will fail if there are any compiler warnings. + +## Testing + +### Automated Test Suite + +**This project uses an automated test suite that is publicly released as FLOSS.** + +The project uses **[JUnit 5](https://junit.org/junit5/)** (JUnit Jupiter) as the test framework, which is: +- Publicly released as FLOSS (licensed under the Eclipse Public License 2.0) +- Maintained as a separate FLOSS project +- Standard testing framework for Java applications + +The test suite includes comprehensive unit tests covering: +- Loading environment variables from `.env` files +- Handling comments, empty lines, and whitespace +- Error handling and edge cases +- Priority of System properties over environment variables +- Non-overwriting of existing properties + +### Running Tests + +**The test suite is invocable in a standard way for Java projects using Maven.** + +To run the automated test suite: ```bash mvn test ``` +This is the **standard Maven command** for running tests in Java projects. The command will: +1. Compile the source code +2. Compile the test code +3. Execute all tests using JUnit 5 +4. Display test results + +**Alternative ways to run tests:** + +```bash +# Run tests with verbose output +mvn test -X + +# Run a specific test class +mvn test -Dtest=DotEnvLoaderTest + +# Run tests and generate coverage report +mvn test jacoco:report +``` + +### Code Coverage + +**The project uses [JaCoCo](https://www.jacoco.org/jacoco/) for code coverage analysis.** + +JaCoCo is: +- A FLOSS Java code coverage library +- Integrated into the Maven build process +- Automatically generates coverage reports during testing +- Enforces minimum coverage thresholds to maintain code quality + +**Coverage requirements:** +- Minimum line coverage: 80% +- Minimum branch coverage: 70% + +Coverage reports are generated automatically during the build and can be viewed at `target/site/jacoco/index.html` after running `mvn test jacoco:report`. + +To check coverage thresholds: +```bash +mvn verify +``` + +The build will fail if coverage thresholds are not met. + +### Continuous Integration + +The test suite is automatically executed on every push and pull request via GitHub Actions CI pipeline (`.github/workflows/ci.yml`). The CI configuration is publicly available and uses FLOSS tools. + +**CI Pipeline URL**: [https://github.com/NGirchev/dotenv/actions](https://github.com/NGirchev/dotenv/actions) + ## Releasing ### Manual Release @@ -212,6 +484,7 @@ To create a release manually: ```bash # 1. Prepare release (version and tag) +# This creates a Git tag with format v{version} (e.g., v1.0.0) mvn -B release:prepare -Darguments="-DskipTests" # 2. Switch to release tag @@ -221,11 +494,14 @@ git checkout v1.0.0 mvn clean deploy -P release -DskipTests # 4. Push changes and tags +# This pushes the Git tag to the repository, making the release identifiable in version control git push origin master git push --tags ``` -**Note:** Do NOT use `release:perform`. Use `mvn clean deploy -P release` instead. +**Note:** +- Do NOT use `release:perform`. Use `mvn clean deploy -P release` instead. +- The `release:prepare` step automatically creates a Git tag with the format `v{version}` (e.g., `v1.0.0`) for each release, ensuring each release is identified within the version control system. ### GitHub Actions @@ -237,13 +513,101 @@ This project uses GitHub Actions for continuous integration: Releases are performed manually from the command line (see "Manual Release" section above). +### Development History + +This project maintains a complete development history in the public repository. **The repository includes interim versions for review between releases; it does NOT include only final releases.** + +All commits, branches, and Pull Requests between releases are publicly available for collaborative review. This enables: +- **Transparent code review**: Contributors and reviewers can see the evolution of changes before they are included in a final release +- **Collaborative development**: All intermediate commits are visible, allowing for feedback and discussion during development +- **Complete history**: The full development process is documented, not just release snapshots + +**Note**: The project may choose to omit specific interim versions from the public repository only in exceptional cases (e.g., versions that fix non-public security vulnerabilities that may never be publicly released, or include material that cannot be legally posted and are not in the final release). + ## License See [LICENSE](LICENSE) file for details. +## Reporting Issues and Suggesting Enhancements + +Found a bug or have an idea for improvement? We'd love to hear from you! + +**⚠️ Security Vulnerabilities**: If you discover a security vulnerability, please **do not** open a public issue. Instead, follow the [Security Vulnerability Reporting](#security-vulnerability-reporting) process to report it privately. + +### Bug Reporting Process + +**The project provides a process for users to submit bug reports using the GitHub Issues tracker.** + +**Issue Tracker URL**: [https://github.com/NGirchev/dotenv/issues](https://github.com/NGirchev/dotenv/issues) + +This project uses **GitHub Issues** as the issue tracker for tracking individual issues, bug reports, and enhancement requests. All issues are publicly accessible and searchable, providing a publicly available archive for reports and responses. + +### How to Report Bugs + +To submit a bug report: + +1. Go to the [GitHub Issues page](https://github.com/NGirchev/dotenv/issues) +2. Click "New Issue" +3. Select "Bug Report" template (if available) or create a new issue +4. Include the following information: + - **Description**: Clear description of the problem + - **Steps to Reproduce**: Detailed steps to reproduce the issue + - **Expected Behavior**: What you expected to happen + - **Actual Behavior**: What actually happened + - **Environment**: Java version, OS, library version, etc. + - **Code Example**: Minimal code example that demonstrates the issue (if applicable) + +**Language**: Please submit bug reports, feature requests, and comments in **English** to ensure they can be understood and addressed by the global developer community. + +### Enhancement Requests + +To suggest an enhancement or new feature: + +1. Go to the [GitHub Issues page](https://github.com/NGirchev/dotenv/issues) +2. Click "New Issue" +3. Select "Feature Request" template (if available) or create a new issue with the `enhancement` label +4. Describe the enhancement, its use case, and potential benefits + +### Response Policy + +- **Bug Reports**: The project acknowledges and responds to a majority of bug reports submitted in the last 2-12 months. Responses may include confirmation, requests for additional information, or status updates. A response does not necessarily mean the bug is fixed immediately, but that it has been reviewed and tracked. + +- **Enhancement Requests**: The project responds to a majority (>50%) of enhancement requests submitted in the last 2-12 months. Responses may include discussion, acceptance for future consideration, or explanation if the enhancement doesn't fit the project's scope. + +### Issue Archive + +**All bug reports, enhancement requests, and responses are publicly available and searchable** in the [GitHub Issues archive](https://github.com/NGirchev/dotenv/issues). This provides a complete history of: +- All reported bugs and their status +- Enhancement requests and discussions +- Responses from maintainers +- Resolution status and related commits + +You can search the issue archive using GitHub's search functionality to find similar issues, check if a bug has already been reported, or review past discussions. + ## Contributing -Contributions are welcome! Please feel free to submit a Pull Request. +Contributions are welcome! We appreciate your help in making this project better. + +### How to Contribute + +1. Fork the repository +2. Create a feature branch (`git checkout -b feature/your-feature-name`) +3. Make your changes +4. Run tests (`mvn test`) +5. Commit your changes (`git commit -am 'Add some feature'`) +6. Push to the branch (`git push origin feature/your-feature-name`) +7. Create a [Pull Request](https://github.com/NGirchev/dotenv/pulls) + +### Contribution Requirements + +All contributions must meet our requirements for acceptable contributions, including: + +- **Coding Standards**: Follow Java code conventions and maintain consistent style +- **Testing**: Ensure all tests pass and add tests for new features +- **Documentation**: Add JavaDoc comments for public APIs +- **Code Quality**: Write clean, readable, and maintainable code + +For detailed contribution requirements, coding standards, and guidelines, please see [CONTRIBUTING.md](CONTRIBUTING.md#contribution-requirements). ## Contributors diff --git a/checkstyle.xml b/checkstyle.xml index 1417f5f..b46f8ec 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -95,17 +95,13 @@ - + - - - - - - + + diff --git a/pom.xml b/pom.xml index 1107e7b..f9fa7d8 100644 --- a/pom.xml +++ b/pom.xml @@ -42,9 +42,20 @@ 3.0.0 3.3.0 3.2.4 + 4.8.6.0 + 0.8.11 + 3.3.1 + 10.12.5 + 3.21.0 + 3.12.1 + 2.16.2 UTF-8 UTF-8 + + + 0.80 + 0.70 @@ -74,6 +85,19 @@ org.apache.maven.plugins maven-compiler-plugin ${maven.compiler.plugin} + + 11 + UTF-8 + + + -Xlint:all + -Xlint:-processing + + true + true + + true + @@ -132,9 +156,227 @@ central + + + + com.github.spotbugs + spotbugs-maven-plugin + ${spotbugs.maven.plugin} + + Max + Low + true + + + + analyze-compile + compile + + check + + + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.maven.plugin} + + + prepare-agent + + prepare-agent + + + + report + test + + report + + + + check + verify + + check + + + + + PACKAGE + + + LINE + COVEREDRATIO + ${jacoco.min.line.coverage} + + + BRANCH + COVEREDRATIO + ${jacoco.min.branch.coverage} + + + + + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven.checkstyle.plugin} + + + com.puppycrawl.tools + checkstyle + ${checkstyle.version} + + + + checkstyle.xml + true + true + false + + + + validate + validate + + check + + + + + + + + org.apache.maven.plugins + maven-pmd-plugin + ${maven.pmd.plugin} + + + pmd-ruleset.xml + + true + true + + + + pmd-check + validate + + check + + + + + + + + org.codehaus.mojo + versions-maven-plugin + ${versions.maven.plugin} + + + + + + org.apache.maven.plugins + maven-site-plugin + ${maven.site.plugin} + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 3.9.0 + + + + dependencies + dependency-info + distribution-management + licenses + plugin-management + plugins + scm + summary + team + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + ${spotbugs.maven.plugin} + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.maven.plugin} + + + + report + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven.checkstyle.plugin} + + checkstyle.xml + + + + + org.apache.maven.plugins + maven-pmd-plugin + ${maven.pmd.plugin} + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven.javadoc.plugin} + + false + true + + + + + javadoc + javadoc-no-fork + + + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + ${maven.surefire.plugin} + + + + diff --git a/pom.xml.releaseBackup b/pom.xml.releaseBackup new file mode 100644 index 0000000..8ec197c --- /dev/null +++ b/pom.xml.releaseBackup @@ -0,0 +1,197 @@ + + + 4.0.0 + io.github.ngirchev + dotenv + 1.0.0-SNAPSHOT + + dotenv + Simplest dotenv utility for Java applications. Load environment variables from .env files into System properties. + https://github.com/NGirchev/dotenv + + + + MIT License + https://opensource.org/licenses/MIT + repo + + + + + + ngirchev + Nikolai Girchev + + + + + scm:git:https://github.com/NGirchev/dotenv.git + scm:git:git@github.com:NGirchev/dotenv.git + https://github.com/NGirchev/dotenv + HEAD + + + + 11 + 11 + + 3.11.0 + 3.11.0 + 3.2.1 + 3.5.0 + 3.0.0 + 3.3.0 + 3.2.4 + + UTF-8 + UTF-8 + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${maven.enforcer.plugin} + + + enforce-java + + enforce + + + + + 11 + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin} + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven.surefire.plugin} + + + + org.apache.maven.plugins + maven-source-plugin + ${maven.source.plugin} + + + attach-sources + + jar + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven.javadoc.plugin} + + + attach-javadocs + + jar + + + + + + + org.apache.maven.plugins + maven-release-plugin + 3.0.0 + + v@{project.version} + true + release + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.13 + true + + ossrh + https://oss.sonatype.org/ + + false + + + + + + + + + org.slf4j + slf4j-api + 1.7.36 + + + + + org.slf4j + slf4j-simple + 1.7.36 + + + + + org.junit.jupiter + junit-jupiter + 5.9.2 + test + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + release + + + + org.apache.maven.plugins + maven-gpg-plugin + ${maven.gpg.plugin} + + + sign-artifacts + verify + + sign + + + + + + + + + \ No newline at end of file diff --git a/release.properties b/release.properties new file mode 100644 index 0000000..7037854 --- /dev/null +++ b/release.properties @@ -0,0 +1,27 @@ +#release configuration +#Sun Dec 07 20:40:09 EET 2025 +completedPhase=end-release +exec.additionalArguments="-DskipTests" +exec.pomFileName=pom.xml +exec.snapshotReleasePluginAllowed=false +pinExternals=false +preparationGoals=clean verify +project.dev.io.github.ngirchev\:dotenv=1.0.1-SNAPSHOT +project.rel.io.github.ngirchev\:dotenv=1.0.0 +project.scm.io.github.ngirchev\:dotenv.connection=scm\:git\:https\://github.com/NGirchev/dotenv.git +project.scm.io.github.ngirchev\:dotenv.developerConnection=scm\:git\:git@github.com\:NGirchev/dotenv.git +project.scm.io.github.ngirchev\:dotenv.tag=HEAD +project.scm.io.github.ngirchev\:dotenv.url=https\://github.com/NGirchev/dotenv +projectVersionPolicyConfig=${projectVersionPolicyConfig}\n +projectVersionPolicyId=default +pushChanges=true +releaseStrategyId=default +remoteTagging=true +scm.branchCommitComment=@{prefix} prepare branch @{releaseLabel} +scm.commentPrefix=[maven-release-plugin] +scm.developmentCommitComment=@{prefix} prepare for next development iteration +scm.releaseCommitComment=@{prefix} prepare release @{releaseLabel} +scm.rollbackCommitComment=@{prefix} rollback the release of @{releaseLabel} +scm.tag=v1.0.0 +scm.tagNameFormat=v@{project.version} +scm.url=scm\:git\:git@github.com\:NGirchev/dotenv.git diff --git a/sonar-project.properties b/sonar-project.properties index 035b008..9c5e1e6 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -8,4 +8,7 @@ sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml sonar.junit.reportPaths=target/surefire-reports sonar.sourceEncoding=UTF-8 sonar.host.url=https://sonarcloud.io +sonar.language=java +sonar.java.source=11 +sonar.java.target=11 diff --git a/src/main/java/io/github/ngirchev/dotenv/DotEnvLoader.java b/src/main/java/io/github/ngirchev/dotenv/DotEnvLoader.java index b1d484b..4f9ad59 100644 --- a/src/main/java/io/github/ngirchev/dotenv/DotEnvLoader.java +++ b/src/main/java/io/github/ngirchev/dotenv/DotEnvLoader.java @@ -10,76 +10,182 @@ import java.util.stream.Stream; /** - * Utility class for loading environment variables from .env file + * Utility class for loading environment variables from .env files into Java System properties. + * + *

This class provides a simple way to manage application configuration by loading + * key-value pairs from a `.env` file into System properties. The loaded properties can + * then be accessed using {@link #getEnv(String)} or standard Java System property methods. + * + *

Key features: + *

    + *
  • Loads variables from `.env` files into System properties
  • + *
  • Does not overwrite existing System properties or environment variables
  • + *
  • Supports comments (lines starting with #)
  • + *
  • Automatically trims whitespace from keys and values
  • + *
  • Silently handles missing files and invalid lines
  • + *
+ * + *

Example usage: + *

{@code
+ * // Load from default .env file in project root
+ * DotEnvLoader.loadDotEnv();
+ * 
+ * // Access loaded variables
+ * String dbHost = DotEnvLoader.getEnv("DB_HOST");
+ * }
+ * + * @author NGirchev + * @since 1.0.0 */ -public class DotEnvLoader { +public final class DotEnvLoader { - private static final Logger log = LoggerFactory.getLogger(DotEnvLoader.class); + private static final Logger LOG = LoggerFactory.getLogger(DotEnvLoader.class); private DotEnvLoader() { } /** - * Loads environment variables from .env file into System properties. - * Does not overwrite existing values in System properties or environment variables. + * Loads environment variables from a specified .env file into System properties. + * + *

This method reads the `.env` file line by line and loads key-value pairs + * into System properties. The following rules apply: + *

    + *
  • Lines starting with '#' are treated as comments and ignored
  • + *
  • Empty lines are ignored
  • + *
  • Whitespace around keys and values is automatically trimmed
  • + *
  • Existing System properties and environment variables are never overwritten
  • + *
  • If the file doesn't exist, the method returns silently (logs debug message)
  • + *
  • Invalid lines (without '=' or with empty keys) are ignored
  • + *
+ * + *

Example .env file format: + *

{@code
+     * # Database configuration
+     * DB_HOST=localhost
+     * DB_PORT=5432
+     * API_KEY=your-secret-key
+     * }
+ * + *

Example usage: + *

{@code
+     * import java.nio.file.Paths;
+     * 
+     * // Load from custom path
+     * DotEnvLoader.loadDotEnv(Paths.get("config/.env"));
+     * }
* - * @param envPath path to .env file (default is ".env" in project root) + * @param envPath the path to the .env file to load. Must not be null. + * @throws NullPointerException if envPath is null + * @see #loadDotEnv() + * @see #getEnv */ - public static void loadDotEnv(Path envPath) { + public static void loadDotEnv(final Path envPath) { if (!Files.exists(envPath)) { - log.debug(".env file not found at {}, skipping dotenv loading", envPath); + if (LOG.isDebugEnabled()) { + LOG.debug(".env file not found at {}, skipping dotenv loading", envPath); + } return; } try (Stream lines = Files.lines(envPath)) { lines.map(String::trim) .filter(line -> !line.isEmpty()) - .filter(line -> !line.startsWith("#")) + .filter(line -> line.length() > 0 && line.charAt(0) != '#') .forEach(line -> { - int idx = line.indexOf('='); + final int idx = line.indexOf('='); if (idx <= 0) { return; } - String key = line.substring(0, idx).trim(); - String value = line.substring(idx + 1).trim(); + final String key = line.substring(0, idx).trim(); if (key.isEmpty()) { return; } + final String value = line.substring(idx + 1).trim(); + // Do not overwrite existing values if (System.getProperty(key) == null && System.getenv(key) == null) { System.setProperty(key, value); - log.debug("Loaded .env property: {}", key); + if (LOG.isDebugEnabled()) { + LOG.debug("Loaded .env property: {}", key); + } } }); - log.info(".env properties loaded into System properties from {}", envPath); + if (LOG.isInfoEnabled()) { + LOG.info(".env properties loaded into System properties from {}", envPath); + } } catch (IOException e) { - log.warn("Failed to load .env file from {}: {}. Skipping dotenv loading.", envPath, e.getMessage()); + if (LOG.isWarnEnabled()) { + LOG.warn("Failed to load .env file from {}: {}. Skipping dotenv loading.", envPath, e.getMessage()); + } } } /** - * Loads environment variables from .env file in project root. - * Convenient method for default usage. + * Loads environment variables from the default `.env` file in the project root directory. + * + *

This is a convenience method that calls {@link #loadDotEnv(Path)} with + * the path to `.env` in the current working directory (project root). + * + *

Example usage: + *


+     * public class MyApp {
+     *     public static void main(String[] args) {
+     *         // Load from default .env file
+     *         DotEnvLoader.loadDotEnv();
+     *         
+     *         // Use loaded variables
+     *         String apiKey = DotEnvLoader.getEnv("API_KEY");
+     *     }
+     * }
*/ public static void loadDotEnv() { loadDotEnv(Paths.get(".env")); } /** - * Gets environment variable value from System properties or environment variables. - * First checks System properties (loaded from .env), then environment variables. + * Gets an environment variable value from System properties or system environment variables. + * + *

This method checks for the variable in the following order: + *

    + *
  1. System properties (loaded from `.env` file via {@link #loadDotEnv()})
  2. + *
  3. System environment variables
  4. + *
+ * + *

If the variable is found in System properties, that value is returned. + * Otherwise, the method checks system environment variables. If the variable + * is not found in either location, {@code null} is returned. + * + *

Example usage: + *

{@code
+     * // Load .env file first
+     * DotEnvLoader.loadDotEnv();
+     * 
+     * // Get variable value
+     * String dbHost = DotEnvLoader.getEnv("DB_HOST");
+     * if (dbHost != null) {
+     *     System.out.println("Database host: " + dbHost);
+     * } else {
+     *     System.out.println("DB_HOST not set");
+     * }
+     * }
* - * @param key variable name - * @return variable value or null if not found + * @param key the name of the environment variable to retrieve. Must not be null. + * @return the value of the environment variable, or {@code null} if not found + * @throws NullPointerException if key is null + * @see System#getProperty(String) + * @see System#getenv(String) */ - public static String getEnv(String key) { - String value = System.getProperty(key); + public static String getEnv(final String key) { + final String value = System.getProperty(key); + final String result; if (value != null) { - return value; + result = value; + } else { + result = System.getenv(key); } - return System.getenv(key); + return result; } } diff --git a/src/site/markdown/index.md b/src/site/markdown/index.md new file mode 100644 index 0000000..feaf402 --- /dev/null +++ b/src/site/markdown/index.md @@ -0,0 +1,24 @@ +# dotenv + +Simplest dotenv utility for Java applications. Load environment variables from .env files into System properties. + +## Code Quality Reports + +The following code quality reports are available: + +* [SpotBugs](./spotbugs.html) - Static code analysis report +* [PMD](./pmd.html) - Code quality analysis report +* [Checkstyle](./checkstyle.html) - Code style checking report +* [CPD](./cpd.html) - Duplicate code detection report +* [JaCoCo](./jacoco/index.html) - Code coverage report +* [Surefire Report](./surefire-report.html) - Test results report +* [Javadoc](./apidocs/index.html) - API documentation + +For a complete list of reports, see [Project Reports](./project-reports.html). + +## Project Information + +* [Project Information](./project-info.html) - General project information +* [Dependencies](./dependencies.html) - Project dependencies +* [Licenses](./licenses.html) - Project licenses + diff --git a/src/site/site.xml b/src/site/site.xml new file mode 100644 index 0000000..9031767 --- /dev/null +++ b/src/site/site.xml @@ -0,0 +1,20 @@ + + + + org.apache.maven.skins + maven-default-skin + 1.3 + + + + + true + true + + + + From 34a5303d872090fb55c2e1c1278a84f67692ac31 Mon Sep 17 00:00:00 2001 From: ngirchev Date: Mon, 8 Dec 2025 22:57:40 +0200 Subject: [PATCH 3/3] Fixed --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3fbc7d0..59df0b9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,7 +38,7 @@ jobs: run: mvn -B -ntp spotbugs:check - name: SonarCloud Scan - uses: SonarSource/sonarcloud-github-action@master + uses: SonarSource/sonarcloud-github-action@ba3875ecf642b2129de2b589510c81a8b53dbf4e env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} @@ -47,7 +47,7 @@ jobs: projectBaseDir: . - name: Upload coverage reports - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@ab904c41d6ece82784817410c45d8b8c02684457 with: file: ./target/site/jacoco/jacoco.xml flags: unittests