diff --git a/.github/workflows/cloud-51did.yml b/.github/workflows/cloud-51did.yml index 70a4aca91..03f403171 100644 --- a/.github/workflows/cloud-51did.yml +++ b/.github/workflows/cloud-51did.yml @@ -54,12 +54,18 @@ jobs: with: # pipeline.did builds against the owid-java submodule source. submodules: recursive + # The tests run on Java 8, the oldest Java the packages support. Maven + # runs on JDK 17, the JDK every build compiles with, and compiles for + # Java 8 through the tree's release-8 profile. - uses: actions/setup-java@v4 + id: test-jdk with: - # The reactor targets 1.8, so the tests are compiled and run on a - # toolchain that can still produce it. distribution: temurin java-version: '8' + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' cache: maven - name: Cloud 51Did tests shell: pwsh @@ -102,8 +108,10 @@ jobs: 'repository.') } # Only the Pipeline API tree is built, as in its own repository. + $testJava = Join-Path '${{ steps.test-jdk.outputs.path }}' 'bin' 'java' mvn -B -f pipeline/pom.xml ` -pl pipeline.did,pipeline.cloudrequestengine -am test ` + "-Djvm=$testJava" ` '-Dtest=DidClientLiveTests,CloudRequestEngineLiveTests#build_Process_LicenseKeyAlone*' ` -DfailIfNoTests=false if ($LASTEXITCODE -ne 0) { exit 1 } diff --git a/.github/workflows/examples-fresh-clone.yml b/.github/workflows/examples-fresh-clone.yml index 1eb6ca652..483cb45b3 100644 --- a/.github/workflows/examples-fresh-clone.yml +++ b/.github/workflows/examples-fresh-clone.yml @@ -2,7 +2,8 @@ name: Examples from a fresh clone # Builds each product's console examples as AGENTS.md says, from a clone # with its submodules, against the packages published on Maven Central, with -# the JDK and Maven the runner has. Then runs the getting started example +# the Maven the runner has on JDK 17, which compiles for Java 8 with no +# warning. Then runs the getting started example # from the repository root with no settings. A fresh clone holds only a link # for each free data file. On Ubuntu the example downloads its file, which # tests the download, and the job keeps the file in the cache. The other @@ -52,6 +53,11 @@ jobs: submodules: recursive persist-credentials: false + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - name: The runner's Java and Maven shell: pwsh run: | @@ -126,6 +132,11 @@ jobs: enableCrossOsArchive: true fail-on-cache-miss: true + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - name: The runner's Java and Maven shell: pwsh run: | diff --git a/AGENTS.md b/AGENTS.md index 43183df91..3c11b718a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,9 +24,10 @@ the native engines from `cxx` and does need them, as the README says. ### Prerequisites - Git. -- A JDK, 8 or later. CI tests 8, 11, 17 and 21 (`ci/options.json`), and - builds and runs the examples on the JDK each runner has (see - [What CI tests](#pitfalls)). +- JDK 17. The examples compile for Java 8 and treat every compiler warning + as an error, and javac 21 and later warn that Java 8 is obsolete. CI + compiles with JDK 17 and runs the tests on JDK 8, 11, 17 and 21 + (`ci/options.json`, see [What CI tests](#pitfalls)). - Maven 3.8 or later, or the `mvnw` wrapper at the root. - Network access to GitHub, to Maven Central for the packages the examples use, and to `distributor.51degrees.com` for the data files. @@ -251,7 +252,7 @@ and for a list of properties that fails once or every time. when CI has them. Publish tests them against the packages it has just built (`ci/run-integration-tests.ps1`). [examples-fresh-clone.yml](.github/workflows/examples-fresh-clone.yml) - does what [Run the examples](#run-the-examples) says, with the JDK and + does what [Run the examples](#run-the-examples) says, with JDK 17 and the Maven each runner has. It builds the console examples against the published packages and runs each product's `GettingStartedOnPrem` jar from the repository root with no diff --git a/README.md b/README.md index 628d03b57..90f7deb35 100644 --- a/README.md +++ b/README.md @@ -72,9 +72,12 @@ longer includes them, because Git leaves a removed submodule's folder on disk. ## Building -You need a JDK (8 or later) and either Maven 3.8 or later or the `mvnw` -wrapper in this folder. The two on-premise engines compile their native -library during the build, which needs CMake 3.10 or later and a C++ toolchain: +You need JDK 17 and either Maven 3.8 or later or the `mvnw` wrapper in this +folder. The build compiles for Java 8 and treats every compiler warning as an +error, and javac 21 and later warn that Java 8 is obsolete, so JDK 17 is the +one to build with. The packages it makes run on Java 8 or later. The two +on-premise engines compile their native library during the build, which needs +CMake 3.10 or later and a C++ toolchain: Visual Studio with the C++ workload on Windows, GCC or Clang elsewhere. From this folder: diff --git a/ci/build-package-requirements.ps1 b/ci/build-package-requirements.ps1 index 5886a5d1a..27e508bd6 100644 --- a/ci/build-package-requirements.ps1 +++ b/ci/build-package-requirements.ps1 @@ -1,6 +1,9 @@ param( [Parameter(Mandatory)][string]$RepoName, - [string]$Name + [string]$Name, + # The runner variable naming the entry's JDK. The native modules and those + # they depend on compile with JDK 17 of the same architecture. + [Parameter(Mandatory)][string]$JavaSDKEnvVar ) $ErrorActionPreference = "Stop" $PSNativeCommandUseErrorActionPreference = $true @@ -13,7 +16,9 @@ Write-Host "Entering '$RepoName'" Push-Location $RepoName try { Write-Host "Building '$Name'" - mvn package @MavenOptions -DskipTests -pl ($NativePackages.Path -join ',') -am + Invoke-WithJavaHome (Get-CompileJavaHome $JavaSDKEnvVar) { + mvn package @MavenOptions -DskipTests -pl ($NativePackages.Path -join ',') -am + } } finally { Write-Host "Leaving '$RepoName'" Pop-Location diff --git a/ci/build-package.Tests.ps1 b/ci/build-package.Tests.ps1 index 897b30682..9c03fbef1 100644 --- a/ci/build-package.Tests.ps1 +++ b/ci/build-package.Tests.ps1 @@ -14,6 +14,15 @@ BeforeAll { Copy-Item -Recurse $PSScriptRoot (Join-Path $Root 'repo' 'ci') $Script = Join-Path $Root 'repo' 'ci' 'build-package.ps1' $Given = Join-Path $Root 'given.json' + $JavaHomeSeen = Join-Path $Root 'java-home.txt' + + # The JDK the runner has to compile with, under the name the runner gives + # it for its architecture. + $Arch = if ([Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -eq + [Runtime.InteropServices.Architecture]::Arm64) { 'arm64' } else { 'X64' } + $CompileJdkName = "JAVA_HOME_17_$Arch" + $CompileJdk = Join-Path $Root 'jdk-17' + [Environment]::SetEnvironmentVariable($CompileJdkName, $CompileJdk) Set-Content (Join-Path $Root 'steps' 'release-plan.ps1') ` 'function Get-ReleasePlan([string]$RepoPath) { }' @@ -29,6 +38,7 @@ param( [string[]]$VersionPaths = @('.') ) $PSBoundParameters | ConvertTo-Json | Set-Content (Join-Path $PWD 'given.json') +Set-Content (Join-Path $PWD 'java-home.txt') $env:JAVA_HOME $global:LASTEXITCODE = 0 '@ @@ -56,6 +66,7 @@ $global:LASTEXITCODE = 0 } AfterAll { + [Environment]::SetEnvironmentVariable($CompileJdkName, $null) Remove-Item -Recurse -Force $Root } @@ -88,4 +99,11 @@ Describe 'build-package.ps1' { '-DskipNativeBuild=true', '-pl', 'pipeline/pipeline.core') $given.VersionPaths | Should -BeNullOrEmpty } + + It 'builds on JDK 17 and puts JAVA_HOME back' { + $javaHome = $env:JAVA_HOME + Invoke-Build + (Get-Content $JavaHomeSeen) | Should -Be $CompileJdk + $env:JAVA_HOME | Should -Be $javaHome + } } diff --git a/ci/build-package.ps1 b/ci/build-package.ps1 index 0a72577c4..7d5c660c6 100644 --- a/ci/build-package.ps1 +++ b/ci/build-package.ps1 @@ -41,13 +41,16 @@ $modules = @($plan | ForEach-Object { Get-ModulePath $_ }) # common-ci deploys from the root to a local staging folder with signing, and # copies the result and the publishing bundle into the package folder. It reads # the signing keys from the environment of the job that signs. The versions are -# already set, so it is given no folder to set them in. -./java/build-package.ps1 ` - -RepoName $RepoName ` - -Name $Name ` - -Version $Version ` - -VersionPaths @() ` - -ExtraArgs "-DskipNativeBuild=true", "-pl", ($modules -join ',') +# already set, so it is given no folder to set them in. It compiles with the +# same JDK as every other build. +Invoke-WithJavaHome (Get-CompileJavaHome) { + ./java/build-package.ps1 ` + -RepoName $RepoName ` + -Name $Name ` + -Version $Version ` + -VersionPaths @() ` + -ExtraArgs "-DskipNativeBuild=true", "-pl", ($modules -join ',') +} $exitCode = $LASTEXITCODE # Maven Central limits each organisation's release size and file count in a diff --git a/ci/build-project.ps1 b/ci/build-project.ps1 index eea288f3f..cf7880232 100644 --- a/ci/build-project.ps1 +++ b/ci/build-project.ps1 @@ -1,13 +1,17 @@ param( [Parameter(Mandatory)][string]$RepoName, - [string]$Name + [string]$Name, + # The runner variable naming the entry's JDK. The build compiles with JDK + # 17 of the same architecture, whichever JDK the entry tests on. + [Parameter(Mandatory)][string]$JavaSDKEnvVar ) $ErrorActionPreference = "Stop" $PSNativeCommandUseErrorActionPreference = $true . "$PSScriptRoot/packages.ps1" -Write-Host "JAVA_HOME: $ENV:JAVA_HOME" +$compileJavaHome = Get-CompileJavaHome $JavaSDKEnvVar +Write-Host "Compiling with $compileJavaHome, testing with $ENV:JAVA_HOME" # A publish releases a package's dependents only when packages.json names # them, so a module or dependency it leaves out fails here, before the change @@ -24,7 +28,9 @@ if ($gaps.Count -gt 0) { Push-Location $RepoName try { Write-Host "Building $Name..." - mvn install @MavenOptions -DskipTests -Pdev + Invoke-WithJavaHome $compileJavaHome { + mvn install @MavenOptions -DskipTests -Pdev + } } finally { Pop-Location } diff --git a/ci/java-home.Tests.ps1 b/ci/java-home.Tests.ps1 new file mode 100644 index 000000000..33ccf8fb8 --- /dev/null +++ b/ci/java-home.Tests.ps1 @@ -0,0 +1,127 @@ +# Pester 5 tests of the helpers in packages.ps1 that make every Maven call +# that compiles run on JDK 17 while the tests run on the entry's own JDK, and +# a check that each script that compiles uses them. + +BeforeAll { + . (Join-Path $PSScriptRoot 'packages.ps1') + + # The runner variables are set by name here, as the runner sets them. + function Set-RunnerJdk([string]$Name, [string]$Value) { + [Environment]::SetEnvironmentVariable($Name, $Value) + } + $Arch = if ([Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -eq + [Runtime.InteropServices.Architecture]::Arm64) { 'arm64' } else { 'X64' } +} + +Describe 'Get-CompileJavaHome' { + BeforeEach { + Set-RunnerJdk 'JAVA_HOME_17_X64' '/jdk/17-x64' + Set-RunnerJdk 'JAVA_HOME_17_arm64' '/jdk/17-arm64' + } + AfterEach { + Set-RunnerJdk 'JAVA_HOME_17_X64' $null + Set-RunnerJdk 'JAVA_HOME_17_arm64' $null + } + + It 'gives JDK 17 for an entry on ' -ForEach @( + @{ Entry = 'JAVA_HOME_8_X64'; Expected = '/jdk/17-x64' } + @{ Entry = 'JAVA_HOME_11_X64'; Expected = '/jdk/17-x64' } + @{ Entry = 'JAVA_HOME_17_X64'; Expected = '/jdk/17-x64' } + @{ Entry = 'JAVA_HOME_21_X64'; Expected = '/jdk/17-x64' } + @{ Entry = 'JAVA_HOME_11_arm64'; Expected = '/jdk/17-arm64' } + @{ Entry = 'JAVA_HOME_21_arm64'; Expected = '/jdk/17-arm64' } + ) { + Get-CompileJavaHome $Entry | Should -Be $Expected + } + + It 'gives JDK 17 of the runner architecture with no entry' { + Get-CompileJavaHome | Should -Be "/jdk/17-$($Arch.ToLower())" + } + + It 'fails when the runner has no JDK 17' { + Set-RunnerJdk 'JAVA_HOME_17_X64' $null + { Get-CompileJavaHome 'JAVA_HOME_8_X64' } | + Should -Throw '*JAVA_HOME_17_X64 is not set*' + } + + It 'fails on a name that is not a runner JDK variable' { + { Get-CompileJavaHome 'JAVA_HOME' } | + Should -Throw "*'JAVA_HOME' is not a runner JDK variable*" + } +} + +Describe 'Invoke-WithJavaHome' { + It 'runs the block on the JDK given and puts JAVA_HOME and PATH back' { + $javaHome, $path = $env:JAVA_HOME, $env:PATH + $seen = Invoke-WithJavaHome '/jdk/17' { + $env:JAVA_HOME + ($env:PATH -split [IO.Path]::PathSeparator)[0] + } + $seen | Should -Be @('/jdk/17', (Join-Path '/jdk/17' 'bin')) + $env:JAVA_HOME | Should -Be $javaHome + $env:PATH | Should -Be $path + } + + It 'puts JAVA_HOME and PATH back when the block fails' { + $javaHome, $path = $env:JAVA_HOME, $env:PATH + { Invoke-WithJavaHome '/jdk/17' { throw 'failed' } } | Should -Throw 'failed' + $env:JAVA_HOME | Should -Be $javaHome + $env:PATH | Should -Be $path + } +} + +Describe 'Get-TestJvmArgument' { + It "gives Surefire the java of the entry's JDK" { + $javaHome = $env:JAVA_HOME + try { + $env:JAVA_HOME = '/jdk/8' + $java = Join-Path '/jdk/8' 'bin' "java$(if ($IsWindows) { '.exe' })" + Get-TestJvmArgument | Should -Be "-Djvm=$java" + } finally { + $env:JAVA_HOME = $javaHome + } + } +} + +# Every Maven call in a script that compiles is inside a block that runs it on +# the compile JDK, so a new call that compiles on the entry's JDK fails here. +Describe 'Scripts that compile' { + It ' runs every Maven call on the compile JDK' -ForEach @( + @{ Name = 'build-project.ps1' } + @{ Name = 'build-package-requirements.ps1' } + @{ Name = 'build-package.ps1' } + @{ Name = 'run-integration-tests.ps1' } + @{ Name = 'run-performance-tests.ps1' } + ) { + $path = Join-Path $PSScriptRoot $Name + $ast = [Management.Automation.Language.Parser]::ParseFile( + $path, [ref]$null, [ref]$null) + $calls = $ast.FindAll({ + param($node) + $node -is [Management.Automation.Language.CommandAst] -and + $node.GetCommandName() -in 'mvn', './java/build-package.ps1' + }, $true) + $calls.Count | Should -BeGreaterThan 0 + foreach ($call in $calls) { + $inside = $false + for ($node = $call.Parent; $node; $node = $node.Parent) { + if ($node -is [Management.Automation.Language.CommandAst] -and + $node.GetCommandName() -eq 'Invoke-WithJavaHome') { + $inside = $true + break + } + } + $inside | Should -BeTrue -Because "line $($call.Extent.StartLineNumber) of $Name runs Maven" + } + } + + It ' takes the entry JDK variable' -ForEach @( + @{ Name = 'build-project.ps1' } + @{ Name = 'build-package-requirements.ps1' } + @{ Name = 'run-integration-tests.ps1' } + @{ Name = 'run-performance-tests.ps1' } + ) { + (Get-Command (Join-Path $PSScriptRoot $Name)).Parameters.ContainsKey( + 'JavaSDKEnvVar') | Should -BeTrue + } +} diff --git a/ci/packages.ps1 b/ci/packages.ps1 index e3e153f2d..cca6f62cd 100644 --- a/ci/packages.ps1 +++ b/ci/packages.ps1 @@ -43,6 +43,54 @@ $Accessors = @( # Arguments every Maven call in these scripts passes. $MavenOptions = '--batch-mode', '--no-transfer-progress' +# Every Maven call that compiles runs on this JDK, which compiles for Java 8 +# through each tree's release-8 profile. The tests still run on each entry's +# own JDK. javac 21 warns that release 8 is obsolete, which -Werror makes an +# error, and javac 17 does not. +$CompileJdkVersion = 17 + +# The home of the JDK that compiles. The runner names each JDK it has in a +# variable such as JAVA_HOME_8_X64, so the one that compiles is found from the +# entry's variable with the version changed, for the same architecture. With +# no entry variable, as in the publish build, it is the runner's own +# architecture. +function Get-CompileJavaHome([string]$JavaSDKEnvVar) { + if (-not $JavaSDKEnvVar) { + $arm = [Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -eq + [Runtime.InteropServices.Architecture]::Arm64 + $JavaSDKEnvVar = "JAVA_HOME_$($CompileJdkVersion)_$(if ($arm) { 'arm64' } else { 'X64' })" + } + if ($JavaSDKEnvVar -notmatch '^JAVA_HOME_\d+_([A-Za-z0-9]+)$') { + throw "'$JavaSDKEnvVar' is not a runner JDK variable such as JAVA_HOME_8_X64." + } + $name = "JAVA_HOME_$($CompileJdkVersion)_$($Matches[1])" + $javaHome = [Environment]::GetEnvironmentVariable($name) + if (-not $javaHome) { + throw "$name is not set, so this runner has no JDK $CompileJdkVersion to compile with." + } + return $javaHome +} + +# Runs the script block with JAVA_HOME and PATH set to the JDK given, so Maven +# runs on it, and puts both back afterwards. +function Invoke-WithJavaHome([string]$JavaHome, [scriptblock]$Block) { + $saved = $env:JAVA_HOME, $env:PATH + $env:JAVA_HOME = $JavaHome + $env:PATH = "$(Join-Path $JavaHome 'bin')$([IO.Path]::PathSeparator)$env:PATH" + try { + & $Block + } finally { + $env:JAVA_HOME, $env:PATH = $saved + } +} + +# The Surefire argument that runs the tests on the entry's JDK, which +# setup-environment.ps1 made JAVA_HOME, when Maven runs on another to compile. +function Get-TestJvmArgument { + $java = Join-Path $env:JAVA_HOME 'bin' "java$(if ($IsWindows) { '.exe' })" + return "-Djvm=$java" +} + $PomNamespace = 'http://maven.apache.org/POM/4.0.0' # The packages in packages.json that are published, one per Maven module, diff --git a/ci/pmd-resource-ruleset.xml b/ci/pmd-resource-ruleset.xml index 5f99fad8e..b365f580f 100644 --- a/ci/pmd-resource-ruleset.xml +++ b/ci/pmd-resource-ruleset.xml @@ -18,11 +18,12 @@ - Every FlowData created is closed by a try-with-resources statement, - unless it is returned to the caller or kept in a field. + Every FlowData created is closed by a try-with-resources statement + or, held in a local variable, in a finally block of the same + method, unless it is returned to the caller or kept in a field. 3 @@ -34,6 +35,14 @@ [not(ancestor::Resource)] [not(parent::ReturnStatement)] [not(parent::AssignmentExpression)] + [not(parent::VariableDeclarator/VariableId[ + let $name := @Name, + $body := ancestor::*[self::MethodDeclaration + or self::ConstructorDeclaration + or self::Initializer + or self::LambdaExpression][1] + return $body//FinallyClause//MethodCall[@MethodName = 'close'] + /VariableAccess[@Name = $name]])] ]]> @@ -42,12 +51,13 @@ Every CloseableIterable a method returns, such as the profiles or the components of an engine, is closed by a try-with-resources - statement, unless it is returned to the caller. + statement or, held in a local variable, in a finally block of the + same method, unless it is returned to the caller. 3 @@ -57,6 +67,14 @@ //MethodCall[pmd-java:typeIs('fiftyone.pipeline.engines.fiftyone.data.CloseableIterable')] [not(ancestor::Resource)] [not(parent::ReturnStatement)] + [not(parent::VariableDeclarator/VariableId[ + let $name := @Name, + $body := ancestor::*[self::MethodDeclaration + or self::ConstructorDeclaration + or self::Initializer + or self::LambdaExpression][1] + return $body//FinallyClause//MethodCall[@MethodName = 'close'] + /VariableAccess[@Name = $name]])] ]]> diff --git a/ci/run-integration-tests.ps1 b/ci/run-integration-tests.ps1 index 120132cab..1df26bc51 100644 --- a/ci/run-integration-tests.ps1 +++ b/ci/run-integration-tests.ps1 @@ -10,7 +10,10 @@ param( [bool]$SeleniumContract = $true, # The branch of the shared Selenium contract tests to run, so a change # there can be tried here before it is merged. - [string]$SeleniumTestsRef = 'main' + [string]$SeleniumTestsRef = 'main', + # The runner variable naming the entry's JDK, which the tests run on. + # Maven compiles with JDK 17 of the same architecture. + [Parameter(Mandatory)][string]$JavaSDKEnvVar ) $ErrorActionPreference = "Stop" # Each part's exit code is checked below, so one failing part does not stop @@ -20,6 +23,8 @@ $PSNativeCommandUseErrorActionPreference = $false . "$PSScriptRoot/packages.ps1" $results = "$RepoName/test-results/integration" +$compileJavaHome = Get-CompileJavaHome $JavaSDKEnvVar +$testJvm = Get-TestJvmArgument $failed = @() # The examples take the libraries from Maven Central unless told otherwise. @@ -41,7 +46,9 @@ try { # The cloud engine example calls the live cloud service. Its test reads # the key from _51DEGREES_RESOURCE_KEY_BESPOKE and gives it to the example # as _51DEGREES_RESOURCE_KEY. - mvn test @MavenOptions -DfailIfNoTests=false "-Dsurefire.failIfNoSpecifiedTests=false" -Dtest=ExampleTests + Invoke-WithJavaHome $compileJavaHome { + mvn test @MavenOptions $testJvm -DfailIfNoTests=false "-Dsurefire.failIfNoSpecifiedTests=false" -Dtest=ExampleTests + } if ($LASTEXITCODE -ne 0) { $failed += 'pipeline developer examples' } } finally { Pop-Location @@ -59,7 +66,9 @@ if ($Version) { Write-Host "::group::$example against $($versionArgs -join ' ')" Push-Location "$RepoName/$example" try { - mvn clean test @MavenOptions @versionArgs + Invoke-WithJavaHome $compileJavaHome { + mvn clean test @MavenOptions $testJvm @versionArgs + } if ($LASTEXITCODE -ne 0) { $failed += $example } } finally { Pop-Location @@ -87,7 +96,9 @@ function Invoke-ContractTests { $example = $null Push-Location "$RepoName/examples/device-detection" try { - mvn @MavenOptions -pl $Module -am package -DskipTests @versionArgs + Invoke-WithJavaHome $compileJavaHome { + mvn @MavenOptions -pl $Module -am package -DskipTests @versionArgs + } if ($LASTEXITCODE -ne 0) { throw "Building the $Label web example failed." } $jar = (Get-ChildItem "$Module/target/*-jar-with-dependencies.jar" | Select-Object -First 1).FullName # The port the example listens on, under the name the shared suite diff --git a/ci/run-performance-tests.ps1 b/ci/run-performance-tests.ps1 index fed8408c3..9777f6d27 100644 --- a/ci/run-performance-tests.ps1 +++ b/ci/run-performance-tests.ps1 @@ -4,7 +4,10 @@ param( # Set by the publish workflow, which built and installed the packages, to # its label for the run. Not set when a pull request is tested, which # builds the reactor itself. - [string]$Version + [string]$Version, + # The runner variable naming the entry's JDK, which the tests run on. + # Maven compiles with JDK 17 of the same architecture. + [Parameter(Mandatory)][string]$JavaSDKEnvVar ) $ErrorActionPreference = "Stop" # Each product's exit code is checked below, so one failing product does not @@ -20,6 +23,8 @@ $PSNativeCommandUseErrorActionPreference = $false $summary = @{ HigherIsBetter = [ordered]@{}; LowerIsBetter = [ordered]@{} } $results = "$RepoName/test-results/performance" $failed = @() +$compileJavaHome = Get-CompileJavaHome $JavaSDKEnvVar +$testJvm = Get-TestJvmArgument # A publish measures the versions it built, each package's own. if ($Version) { @@ -35,8 +40,10 @@ $pipelineResults = Join-Path $PWD "pipeline-performance-$Name.json" Remove-Item -Path $pipelineResults -Force -ErrorAction SilentlyContinue Push-Location "$RepoName/pipeline" try { - mvn test @MavenOptions -DfailIfNoTests=false "-Dsurefire.failIfNoSpecifiedTests=false" ` - "-Dtest=*ShareUsageOverheadTests*" "-D_51DEGREES_PERFORMANCE_JSON=$pipelineResults" + Invoke-WithJavaHome $compileJavaHome { + mvn test @MavenOptions $testJvm -DfailIfNoTests=false "-Dsurefire.failIfNoSpecifiedTests=false" ` + "-Dtest=*ShareUsageOverheadTests*" "-D_51DEGREES_PERFORMANCE_JSON=$pipelineResults" + } if ($LASTEXITCODE -ne 0) { $failed += 'Pipeline API' } } finally { Pop-Location @@ -121,7 +128,9 @@ foreach ($benchmark in $benchmarks) { Write-Host "::group::$($benchmark.Product)" Push-Location "$RepoName/$($benchmark.Path)" try { - mvn clean test @MavenOptions @versionArgs -DfailIfNoTests=false "-Dsurefire.failIfNoSpecifiedTests=false" "-Dtest=*Performance*" + Invoke-WithJavaHome $compileJavaHome { + mvn clean test @MavenOptions $testJvm @versionArgs -DfailIfNoTests=false "-Dsurefire.failIfNoSpecifiedTests=false" "-Dtest=*Performance*" + } if ($LASTEXITCODE -ne 0) { $failed += $benchmark.Product } } finally { Pop-Location diff --git a/ci/run-unit-tests.ps1 b/ci/run-unit-tests.ps1 index ed067dfde..858a67e2f 100644 --- a/ci/run-unit-tests.ps1 +++ b/ci/run-unit-tests.ps1 @@ -9,16 +9,19 @@ param( $ErrorActionPreference = "Stop" # One run of every test in the reactor that build-project.ps1 built, the -# examples included. common-ci runs Surefire from the root, copies the reports -# of every module at any depth into test-results/unit, leaving out the example -# tests the integration tests report, and logs why a forked JVM died when one -# does. The dev profile points the examples at the reactor. The tests read -# their keys from the environment, each under its own _51DEGREES_ name. A test -# that needs every property reads _51DEGREES_RESOURCE_KEY_BESPOKE, and the -# Device Detection data file update example reads _51DEGREES_LICENSE_KEY. No -# secret fills _51DEGREES_RESOURCE_KEY, which is the name a person running an -# example sets. A test that runs an example gives the example its key under -# that name. A pull request at the standard depth leaves out the tests in +# examples included. build-project.ps1 compiled them with JDK 17, and Surefire +# runs them here with Maven on the entry's own JDK, which setup-environment.ps1 +# made JAVA_HOME, without compiling. common-ci runs Surefire from the root, +# copies the reports of every module at any depth into test-results/unit, +# leaving out the example tests the integration tests report, and logs why a +# forked JVM died when one does. The dev profile points the examples at the +# reactor. The tests read their keys from the environment, each under its own +# _51DEGREES_ name. A test that needs every property reads +# _51DEGREES_RESOURCE_KEY_BESPOKE, and the Device Detection data file update +# example reads _51DEGREES_LICENSE_KEY. No secret fills +# _51DEGREES_RESOURCE_KEY, which is the name a person running an example +# sets. A test that runs an example gives the example its key under that +# name. A pull request at the standard depth leaves out the tests in # standard-excludes.txt. $extraArgs = @( '-Pdev' diff --git a/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/DeviceDetectionCloudEngineBuilder.java b/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/DeviceDetectionCloudEngineBuilder.java index f54f1acf3..2a122f65b 100644 --- a/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/DeviceDetectionCloudEngineBuilder.java +++ b/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/DeviceDetectionCloudEngineBuilder.java @@ -61,6 +61,7 @@ protected DeviceDetectionCloudEngine newEngine(List properties) { /** * Build an engine using the current options. * @return new instance + * @throws Exception if the engine could not be created */ public DeviceDetectionCloudEngine build() throws Exception { return buildEngine(); diff --git a/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/HardwareProfileCloudEngine.java b/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/HardwareProfileCloudEngine.java index a961dcd68..ac26351db 100644 --- a/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/HardwareProfileCloudEngine.java +++ b/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/HardwareProfileCloudEngine.java @@ -32,13 +32,20 @@ import org.slf4j.Logger; /** - * Engine that takes the JSON response from the {@link CloudRequestEngine} and + * Engine that takes the JSON response from the + * {@link fiftyone.pipeline.cloudrequestengine.flowelements.CloudRequestEngine} and * uses it populate a {@link MultiDeviceDataCloud} instance for easier consumption. * @see Specification */ public class HardwareProfileCloudEngine extends PropertyKeyedCloudEngineBase { + /** + * Create a new instance. + * + * @param logger used for logging + * @param aspectDataFactory creates the element data this engine returns + */ public HardwareProfileCloudEngine( Logger logger, ElementDataFactory aspectDataFactory) { diff --git a/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/HardwareProfileCloudEngineBuilder.java b/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/HardwareProfileCloudEngineBuilder.java index 6b0f05472..9db810984 100644 --- a/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/HardwareProfileCloudEngineBuilder.java +++ b/device-detection/device-detection.cloud/src/main/java/fiftyone/devicedetection/cloud/flowelements/HardwareProfileCloudEngineBuilder.java @@ -35,16 +35,28 @@ import java.util.List; +/** Builder for the {@link HardwareProfileCloudEngine}. */ @ElementBuilder public class HardwareProfileCloudEngineBuilder extends AspectEngineBuilderBase< HardwareProfileCloudEngineBuilder, HardwareProfileCloudEngine> { private final ILoggerFactory loggerFactory; + /** + * Create a new builder. + * + * @param loggerFactory creates the loggers the engine uses + */ public HardwareProfileCloudEngineBuilder(ILoggerFactory loggerFactory) { this.loggerFactory = loggerFactory; } + /** + * Build an engine using the current options. + * + * @return a new engine + * @throws Exception if the engine could not be created + */ public HardwareProfileCloudEngine build() throws Exception { return buildEngine(); } diff --git a/device-detection/device-detection.hash.engine.on-premise/pom.xml b/device-detection/device-detection.hash.engine.on-premise/pom.xml index b855aab87..cb9040134 100644 --- a/device-detection/device-detection.hash.engine.on-premise/pom.xml +++ b/device-detection/device-detection.hash.engine.on-premise/pom.xml @@ -171,6 +171,19 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + + + + -Xdoclint/package:-fiftyone.devicedetection.hash.engine.onpremise.interop.swig + + + diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/Enums.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/Enums.java index f84711ddb..9c3a27328 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/Enums.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/Enums.java @@ -22,14 +22,23 @@ package fiftyone.devicedetection.hash.engine.onpremise; +/** Enumerations used by the on-premise engine. */ public class Enums { + /** Create a new instance. */ + public Enums() { + } + /** * Enumeration of possible match methods used by the Hash engine. */ public enum MatchMethods { + /** No hash nodes were matched. */ NONE, + /** Every match came from the performance graph. */ PERFORMANCE, + /** Matches came from both the performance and predictive graphs. */ COMBINED, + /** Every match came from the predictive graph. */ PREDICTIVE } } \ No newline at end of file diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ComponentMetaDataHash.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ComponentMetaDataHash.java index 63cfdbf6f..798e9e8cb 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ComponentMetaDataHash.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ComponentMetaDataHash.java @@ -111,6 +111,12 @@ public boolean equals(Object obj) { return super.equals(obj); } + /** + * Whether this component has the same id as another. + * + * @param other the component to compare with + * @return true if the ids are equal + */ public boolean equals(ComponentMetaData other) { return getComponentId() == other.getComponentId(); } diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/DeviceDataHash.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/DeviceDataHash.java index b058b3983..cc8ed96ac 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/DeviceDataHash.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/DeviceDataHash.java @@ -34,7 +34,7 @@ public interface DeviceDataHash extends DeviceData { /** - * Get the values for the specified property as a List<>. For + * Get the values for the specified property as a {@code List}. For * on-premise engines, this is the raw form they are stored in the data file * as. * @param propertyName name of the property to get values for diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ProfileMetaDataHash.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ProfileMetaDataHash.java index afadcd5b2..c6bd33c53 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ProfileMetaDataHash.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ProfileMetaDataHash.java @@ -165,6 +165,12 @@ public boolean equals(Object obj) { return super.equals(obj); } + /** + * Whether this profile has the same id as another. + * + * @param other the profile to compare with + * @return true if the ids are equal + */ public boolean equals(ProfileMetaData other) { return getProfileId() == other.getProfileId(); } diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/PropertyMetaDataHash.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/PropertyMetaDataHash.java index 6a6b5a92a..a0e58425e 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/PropertyMetaDataHash.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/PropertyMetaDataHash.java @@ -236,10 +236,22 @@ public boolean equals(Object obj) { return super.equals(obj); } + /** + * Whether this property has the same name as another. + * + * @param other the property to compare with + * @return true if the names are equal + */ public boolean equals(FiftyOneAspectPropertyMetaData other) { return getName().equals(other.getName()); } + /** + * Whether this property has the given name. + * + * @param other the name to compare with + * @return true if the names are equal + */ public boolean equals(String other) { return getName().equals(other); } diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ValueMetaDataHash.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ValueMetaDataHash.java index 375e91b35..f3440651b 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ValueMetaDataHash.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/data/ValueMetaDataHash.java @@ -86,6 +86,12 @@ public boolean equals(Object obj) { return super.equals(obj); } + /** + * Whether this value has the same property and name as another. + * + * @param other the value to compare with + * @return true if both are equal + */ public boolean equals(ValueMetaData other) { return getProperty().equals(other.getProperty()) && getName().equals(other.getName()); diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/Constants.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/Constants.java index 39734c8cd..ccdf5d8f7 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/Constants.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/Constants.java @@ -22,39 +22,63 @@ package fiftyone.devicedetection.hash.engine.onpremise.flowelements; +/** Constants used by the Hash engine. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } + + /** Names and descriptions of the match metric properties. */ public static class MatchMetrics { - /* Category */ + /** Create a new instance. */ + public MatchMetrics() { + } + + /** Category of the match metric properties. */ public static final String CATEGORY = "Device Metrics"; - /* Component */ + /** Component the match metric properties belong to. */ public static final String COMPONENT = "Metrics"; /* Names */ + /** Name of the matched nodes property. */ public static final String MATCHED_NODES = "MatchedNodes"; + /** Name of the difference property. */ public static final String DIFFERENCE = "Difference"; + /** Name of the drift property. */ public static final String DRIFT = "Drift"; + /** Name of the device id property. */ public static final String DEVICE_ID = "DeviceId"; + /** Name of the matched User-Agents property. */ public static final String USER_AGENTS = "UserAgents"; + /** Name of the match method property. */ public static final String METHOD = "Method"; + /** Name of the iterations property. */ public static final String ITERATIONS = "Iterations"; /* Match metric properties description */ + /** Description of the matched nodes property. */ public static final String MATCHED_NODES_DESCRIPTION = "Indicates the number of " + "hash nodes matched within the evidence."; + /** Description of the difference property. */ public static final String DIFFERENCE_DESCRIPTION = "Used when detection method " + "is not Exact or None. This is an integer value and the larger the " + "value the less confident the detector is in this result."; + /** Description of the drift property. */ public static final String DRIFT_DESCRIPTION = "Total difference in character " + "positions where the substrings hashes were found away from where " + "they were expected."; + /** Description of the device id property. */ public static final String DEVICE_ID_DESCRIPTION = "Consists of four components " + "separated by a hyphen symbol: Hardware-Platform-Browser-IsCrawler " + "where each Component represents an ID of the corresponding Profile."; + /** Description of the matched User-Agents property. */ public static final String USER_AGENTS_DESCRIPTION = "The matched User-Agents."; + /** Description of the match method property. */ public static final String METHOD_DESCRIPTION = "Provides information about " + "the algorithm that was used to perform detection for a particular " + "User-Agent."; + /** Description of the iterations property. */ public static final String ITERATIONS_DESCRIPTION = "The number of iterations " + "carried out in order to find a match. This is the number of nodes " + "in the graph which have been visited."; diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/DeviceDetectionHashEngineBuilder.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/DeviceDetectionHashEngineBuilder.java index 0e6f98760..edb0a8644 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/DeviceDetectionHashEngineBuilder.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/DeviceDetectionHashEngineBuilder.java @@ -187,7 +187,8 @@ public DeviceDetectionHashEngineBuilder setPerformanceProfile( /** * Provide a hint as to how many threads will access the pipeline simultaneously *

- * Default is the result of {@link Runtime#getRuntime()#getAvailableProcessors()} + * Default is the result of + * {@code Runtime.getRuntime().availableProcessors()} * @see Concurrent processing * @param concurrency expected concurrent accesses * @return this builder diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ComponentIterable.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ComponentIterable.java index 77d748d2a..54b1d6e04 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ComponentIterable.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ComponentIterable.java @@ -89,7 +89,7 @@ protected ComponentMetaData get(long index) { } @Override - public void close() throws Exception { + public void close() { collection.delete(); } } diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/Constants.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/Constants.java index 1fa22d3ef..600287896 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/Constants.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/Constants.java @@ -22,7 +22,12 @@ package fiftyone.devicedetection.hash.engine.onpremise.interop; +/** Messages used when the native library cannot be loaded. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } + private static final String USE_PACKAGE_MANAGER = "use your Linux " + "package manager to install it on your system. If this is not " + diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ProfileIterable.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ProfileIterable.java index a169697e9..15977e8e9 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ProfileIterable.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ProfileIterable.java @@ -58,7 +58,7 @@ protected ProfileMetaData get(long index) { } @Override - public void close() throws Exception { + public void close() { collection.delete(); } } \ No newline at end of file diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/PropertyIterable.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/PropertyIterable.java index ca76f16d8..922482649 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/PropertyIterable.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/PropertyIterable.java @@ -44,6 +44,7 @@ public class PropertyIterable /** * Create a new instance. * @param engine the engine which the meta data relates to + * @param list holds the properties once they have been read * @param collection the native collection of properties */ public PropertyIterable( @@ -61,7 +62,7 @@ protected FiftyOneAspectPropertyMetaData get(long index) { } @Override - public void close() throws Exception { + public void close() { collection.delete(); } } \ No newline at end of file diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/Swig.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/Swig.java index 7e38a5515..a4e7bd8f4 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/Swig.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/Swig.java @@ -34,6 +34,10 @@ * Static methods to help interoperability through the SWIG layer to C++. */ public class Swig { + /** Create a new instance. */ + public Swig() { + } + /** * Copy the values in the native string vector to a {@link List}. * @param vector native instance to copy diff --git a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ValueIterable.java b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ValueIterable.java index d58ee8e38..72e7e52d1 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ValueIterable.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/main/java/fiftyone/devicedetection/hash/engine/onpremise/interop/ValueIterable.java @@ -58,7 +58,7 @@ protected ValueMetaData get(long index) { } @Override - public void close() throws Exception { + public void close() { collection.delete(); } } \ No newline at end of file diff --git a/device-detection/device-detection.hash.engine.on-premise/src/test/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/DeviceDataTests.java b/device-detection/device-detection.hash.engine.on-premise/src/test/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/DeviceDataTests.java index 64dc19f0f..b3e9e7e46 100644 --- a/device-detection/device-detection.hash.engine.on-premise/src/test/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/DeviceDataTests.java +++ b/device-detection/device-detection.hash.engine.on-premise/src/test/java/fiftyone/devicedetection/hash/engine/onpremise/flowelements/DeviceDataTests.java @@ -71,6 +71,7 @@ public void cleanup() { */ @Test public void DeviceData_ResultsClose() throws Exception { + ResultsHashSwig results = mock(ResultsHashSwig.class); try (FlowData flowData = getWrapper().getPipeline().createFlowData()) { DeviceDataHashDefault data = new DeviceDataHashDefault( logger, @@ -78,14 +79,12 @@ public void DeviceData_ResultsClose() throws Exception { getWrapper().getEngine(), missingPropertyService); - ResultsHashSwig results = mock(ResultsHashSwig.class); data.setResults(results); flowData.getOrAdd( getWrapper().getEngine().getTypedDataKey(), arg -> data); - flowData.close(); - verify(results, times(1)).close(); } + verify(results, times(1)).close(); } /** diff --git a/device-detection/device-detection.shared/pom.xml b/device-detection/device-detection.shared/pom.xml index 7d2618c67..d8616ce70 100644 --- a/device-detection/device-detection.shared/pom.xml +++ b/device-detection/device-detection.shared/pom.xml @@ -56,6 +56,18 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + + + all,-missing + + diff --git a/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/Constants.java b/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/Constants.java index 012f1d24a..ea0a9a35e 100644 --- a/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/Constants.java +++ b/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/Constants.java @@ -25,6 +25,7 @@ import static fiftyone.pipeline.core.Constants.EVIDENCE_QUERY_PREFIX; import static fiftyone.pipeline.core.Constants.EVIDENCE_SEPERATOR; +/** Evidence keys and other constants shared by the device detection engines. */ public class Constants { /** diff --git a/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/DeviceDataBaseOnPremise.java b/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/DeviceDataBaseOnPremise.java index ac69c3bf2..08ce264af 100644 --- a/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/DeviceDataBaseOnPremise.java +++ b/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/DeviceDataBaseOnPremise.java @@ -53,6 +53,10 @@ public abstract class DeviceDataBaseOnPremise extends DeviceDataBase implements ProvidesValuesAsString { + /** + * Maps each primitive type to its boxed type, used when converting native + * values. + */ protected final Map, Class> primitiveTypes; private final Object dataLock = new Object(); private final Object getLock = new Object(); diff --git a/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/testhelpers/FileUtils.java b/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/testhelpers/FileUtils.java index 9f8ca6e8f..a9dd9d453 100644 --- a/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/testhelpers/FileUtils.java +++ b/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/testhelpers/FileUtils.java @@ -46,18 +46,25 @@ @Deprecated @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public class FileUtils { + /** Name of the Enterprise data file. */ public static final String ENTERPRISE_HASH_DATA_FILE_NAME = "Enterprise-HashV41.hash"; + /** Name of the TAC data file. */ public static final String TAC_HASH_DATA_FILE_NAME = "TAC-HashV41.hash"; + /** Name of the free Lite data file. */ public static final String LITE_HASH_DATA_FILE_NAME = "51Degrees-LiteV4.1.hash"; private static Optional HASH_DATA_FILE; + /** Name of the evidence file the tests use. */ public static final String EVIDENCE_FILE_NAME = "20000 Evidence Records.yml"; private static Optional EVIDENCE_FILE; - // Where each free file is in the data repository. A search for the path - // rather than the name does not stop at another file of the same name, - // such as a Git LFS pointer in an old device-detection-data folder. + /** + * Path of the Lite data file in the data repository. A search for the + * path rather than the name does not stop at another file of the same + * name, such as a Git LFS pointer in an old device-detection-data folder. + */ public static final String LITE_HASH_DATA_FILE_PATH = "device-detection/" + LITE_HASH_DATA_FILE_NAME; + /** Path of the evidence file in the data repository. */ public static final String EVIDENCE_FILE_PATH = "device-detection/" + EVIDENCE_FILE_NAME; @@ -101,6 +108,12 @@ public static File getHashFile() { } } + /** + * Find the evidence file the tests use, searching once and keeping the + * result. + * + * @return the file, or null if it was not found + */ public static File getEvidenceFile() { if (Objects.nonNull(EVIDENCE_FILE)) { return EVIDENCE_FILE.orElse(null); diff --git a/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/testhelpers/KeyUtils.java b/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/testhelpers/KeyUtils.java index a3a39516b..a432a3494 100644 --- a/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/testhelpers/KeyUtils.java +++ b/device-detection/device-detection.shared/src/main/java/fiftyone/devicedetection/shared/testhelpers/KeyUtils.java @@ -38,6 +38,8 @@ public class KeyUtils { /** * Obtain a key from the environment variable of the name given, or * from the system property of the same name when that is not set. + * @param keyName name of the environment variable and system property + * @return the key, or null when neither is set */ public static String getNamedKey(String keyName) { return getNamedKey(keyName, System::getenv); diff --git a/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionCloudPipelineBuilder.java b/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionCloudPipelineBuilder.java index a063a588d..a81589efc 100644 --- a/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionCloudPipelineBuilder.java +++ b/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionCloudPipelineBuilder.java @@ -45,8 +45,9 @@ public class DeviceDetectionCloudPipelineBuilder * Internal Constructor. * This builder should only be created through the * DeviceDetectionPipelineBuilder - * @param loggerFactory - * @param httpClient + * @param loggerFactory creates the loggers for the Pipeline and its + * elements + * @param httpClient used to make requests to the cloud service */ public DeviceDetectionCloudPipelineBuilder( ILoggerFactory loggerFactory, @@ -60,7 +61,7 @@ public DeviceDetectionCloudPipelineBuilder( * @return A new pipeline instance that contains a cloud request engine for * making requests to the 51Degrees cloud service and a * DeviceDetectionCloudEngine to interpret the device detection results. - * @throws Exception + * @throws Exception if the Pipeline could not be built */ @Override public Pipeline build() throws Exception { diff --git a/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionOnPremisePipelineBuilder.java b/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionOnPremisePipelineBuilder.java index f38644676..df5e6b3b2 100644 --- a/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionOnPremisePipelineBuilder.java +++ b/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionOnPremisePipelineBuilder.java @@ -50,6 +50,7 @@ public class DeviceDetectionOnPremisePipelineBuilder extends PrePackagedPipelineBuilderBase { + /** Whether the Pipeline shares usage data with 51Degrees. */ protected boolean shareUsageEnabled = fiftyone.pipeline.engines.fiftyone.flowelements.Constants .SHARE_USAGE_DEFAULT_ENABLED; diff --git a/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionPipelineBuilder.java b/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionPipelineBuilder.java index 6e025c28b..09f75f17c 100644 --- a/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionPipelineBuilder.java +++ b/device-detection/device-detection/src/main/java/fiftyone/devicedetection/DeviceDetectionPipelineBuilder.java @@ -34,6 +34,7 @@ */ public class DeviceDetectionPipelineBuilder { + /** Creates the loggers for the Pipeline and its elements. */ protected final ILoggerFactory loggerFactory; private final DataUpdateService dataUpdateService; private final HttpClient httpClient; @@ -145,7 +146,7 @@ public DeviceDetectionOnPremisePipelineBuilder useOnPremise( /** * Use the 51Degrees Cloud service to perform device detection. * @param resourceKey The resource key to use when querying the cloud service. - * Obtain one from https://51degrees.com/configure?utm_source=code&utm_medium=comment&utm_campaign=51degrees-java&utm_content=device-detection-src-main-java-fiftyone-devicedetection-devicedetectionpipelinebuilder.java&utm_term=usecloud + * Obtain one from 51degrees.com/configure * @return A builder that can be used to configure and build a pipeline * that will use the cloud device detection engine. */ diff --git a/device-detection/device-detection/src/main/java/fiftyone/devicedetection/Enums.java b/device-detection/device-detection/src/main/java/fiftyone/devicedetection/Enums.java index a1773f9d2..a3d73c083 100644 --- a/device-detection/device-detection/src/main/java/fiftyone/devicedetection/Enums.java +++ b/device-detection/device-detection/src/main/java/fiftyone/devicedetection/Enums.java @@ -27,8 +27,15 @@ */ @Deprecated public class Enums { + /** Create a new instance. */ + public Enums() { + } + + /** The detection algorithms an engine can use. */ public enum DeviceDetectionAlgorithm { + /** The Hash algorithm. */ Hash, + /** The Pattern algorithm, which is no longer available. */ Pattern } } diff --git a/device-detection/device-detection/src/test/java/fiftyone/devicedetection/DeviceDetectionOnPremisePipelineBuilderTest.java b/device-detection/device-detection/src/test/java/fiftyone/devicedetection/DeviceDetectionOnPremisePipelineBuilderTest.java index 75f38b64d..7a6e934e6 100644 --- a/device-detection/device-detection/src/test/java/fiftyone/devicedetection/DeviceDetectionOnPremisePipelineBuilderTest.java +++ b/device-detection/device-detection/src/test/java/fiftyone/devicedetection/DeviceDetectionOnPremisePipelineBuilderTest.java @@ -216,13 +216,13 @@ public void setDataFileSystemWatcher_PropertyPropagatedToDataFileConfiguration() @Test public void setDataUpdateService_RegisterDataFileTriggered() throws Exception { DataUpdateServiceDefault dataUpdateServiceDefault = mock(DataUpdateServiceDefault.class); - try (Pipeline ignored = builder - .setAutoUpdate(true) - .setDataUpdateLicenseKey("licence_key") - .setDataUpdateService(dataUpdateServiceDefault) - .build()) { - verify(dataUpdateServiceDefault).registerDataFile(any()); - } + builder + .setAutoUpdate(true) + .setDataUpdateLicenseKey("licence_key") + .setDataUpdateService(dataUpdateServiceDefault) + .build() + .close(); + verify(dataUpdateServiceDefault).registerDataFile(any()); } @Test diff --git a/device-detection/pom.xml b/device-detection/pom.xml index 645d7df65..92687944d 100644 --- a/device-detection/pom.xml +++ b/device-detection/pom.xml @@ -136,7 +136,7 @@ ${maven.compiler.target} true - -Xlint:all,-try,-options + -Xlint:all -Werror @@ -234,8 +234,11 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - none - true + + all + true false @@ -376,4 +379,21 @@ scm:git:https://github.com/51Degrees/51degrees-java.git scm:git:https://github.com/51Degrees/51degrees-java.git + + + + + release-8 + + [9,) + + + 8 + + + diff --git a/examples/device-detection/README.md b/examples/device-detection/README.md index d5537424a..782d6cccc 100644 --- a/examples/device-detection/README.md +++ b/examples/device-detection/README.md @@ -99,6 +99,11 @@ The tables below describe the examples available in this repository. ## Running built examples from command line +Build the examples with JDK 17. They compile for Java 8 and treat every +compiler warning as an error, and javac 21 and later warn that Java 8 is +obsolete, so the build fails on JDK 21 and later. The JARs it makes run on +Java 8 or later. + Running ```bash diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedCloud.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedCloud.java index fa8884129..9cad8b3c4 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedCloud.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedCloud.java @@ -107,10 +107,11 @@ public static void run(String resourceKey, For more information about pipelines in general see the documentation at https://51degrees.com/documentation/_pipeline_api__concepts__configuration__builders__index.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=console-src-main-java-fiftyone-devicedetection-examples-console-gettingstartedcloud.java&utm_term=run - Note that we wrap the creation of a pipeline in a try/resources to control its lifecycle */ - try (Pipeline pipeline = new DeviceDetectionPipelineBuilder() + Note that we close the pipeline in a finally block to control its lifecycle */ + Pipeline pipeline = new DeviceDetectionPipelineBuilder() .useCloud(resourceKey) - .build()) { + .build(); + try { // carry out some sample detections @@ -119,6 +120,8 @@ public static void run(String resourceKey, } logger.info("All done"); + } finally { + pipeline.close(); } } @@ -138,9 +141,10 @@ private static void analyzeEvidence(Map evidence, detection is called "evidence" and usually consists of a number of HTTP Header field values, in this case represented by a Map of header name/value entries. - FlowData is wrapped in a try/resources block in order to ensure that the unmanaged + FlowData is closed in a finally block in order to ensure that the unmanaged resources allocated by the native device detection library are freed */ - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // list the evidence writer.println("Input values:"); @@ -169,6 +173,8 @@ private static void analyzeEvidence(Map evidence, writer.println("\tPlatform Version: " + asString(device.getPlatformVersion())); writer.println("\tBrowser Name: " + asString(device.getBrowserName())); writer.println("\tBrowser Version: " + asString(device.getBrowserVersion())); + } finally { + data.close(); } writer.println(); writer.flush(); diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedOnPrem.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedOnPrem.java index 4f5565d1c..65d889015 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedOnPrem.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/GettingStartedOnPrem.java @@ -120,7 +120,7 @@ public static void run(String dataFile, For more information about pipelines in general see the documentation at https://51degrees.com/documentation/_pipeline_api__concepts__configuration__builders__index.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=console-src-main-java-fiftyone-devicedetection-examples-console-gettingstartedonprem.java&utm_term=run - Note that we wrap the creation of a pipeline in a try/resources to control its lifecycle */ + Note that we close the pipeline in a finally block to control its lifecycle */ // the configuration file is in the resources directory File optionsFile = getFilePath("examples/device-detection/console/src/main/resources/gettingStartedOnPrem.xml"); // load the options and if no resource key has been set in the file @@ -135,8 +135,9 @@ public static void run(String dataFile, already holds, but in normal operation usage sharing should be enabled by adding a Usage Sharing Element to the Pipeline, which the FiftyOnePipelineBuilder does unless ShareUsage is false. */ - try (Pipeline pipeline = new FiftyOnePipelineBuilder() - .buildFromConfiguration(pipelineOptions)) { + Pipeline pipeline = new FiftyOnePipelineBuilder() + .buildFromConfiguration(pipelineOptions); + try { /* Get the 'engine' element within the pipeline that performs device detection. We can use this to get details about the data file as well as meta-data describing @@ -155,6 +156,8 @@ public static void run(String dataFile, DataFileHelper.logDataFileInfo(engine); logger.info("All done"); + } finally { + pipeline.close(); } } @@ -178,9 +181,10 @@ private static boolean analyzeEvidence(Map evidence, detection is called "evidence" and usually consists of a number of HTTP Header field values, in this case represented by a Map of header name/value entries. - FlowData is wrapped in a try/resources block in order to ensure that the unmanaged + FlowData is closed in a finally block in order to ensure that the unmanaged resources allocated by the native device detection library are freed */ - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // list the evidence writer.println("Input values:"); @@ -217,6 +221,8 @@ private static boolean analyzeEvidence(Map evidence, engine, "HardwareName", device::getHardwareName); needsEnterprise |= writeEnterpriseValue(writer, "Device Type", engine, "DeviceType", device::getDeviceType); + } finally { + data.close(); } writer.println(); writer.flush(); diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/ManualDataUpdate.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/ManualDataUpdate.java index 68a9447e7..945402ac5 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/ManualDataUpdate.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/ManualDataUpdate.java @@ -107,7 +107,7 @@ public static void run(String dataFile, OutputStream outputStream) // The data file changes only when this code says so, because // automatic updates and the file system watcher are off. - try (Pipeline pipeline = new DeviceDetectionPipelineBuilder() + Pipeline pipeline = new DeviceDetectionPipelineBuilder() // The engine works from a copy of the data file, so a newer // file can be copied over the original while it runs. .useOnPremise(dataFileLocation, true) @@ -118,7 +118,8 @@ public static void run(String dataFile, OutputStream outputStream) // known to 51Degrees. In production, leave usage sharing on, which adds // a Usage Sharing Element to the Pipeline and helps improve the service. .setShareUsage(false) - .build()) { + .build(); + try { DeviceDetectionHashEngine engine = pipeline.getElement(DeviceDetectionHashEngine.class); @@ -148,6 +149,8 @@ public static void run(String dataFile, OutputStream outputStream) "updates."); DataFileHelper.writeEnterpriseNote(writer, CONTACT_US); } + } finally { + pipeline.close(); } writer.flush(); } @@ -166,7 +169,8 @@ private static boolean checkIfMobile(Pipeline pipeline, // The flow data is closed straight away, which releases the results // of the detection. Results that are not released keep the data // they were read from in memory, even after the data is refreshed. - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { data.addEvidence("header.user-agent", userAgent); data.process(); DeviceData device = data.get(DeviceData.class); @@ -182,6 +186,8 @@ private static boolean checkIfMobile(Pipeline pipeline, DataFileHelper.NEEDS_ENTERPRISE); writer.println(); return true; + } finally { + data.close(); } } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MatchMetrics.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MatchMetrics.java index ae753978d..706c5e660 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MatchMetrics.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MatchMetrics.java @@ -104,7 +104,7 @@ static void run(String dataFile, List> evidenceList, // Build a new Pipeline to use an on-premise Hash engine with the // low memory performance profile. - try (Pipeline pipeline = new DeviceDetectionPipelineBuilder() + Pipeline pipeline = new DeviceDetectionPipelineBuilder() .useOnPremise(dataFile, true) .setAutoUpdate(false) // Prefer low memory profile where all data streamed from disk @@ -136,14 +136,16 @@ static void run(String dataFile, List> evidenceList, // https://51degrees.com/documentation/_device_detection__hash.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=console-src-main-java-fiftyone-devicedetection-examples-console-matchmetrics.java&utm_term=run#DeviceDetection_Hash_DataSetProduction_Performance .setUsePredictiveGraph(true) .setUsePerformanceGraph(false) - .build()) { + .build(); + try { DataFileHelper.logDataFileInfo(pipeline.getElement(DeviceDetectionHashEngine.class)); - // A try-with-resource block MUST be used for the FlowData instance. + // The FlowData instance MUST be closed in a finally block. // This ensures that native resources created by the device // detection engine are freed. - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // Process a single evidence to retrieve the values // associated with the user-agent and other evidence such as sec-ch-* for the @@ -234,11 +236,15 @@ static void run(String dataFile, List> evidenceList, }); }); writer.println(); + } finally { + data.close(); } if (DataFileHelper.isLiteDataFile( pipeline.getElement(DeviceDetectionHashEngine.class))) { DataFileHelper.writeEnterpriseOffer(writer, CONTACT_US); } + } finally { + pipeline.close(); } logger.info("Finished Match Metrics Example"); } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataCloud.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataCloud.java index 875a7fb0a..f3a0a9332 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataCloud.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataCloud.java @@ -86,9 +86,10 @@ public static void run(String resourceKey, OutputStream output) throws Exception // the meta-data. // If you already have a pipeline and just want to get a reference to the engine // then you can use `var engine = pipeline.GetElement();` - try (Pipeline pipeline = new DeviceDetectionPipelineBuilder(LoggerFactory.getILoggerFactory()) + Pipeline pipeline = new DeviceDetectionPipelineBuilder(LoggerFactory.getILoggerFactory()) .useCloud(resourceKey) - .build()) { + .build(); + try { PrintWriter writer = new PrintWriter(output); @@ -108,6 +109,8 @@ public static void run(String resourceKey, OutputStream output) throws Exception outputEvidenceKeyDetails(pipeline.getElement(CloudRequestEngine.class), writer); writer.println(); writer.flush(); + } finally { + pipeline.close(); } } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataOnPrem.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataOnPrem.java index a7dbdb5f1..9a2d1f9e6 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataOnPrem.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MetadataOnPrem.java @@ -92,8 +92,8 @@ public static void run(String dataFile, OutputStream output) throws Exception { // the meta-data. // If you already have a pipeline and just want to get a reference to the engine // then you can use `var engine = pipeline.GetElement();` - try (DeviceDetectionHashEngine ddEngine = - new DeviceDetectionHashEngineBuilder(LoggerFactory.getILoggerFactory()) + DeviceDetectionHashEngine ddEngine = + new DeviceDetectionHashEngineBuilder(LoggerFactory.getILoggerFactory()) // We use the low memory profile as its performance is sufficient for this // example. See the documentation for more detail on this and other // configuration options: @@ -104,7 +104,8 @@ public static void run(String dataFile, OutputStream output) throws Exception { .setAutoUpdate(false) .setDataFileSystemWatcher(false) .setDataUpdateOnStartup(false) - .build(dataFileLocation, false)){ + .build(dataFileLocation, false); + try { PrintWriter writer = new PrintWriter(output); logger.info("Listing Components"); @@ -126,6 +127,8 @@ public static void run(String dataFile, OutputStream output) throws Exception { if (DataFileHelper.isLiteDataFile(ddEngine)) { DataFileHelper.writeEnterpriseOffer(writer, CONTACT_US); } + } finally { + ddEngine.close(); } } @@ -158,16 +161,19 @@ private static void outputProfileDetails(DeviceDetectionHashEngine ddEngine, // Group the profiles by component and then output the number of profiles // for each component. // - // A try-with-resource block MUST be used for the collections of - // metadata returned by the engine. Each one holds a reference to the + // The collections of metadata returned by the engine MUST be closed + // in a finally block. Each one holds a reference to the // engine's data set until it is closed, so if it is left open the // data set cannot be freed when the engine is closed. Map groups; - try (CloseableIterable profiles = ddEngine.getProfiles()) { + CloseableIterable profiles = ddEngine.getProfiles(); + try { groups = StreamSupport.stream(profiles.spliterator(), false) .collect(Collectors.groupingBy( p -> p.getComponent().getName(), Collectors.counting())); + } finally { + profiles.close(); } groups.forEach((k,v)->output.format("%s Profiles: %d\n", k , v)); } @@ -177,12 +183,15 @@ private static void outputProfileDetails(DeviceDetectionHashEngine ddEngine, // more readable. private static void outputComponents(DeviceDetectionHashEngine ddEngine, PrintWriter output) throws Exception { - // See outputProfileDetails for why this is a try-with-resource block. - try (CloseableIterable components = ddEngine.getComponents()) { + // See outputProfileDetails for why this is closed in a finally block. + CloseableIterable components = ddEngine.getComponents(); + try { for (ComponentMetaData c : components) { output.println("Component - "+ c.getName()); outputProperties(c, output); } + } finally { + components.close(); } } @@ -190,8 +199,9 @@ private static void outputProperties(ComponentMetaData component, PrintWriter ou throws Exception { // The properties of a component, and the values of a property, are // collections that are closed in the same way. - try (CloseableIterable properties = - component.getProperties()) { + CloseableIterable properties = + component.getProperties(); + try { if (properties.iterator().hasNext() == false) { output.println(" ... no properties"); return; @@ -213,8 +223,9 @@ private static void outputProperties(ComponentMetaData component, PrintWriter ou if (property.getCategory().equals("Device Metrics")==false) { StringBuilder values = new StringBuilder(" Possible " + "values: "); - try (CloseableIterable propertyValues = - property.getValues()) { + CloseableIterable propertyValues = + property.getValues(); + try { Spliterator spliterator2 = propertyValues.spliterator(); StreamSupport.stream(spliterator2, false) @@ -235,10 +246,14 @@ private static void outputProperties(ComponentMetaData component, PrintWriter ou if (spliterator2.estimateSize() > 20) { values.append(" + more ..."); } + } finally { + propertyValues.close(); } output.println(values); } } + } finally { + properties.close(); } } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MinimalExample.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MinimalExample.java index 6ea23a441..dbdf3f138 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MinimalExample.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/MinimalExample.java @@ -73,14 +73,16 @@ public static void run(String resource) throws Exception { // create a minimal pipeline to access the cloud engine // you only need one pipeline for multiple requests - // use try-with-resources to free the pipeline when done - try (Pipeline pipeline = new DeviceDetectionPipelineBuilder() + // close the pipeline in a finally block to free it when done + Pipeline pipeline = new DeviceDetectionPipelineBuilder() .useCloud(resource) - .build()) { + .build(); + try { /* get a flow data from the singleton pipeline for each detection */ // it's important to free the flowdata when done - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // add user-agent and client hint headers (if any) from the HTTP request data.addEvidence("header.user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + @@ -98,7 +100,11 @@ public static void run(String resource) throws Exception { DeviceData device = data.get(DeviceData.class); System.out.println("device.IsMobile: " + device.getIsMobile().getValue()); + } finally { + data.close(); } + } finally { + pipeline.close(); } } } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/NativeModelCloud.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/NativeModelCloud.java index cc470a745..586692d66 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/NativeModelCloud.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/NativeModelCloud.java @@ -103,7 +103,7 @@ public static void run(String resourceKey, OutputStream os) throws Exception { output.println("----------------------------------------"); // Create the pipeline and the engines we need. - try (Pipeline pipeline = new PipelineBuilder(LoggerFactory.getILoggerFactory()) + Pipeline pipeline = new PipelineBuilder(LoggerFactory.getILoggerFactory()) // Create the cloud request engine and add to the pipeline. .addFlowElement(new CloudRequestEngineBuilder(LoggerFactory.getILoggerFactory()) .setResourceKey(resourceKey) @@ -115,7 +115,8 @@ public static void run(String resourceKey, OutputStream os) throws Exception { // very important to ask pipeline to close the engines we added since // we are not closing them ourselves .setAutoCloseElements(true) - .build()) { + .build(); + try { // The pipeline asked the cloud for the key's accessible // properties as it was built, so unless that request failed, // a key without the lookup is found here, before any lookup. @@ -126,6 +127,8 @@ public static void run(String resourceKey, OutputStream os) throws Exception { // Repeat for an alternative native model name. analyseNativeModel(NATIVE_MODEL_2, pipeline, output); } + } finally { + pipeline.close(); } // The writer closes the stream it was given, so the section is // written before it. @@ -140,9 +143,10 @@ public static void run(String resourceKey, OutputStream os) throws Exception { * @return false if the key does not include the lookup */ static boolean analyseNativeModel(String nativemodel, Pipeline pipeline, PrintWriter output) throws Exception { - // Create the FlowData instance. This is wrapped in a try with resources to ensure + // Create the FlowData instance. This is closed in a finally block to ensure // that resources are disposed correctly. - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // Add the native model key as evidence. data.addEvidence(Constants.EVIDENCE_QUERY_NATIVE_MODEL_KEY, nativemodel); // Process the supplied evidence. If the accessible properties @@ -175,6 +179,8 @@ static boolean analyseNativeModel(String nativemodel, Pipeline pipeline, PrintWr } return true; + } finally { + data.close(); } } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/OfflineProcessing.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/OfflineProcessing.java index 173d74ba0..25e294b91 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/OfflineProcessing.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/OfflineProcessing.java @@ -140,9 +140,9 @@ public static void run(String dataFile, InputStream is, OutputStream os) throws logger.info("Constructing pipeline with on-premise hash " + "engine from file " + dataFile); - // Build a new on-premise Hash engine in a try/resources so - // that the pipeline is disposed when done - try (Pipeline pipeline = new DeviceDetectionPipelineBuilder() + // Build a new on-premise Hash engine and close it in a finally + // block so that the pipeline is disposed when done + Pipeline pipeline = new DeviceDetectionPipelineBuilder() .useOnPremise(detectionFile, false) // inhibit sharing usage for this test, usually // this should be set "true" @@ -167,7 +167,8 @@ public static void run(String dataFile, InputStream is, OutputStream os) throws // see https://51degrees.com/documentation/_device_detection__hash.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=console-src-main-java-fiftyone-devicedetection-examples-console-offlineprocessing.java&utm_term=run#DeviceDetection_Hash_PredictivePower //.setDifference(0) //.setDrift(0) - .build()) { + .build(); + try { // get the details of the detection engine from the pipeline, // to find out what data file we are using @@ -187,8 +188,9 @@ public static void run(String dataFile, InputStream is, OutputStream os) throws // Flow data is the container for inputs and outputs that // flow through the pipeline a flowdata instance is // created by the pipeline factory method it's important - // to dispose flowdata - so wrap in a try/resources - try (FlowData flowData = pipeline.createFlowData()) { + // to dispose flowdata - so close it in a finally block + FlowData flowData = pipeline.createFlowData(); + try { // the evidence values in the test YAML data are read // as a Map - add the evidence to the // flowData @@ -234,6 +236,8 @@ public static void run(String dataFile, InputStream is, OutputStream os) throws yaml.dump(flowData.getEvidence().asKeyMap(), writer); yaml.dump(resultMap, writer); writer.flush(); + } finally { + flowData.close(); } count++; } @@ -252,6 +256,8 @@ public static void run(String dataFile, InputStream is, OutputStream os) throws writer.flush(); logger.info("Finished processing {} records", count); } + } finally { + pipeline.close(); } } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/PerformanceBenchmark.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/PerformanceBenchmark.java index 3a527d479..053e70499 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/PerformanceBenchmark.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/PerformanceBenchmark.java @@ -346,28 +346,33 @@ public BenchmarkResult call() { for (Map evidence : testList) { // the benchmark is for detection time only - // A try-with-resource block MUST be used for the - // FlowData instance. This ensures that native resources + // The FlowData instance MUST be closed in a finally + // block. This ensures that native resources // created by the device detection engine are freed. - try (FlowData flowData = pipeline.createFlowData()) { - flowData - .addEvidence(evidence) - .process(); - - // Calculate a checksum to compare different runs on - // the same data. - DeviceData device = flowData.get(DeviceData.class); - if (device != null) { - if (device.getIsMobile().hasValue()) { - Object value = device.getIsMobile().getValue(); - if (value != null) { - result.checkSum += value.hashCode(); + try { + FlowData flowData = pipeline.createFlowData(); + try { + flowData + .addEvidence(evidence) + .process(); + + // Calculate a checksum to compare different runs on + // the same data. + DeviceData device = flowData.get(DeviceData.class); + if (device != null) { + if (device.getIsMobile().hasValue()) { + Object value = device.getIsMobile().getValue(); + if (value != null) { + result.checkSum += value.hashCode(); + } } } - } - result.count++; - if (result.count >= TESTS_PER_THREAD) { - break; + result.count++; + if (result.count >= TESTS_PER_THREAD) { + break; + } + } finally { + flowData.close(); } } catch (Exception e) { logger.error("Exception getting flow data", e); diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/ShareUsageExample.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/ShareUsageExample.java index e95d71faf..0ecd229ea 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/ShareUsageExample.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/ShareUsageExample.java @@ -168,10 +168,11 @@ public static void run(InputStream is, String shareUsageUrl) throws Exception { // Build a pipeline with only the ShareUsageElement. The pipeline is // asked to close the element, which sends any data still queued, as // it is not closed anywhere else. - try (Pipeline pipeline = new PipelineBuilder() + Pipeline pipeline = new PipelineBuilder() .addFlowElement(shareUsageElement) .setAutoCloseElements(true) - .build()) { + .build(); + try { logger.info("Pipeline built successfully with ShareUsageElement"); @@ -182,7 +183,8 @@ public static void run(InputStream is, String shareUsageUrl) throws Exception { // Process evidence records int count = 0; while (evidenceIterator.hasNext() && count < RECORDS_TO_PROCESS) { - try (FlowData flowData = pipeline.createFlowData()) { + FlowData flowData = pipeline.createFlowData(); + try { // Get evidence from YAML and filter to only header.* entries Map evidence = filterEvidence( (Map) evidenceIterator.next(), @@ -209,11 +211,15 @@ public static void run(InputStream is, String shareUsageUrl) throws Exception { if (count % 10 == 0) { logger.info("Processed {} records", count); } + } finally { + flowData.close(); } } logger.info("Finished processing {} records", count); logger.info("Closing pipeline - this will flush any remaining queued data..."); + } finally { + pipeline.close(); } // Give the background thread time to send any remaining data diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/TacCloud.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/TacCloud.java index faaafb892..5303400c2 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/TacCloud.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/TacCloud.java @@ -128,8 +128,9 @@ public static void run(String resourceKey, OutputStream os) throws Exception { // Create the pipeline using the service provider and the configured options. - try (Pipeline pipeline = new FiftyOnePipelineBuilder() - .buildFromConfiguration(pipelineOptions)) { + Pipeline pipeline = new FiftyOnePipelineBuilder() + .buildFromConfiguration(pipelineOptions); + try { // The pipeline asked the cloud for the key's accessible // properties as it was built, so unless that request failed, // a key without the lookup is found here, before any lookup. @@ -140,6 +141,8 @@ public static void run(String resourceKey, OutputStream os) throws Exception { // matching devices. analyseTac(TAC_2, pipeline, writer); } + } finally { + pipeline.close(); } // The writer closes the stream it was given, so the section is // written before it. @@ -155,7 +158,8 @@ public static void run(String resourceKey, OutputStream os) throws Exception { */ static boolean analyseTac(String tac, Pipeline pipeline, PrintWriter output) throws Exception { // Create the FlowData instance. - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // Add the TAC as evidence. data.addEvidence(Constants.EVIDENCE_QUERY_TAC_KEY, tac); // Process the supplied evidence. If the accessible properties @@ -187,6 +191,8 @@ static boolean analyseTac(String tac, Pipeline pipeline, PrintWriter output) thr output.format("\t%s %s (%s)%n", asString(vendor), asString(name), asString(model)); } return true; + } finally { + data.close(); } } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/UpdateDataFile.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/UpdateDataFile.java index 800b08f6d..712fc5594 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/UpdateDataFile.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/UpdateDataFile.java @@ -365,7 +365,7 @@ static void run(String dataFilename, String licenseKey, String product, // Build the device detection pipeline and pass in the desired settings to configure // automatic updates. - try (Pipeline pipeline = new DeviceDetectionPipelineBuilder() + Pipeline pipeline = new DeviceDetectionPipelineBuilder() // specify the filename for the data file. When using update on start-up // the file need not exist, but the directory it is in must exist. // Any file that is present is overwritten. Because the file will be @@ -398,7 +398,8 @@ static void run(String dataFilename, String licenseKey, String product, // by default this is 30 mins .setUpdatePollingInterval(1) // build the pipeline - .build()) { + .build(); + try { // thread blocks till update checking is complete - or if there is an // exception we don't get this far @@ -441,6 +442,8 @@ static void run(String dataFilename, String licenseKey, String product, updateNow(dataUpdateService, engine)); logger.info("Finished Example"); + } finally { + pipeline.close(); } } } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/comparison/Detection.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/comparison/Detection.java index 47dc2afd9..a37b44fb6 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/comparison/Detection.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/comparison/Detection.java @@ -141,7 +141,7 @@ public int getCount() { /** * The thing that actually does the detection */ - interface Solution extends AutoCloseable { + interface Solution { void initialise(int numberOfThreads) throws Exception; @@ -156,5 +156,11 @@ interface Solution extends AutoCloseable { */ default void writeNote(PrintWriter writer) { } + + /** + * Frees what the solution holds. + * @throws Exception if what it holds could not be closed + */ + void close() throws Exception; } } diff --git a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/comparison/DetectionImplFiftyOneDegrees.java b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/comparison/DetectionImplFiftyOneDegrees.java index 3057e03ee..750ba5900 100644 --- a/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/comparison/DetectionImplFiftyOneDegrees.java +++ b/examples/device-detection/console/src/main/java/fiftyone/devicedetection/examples/console/comparison/DetectionImplFiftyOneDegrees.java @@ -178,9 +178,12 @@ public void initialise(int numberOfThreads) throws Exception { @Override public Detection.Properties detect(Detection.Request request) throws Exception { - try (FlowData flowData = pipeline.createFlowData()){ + FlowData flowData = pipeline.createFlowData(); + try { flowData.addEvidence(request.getEvidence()).process(); return new FiftyOneProperties(request, flowData, missing); + } finally { + flowData.close(); } } diff --git a/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/CloudDropInTest.java b/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/CloudDropInTest.java index 9d4eaabe4..4be34876f 100644 --- a/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/CloudDropInTest.java +++ b/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/CloudDropInTest.java @@ -111,7 +111,8 @@ public void stopCloud() { * The code a developer writes once, for either engine. */ private static boolean isMobile(Pipeline pipeline) throws Exception { - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { data.addEvidence("header.user-agent", IPHONE).process(); DeviceData device = data.get(DeviceData.class); ElementData byKey = data.get("device"); @@ -122,6 +123,8 @@ private static boolean isMobile(Pipeline pipeline) throws Exception { "with a reason when it has none, and was " + byName, byName instanceof AspectPropertyValue); return device.getIsMobile().getValue(); + } finally { + data.close(); } } @@ -129,11 +132,14 @@ private static boolean isMobile(Pipeline pipeline) throws Exception { public void cloudResultsReadAsOnPremise() throws Exception { String endPoint = "http://" + cloud.getAddress().getHostString() + ":" + cloud.getAddress().getPort() + "/api/v4/"; - try (Pipeline pipeline = new DeviceDetectionPipelineBuilder() + Pipeline pipeline = new DeviceDetectionPipelineBuilder() .useCloud("dropinresourcekey") .setEndPoint(endPoint) - .build()) { + .build(); + try { assertTrue(isMobile(pipeline)); + } finally { + pipeline.close(); } } @@ -141,12 +147,15 @@ public void cloudResultsReadAsOnPremise() throws Exception { public void onPremiseResultsReadAsCloud() throws Exception { String file = getFilePath("device-detection/51Degrees-LiteV4.1.hash") .getAbsolutePath(); - try (Pipeline pipeline = new DeviceDetectionPipelineBuilder() + Pipeline pipeline = new DeviceDetectionPipelineBuilder() .useOnPremise(file, false) .setAutoUpdate(false) .setShareUsage(false) - .build()) { + .build(); + try { assertTrue(isMobile(pipeline)); + } finally { + pipeline.close(); } } } diff --git a/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/GettingStartedOnPremUsageSharingTest.java b/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/GettingStartedOnPremUsageSharingTest.java index d7eb7662d..717302701 100644 --- a/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/GettingStartedOnPremUsageSharingTest.java +++ b/examples/device-detection/console/src/test/java/fiftyone/devicedetection/examples/console/GettingStartedOnPremUsageSharingTest.java @@ -72,12 +72,15 @@ public void pipelineHasNoUsageSharingElement() throws Exception { PipelineOptions options = PipelineOptionsFactory.getOptionsFromFile(getFilePath(OPTIONS)); options.elements.clear(); - try (Pipeline pipeline = new FiftyOnePipelineBuilder() - .buildFromConfiguration(options)) { + Pipeline pipeline = new FiftyOnePipelineBuilder() + .buildFromConfiguration(options); + try { for (FlowElement element : pipeline.getFlowElements()) { assertFalse("The example's Pipeline should not share usage", element instanceof ShareUsageElement); } + } finally { + pipeline.close(); } } diff --git a/examples/device-detection/pom.xml b/examples/device-detection/pom.xml index e2f0b268a..6e8319b06 100644 --- a/examples/device-detection/pom.xml +++ b/examples/device-detection/pom.xml @@ -63,6 +63,7 @@ 2.0.20 1.3.16 3.28.0 + 3.9.0 @@ -75,6 +76,20 @@ ${project.version} + + + release-8 + + [9,) + + + 8 + + @@ -134,6 +149,21 @@ + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + true + + -Xlint:all + -Werror + + + org.apache.maven.plugins maven-surefire-plugin diff --git a/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/DataFileHelper.java b/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/DataFileHelper.java index febe8e8ca..062b2bb04 100644 --- a/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/DataFileHelper.java +++ b/examples/device-detection/shared/src/main/java/fiftyone/devicedetection/examples/shared/DataFileHelper.java @@ -110,10 +110,13 @@ public String getTier() { } } public static DatafileInfo getDatafileMetaData(String dataFileLocation) throws Exception { - try(DeviceDetectionHashEngine ddhe = new DeviceDetectionHashEngineBuilder() + DeviceDetectionHashEngine ddhe = new DeviceDetectionHashEngineBuilder() .setAutoUpdate(false) - .build(dataFileLocation,false)) { + .build(dataFileLocation,false); + try { return new DatafileInfo((FiftyOneDataFile) ddhe.getDataFileMetaData(), ddhe.getDataSourceTier()); + } finally { + ddhe.close(); } } diff --git a/examples/ip-intelligence/README.md b/examples/ip-intelligence/README.md index 0d7dbf5b9..04718423b 100644 --- a/examples/ip-intelligence/README.md +++ b/examples/ip-intelligence/README.md @@ -191,6 +191,11 @@ The web example will start a Jetty server on port 5151. Access it at: `http://lo Alternatively, you can build "fat" JARs and run examples from the command line. +Build the examples with JDK 17. They compile for Java 8 and treat every +compiler warning as an error, and javac 21 and later warn that Java 8 is +obsolete, so the build fails on JDK 21 and later. The JARs it makes run on +Java 8 or later. + First, build the packages: ```bash diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/CompareOnPrem.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/CompareOnPrem.java index 429992ff1..e5940000c 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/CompareOnPrem.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/CompareOnPrem.java @@ -301,7 +301,8 @@ public static void run(String dataFile, for (String property : LOCATION_PROPERTIES) { builder.setProperty(property); } - try (Pipeline pipeline = builder.build()) { + Pipeline pipeline = builder.build(); + try { // Read the truth records, skipping duplicate IP addresses. List truths = readTruths(truthFile); @@ -343,6 +344,8 @@ public static void run(String dataFile, IPIntelligenceOnPremiseEngine engine = pipeline.getElement(IPIntelligenceOnPremiseEngine.class); DataFileHelper.logDataFileInfo(engine); + } finally { + pipeline.close(); } } @@ -391,7 +394,8 @@ private static List readTruths(File csvFile) throws Exception { private static String processTruth(Pipeline pipeline, Truth truth) throws Exception { // Get the data for the IP address. - try (FlowData flowData = pipeline.createFlowData()) { + FlowData flowData = pipeline.createFlowData(); + try { flowData.addEvidence("query.client-ip", truth.ip); flowData.process(); IPIntelligenceData data = flowData.get(IPIntelligenceData.class); @@ -441,6 +445,8 @@ private static String processTruth(Pipeline pipeline, Truth truth) area.getSquareKms() + "," + area.getGeometries() + "," + area.getContains(); + } finally { + flowData.close(); } } diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GetAllPropertiesCloud.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GetAllPropertiesCloud.java index e8d7d7cf0..5451d79cc 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GetAllPropertiesCloud.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GetAllPropertiesCloud.java @@ -133,10 +133,13 @@ public static void run(String resourceKey, } // Create the pipeline - try (Pipeline pipeline = builder.build()) { + Pipeline pipeline = builder.build(); + try { // Output details for the IP address analyzeEvidence(SOME_IP_ADDRESS, pipeline, outputStream); logger.info("All done"); + } finally { + pipeline.close(); } } @@ -145,7 +148,8 @@ private static void analyzeEvidence(String ipAddress, OutputStream out) throws Exception { PrintWriter writer = new PrintWriter(out); // Create the FlowData instance. - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // Add the client IP as evidence. data.addEvidence("query.client-ip", ipAddress); // Process the supplied evidence. @@ -163,6 +167,8 @@ private static void analyzeEvidence(String ipAddress, property.getKey(), getValueToOutput(property.getValue())); } + } finally { + data.close(); } writer.println(); writer.flush(); diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloud.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloud.java index 427261eaa..77798baee 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloud.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloud.java @@ -141,7 +141,7 @@ public static void run(String resourceKey, For more information about pipelines in general see the documentation at https://51degrees.com/documentation/_pipeline_api__concepts__configuration__builders__index.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=console-src-main-java-fiftyone-ipintelligence-examples-console-gettingstartedcloud.java&utm_term=configuration-builders - Note that we wrap the creation of a pipeline in a try/resources to control its lifecycle */ + Note that we close the pipeline in a finally block to control its lifecycle */ IPIntelligenceCloudPipelineBuilder builder = new IPIntelligencePipelineBuilder() // Tell it that we want to use cloud and pass our resource key. .useCloud(resourceKey); @@ -150,7 +150,8 @@ public static void run(String resourceKey, if (endPoint != null && endPoint.isEmpty() == false) { builder.setEndPoint(endPoint); } - try (Pipeline pipeline = builder.build()) { + Pipeline pipeline = builder.build(); + try { // carry out some sample lookups for (Map evidence : evidenceList) { @@ -158,6 +159,8 @@ public static void run(String resourceKey, } logger.info("All done"); + } finally { + pipeline.close(); } } @@ -177,9 +180,10 @@ private static void analyzeEvidence(Map evidence, a lookup is called "evidence", in this case represented by a Map of evidence key/value entries. - FlowData is wrapped in a try/resources block in order to ensure that the resources + FlowData is closed in a finally block in order to ensure that the resources are freed in a timely manner */ - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // list the evidence writer.println("Input values:"); @@ -220,6 +224,8 @@ private static void analyzeEvidence(Map evidence, writeValue(writer, "Areas", tryGet(ipData::getAreas)); writeValue(writer, "AccuracyRadiusMin", tryGet(ipData::getAccuracyRadiusMin)); writeValue(writer, "TimeZoneOffset", tryGet(ipData::getTimeZoneOffset)); + } finally { + data.close(); } writer.println(); writer.flush(); diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloudMixed.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloudMixed.java index 571299223..e0f8daa98 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloudMixed.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedCloudMixed.java @@ -161,12 +161,13 @@ public static void run(String resourceKey, // The engines are not closed anywhere else, so the pipeline is asked // to close them when it is closed. - try (Pipeline pipeline = new PipelineBuilder(loggerFactory) + Pipeline pipeline = new PipelineBuilder(loggerFactory) .addFlowElement(cloudRequestEngine) .addFlowElement(deviceDetectionEngine) .addFlowElement(ipIntelligenceEngine) .setAutoCloseElements(true) - .build()) { + .build(); + try { // carry out some sample detections for (Map evidence : evidenceList) { @@ -174,6 +175,8 @@ public static void run(String resourceKey, } logger.info("All done"); + } finally { + pipeline.close(); } } @@ -181,7 +184,8 @@ private static void analyzeEvidence(Map evidence, Pipeline pipeline, OutputStream out) throws Exception { PrintWriter writer = new PrintWriter(out); - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // List the evidence writer.println("==============================================================================="); @@ -229,6 +233,8 @@ private static void analyzeEvidence(Map evidence, writer.println("\tIpRangeEnd: " + asIPAddressProperty(tryGet(ipData::getIpRangeEnd))); writer.println("\tAccuracyRadiusMin: " + asIntegerProperty(tryGet(ipData::getAccuracyRadiusMin))); writer.println("\tTimeZoneOffset: " + asIntegerProperty(tryGet(ipData::getTimeZoneOffset))); + } finally { + data.close(); } writer.println(); writer.flush(); diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedMixed.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedMixed.java index b2dd8caa7..3d4566e8b 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedMixed.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedMixed.java @@ -161,12 +161,13 @@ public static void run(String ddDataFile, DataFileHelper.useDataFile( pipelineOptions, "IPIntelligenceOnPremiseEngine", ipiLocation); - try (Pipeline pipeline = new FiftyOnePipelineBuilder() + Pipeline pipeline = new FiftyOnePipelineBuilder() // Usage sharing is off because this example's evidence is already // known to 51Degrees. In production, leave usage sharing on, which adds // a Usage Sharing Element to the Pipeline and helps improve the service. .setShareUsage(false) - .buildFromConfiguration(pipelineOptions)) { + .buildFromConfiguration(pipelineOptions); + try { // The engines say which properties their data files have. DeviceDetectionHashEngine ddEngine = pipeline.getElement(DeviceDetectionHashEngine.class); @@ -194,6 +195,8 @@ public static void run(String ddDataFile, } logger.info("All done"); + } finally { + pipeline.close(); } } @@ -245,7 +248,8 @@ private static boolean analyzeEvidence(Map evidence, boolean needsEnterprise = false; PrintWriter writer = new PrintWriter(out); - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // List the evidence writer.println("==============================================================================="); @@ -321,6 +325,8 @@ private static boolean analyzeEvidence(Map evidence, DataFileHelper.hasProperty(ipiEngine, "AccuracyRadiusMin"), ipData::getAccuracyRadiusMin); needsEnterprise |= writeValue(writer, "TimeZoneOffset", DataFileHelper.hasProperty(ipiEngine, "TimeZoneOffset"), ipData::getTimeZoneOffset); + } finally { + data.close(); } writer.println(); writer.flush(); diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedOnPrem.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedOnPrem.java index 1e08adc1c..8427c61aa 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedOnPrem.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/GettingStartedOnPrem.java @@ -146,7 +146,7 @@ public static void run(String dataFile, For more information about pipelines in general see the documentation at https://51degrees.com/documentation/_pipeline_api__concepts__configuration__builders__index.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=console-src-main-java-fiftyone-ipintelligence-examples-console-gettingstartedonprem.java&utm_term=run - Note that we wrap the creation of a pipeline in a try/resources to control its lifecycle */ + Note that we close the pipeline in a finally block to control its lifecycle */ // the configuration file is in the resources directory File optionsFile = getFilePath("examples/ip-intelligence/console/src/main/resources/gettingStartedOnPrem.xml"); // load the options and if no resource key has been set in the file @@ -157,12 +157,13 @@ public static void run(String dataFile, DataFileHelper.useDataFile( pipelineOptions, "IPIntelligenceOnPremiseEngine", dataFileLocation); // Build a new Pipeline from the configuration. - try (Pipeline pipeline = new FiftyOnePipelineBuilder() + Pipeline pipeline = new FiftyOnePipelineBuilder() // Usage sharing is off because this example's evidence is already // known to 51Degrees. In production, leave usage sharing on, which adds // a Usage Sharing Element to the Pipeline and helps improve the service. .setShareUsage(false) - .buildFromConfiguration(pipelineOptions)) { + .buildFromConfiguration(pipelineOptions); + try { /* Get the 'engine' element within the pipeline that performs IP Intelligence. We can use this to get details about the data file as well as meta-data describing @@ -181,6 +182,8 @@ public static void run(String dataFile, DataFileHelper.logDataFileInfo(engine); logger.info("All done"); + } finally { + pipeline.close(); } } @@ -204,9 +207,10 @@ private static boolean analyzeEvidence(Map evidence, a lookup is called "evidence", for IP Intelligence this is an IP address, in this case represented by a Map of evidence key/value entries. - FlowData is wrapped in a try/resources block in order to ensure that the unmanaged + FlowData is closed in a finally block in order to ensure that the unmanaged resources allocated by the native IP Intelligence library are freed */ - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // list the evidence writer.println("Input values:"); @@ -250,6 +254,8 @@ private static boolean analyzeEvidence(Map evidence, needsEnterprise |= writeValue(writer, engine, ipData, "Areas"); needsEnterprise |= writeValue(writer, engine, ipData, "AccuracyRadiusMin"); needsEnterprise |= writeValue(writer, engine, ipData, "TimeZoneOffset"); + } finally { + data.close(); } writer.println(); writer.flush(); diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataCloud.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataCloud.java index 83c49ef0c..1c0b172f5 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataCloud.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataCloud.java @@ -136,7 +136,8 @@ public static void run(String resourceKey, builder.setEndPoint(endPoint); } - try (Pipeline pipeline = builder.build()) { + Pipeline pipeline = builder.build(); + try { PrintWriter writer = new PrintWriter(outputStream); logger.info("Listing Properties"); @@ -162,6 +163,8 @@ public static void run(String resourceKey, writer.flush(); logger.info("All done"); + } finally { + pipeline.close(); } } diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataOnPrem.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataOnPrem.java index 2619ca2cf..a510b9b93 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataOnPrem.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetadataOnPrem.java @@ -107,8 +107,8 @@ public static void run(String dataFile, OutputStream output) throws Exception { // profile. There is no need to build a complete pipeline to read the // metadata. Code that already has a pipeline can get its engine with // pipeline.getElement(IPIntelligenceOnPremiseEngine.class). - try (IPIntelligenceOnPremiseEngine engine = - new IPIntelligenceOnPremiseEngineBuilder(LoggerFactory.getILoggerFactory()) + IPIntelligenceOnPremiseEngine engine = + new IPIntelligenceOnPremiseEngineBuilder(LoggerFactory.getILoggerFactory()) // We use the low memory profile to minimize memory usage for this // metadata example, which is memory-intensive. .setPerformanceProfile(Constants.PerformanceProfiles.LowMemory) @@ -116,7 +116,8 @@ public static void run(String dataFile, OutputStream output) throws Exception { .setAutoUpdate(false) .setDataFileSystemWatcher(false) .setDataUpdateOnStartup(false) - .build(dataFileLocation, false)){ + .build(dataFileLocation, false); + try { PrintWriter writer = new PrintWriter(output); logger.info("Listing Components"); @@ -138,6 +139,8 @@ public static void run(String dataFile, OutputStream output) throws Exception { if (DataFileHelper.isFreeDataFile(engine)) { DataFileHelper.writeEnterpriseOffer(writer, CONTACT_US); } + } finally { + engine.close(); } } @@ -174,16 +177,19 @@ private static void outputProfileDetails(IPIntelligenceOnPremiseEngine engine, // materializing them all just to call size() exhausts the heap // (OutOfMemoryError). counting() retains only the per-group total. // - // A try-with-resource block MUST be used for the collections of - // metadata returned by the engine. Each one holds a reference to the + // The collections of metadata returned by the engine MUST be closed + // in a finally block. Each one holds a reference to the // engine's data set until it is closed, so if it is left open the // data set cannot be freed when the engine is closed. Map groups; - try (CloseableIterable profiles = engine.getProfiles()) { + CloseableIterable profiles = engine.getProfiles(); + try { groups = StreamSupport.stream(profiles.spliterator(), false) .collect(Collectors.groupingBy( p -> p.getComponent().getName(), Collectors.counting())); + } finally { + profiles.close(); } groups.forEach((k,v)->output.format("%s Profiles: %d\n", k , v)); } @@ -193,12 +199,15 @@ private static void outputProfileDetails(IPIntelligenceOnPremiseEngine engine, // more readable. private static void outputComponents(IPIntelligenceOnPremiseEngine engine, PrintWriter output) throws Exception { - // See outputProfileDetails for why this is a try-with-resource block. - try (CloseableIterable components = engine.getComponents()) { + // See outputProfileDetails for why this is closed in a finally block. + CloseableIterable components = engine.getComponents(); + try { for (ComponentMetaData c : components) { output.println("Component - "+ c.getName()); outputProperties(c, output); } + } finally { + components.close(); } } @@ -206,8 +215,9 @@ private static void outputProperties(ComponentMetaData component, PrintWriter ou throws Exception { // The properties of a component, and the values of a property, are // collections that are closed in the same way. - try (CloseableIterable properties = - component.getProperties()) { + CloseableIterable properties = + component.getProperties(); + try { if (properties.iterator().hasNext() == false) { output.println(" ... no properties"); return; @@ -229,8 +239,9 @@ private static void outputProperties(ComponentMetaData component, PrintWriter ou if (property.getCategory().equals("Metrics")==false) { StringBuilder values = new StringBuilder(" Possible " + "values: "); - try (CloseableIterable propertyValues = - property.getValues()) { + CloseableIterable propertyValues = + property.getValues(); + try { Spliterator spliterator2 = propertyValues.spliterator(); StreamSupport.stream(spliterator2, false) @@ -251,10 +262,14 @@ private static void outputProperties(ComponentMetaData component, PrintWriter ou if (spliterator2.estimateSize() > 20) { values.append(" + more ..."); } + } finally { + propertyValues.close(); } output.println(values); } } + } finally { + properties.close(); } } diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetricsOnPrem.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetricsOnPrem.java index 76566b923..e77ee8c38 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetricsOnPrem.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/MetricsOnPrem.java @@ -436,7 +436,8 @@ public static void run(String dataFile, onPremiseBuilder.setProperty(property); } - try (Pipeline pipeline = onPremiseBuilder.build()) { + Pipeline pipeline = onPremiseBuilder.build(); + try { IPIntelligenceOnPremiseEngine engine = pipeline.getElement(IPIntelligenceOnPremiseEngine.class); @@ -490,6 +491,8 @@ public static void run(String dataFile, writeCsv(output, groups); logger.info("All done"); + } finally { + pipeline.close(); } } @@ -509,15 +512,16 @@ private static int addRanges(IPIntelligenceOnPremiseEngine engine, int added = 0; // Find the Network component which contains the range properties. // - // A try-with-resource block MUST be used for the collections of - // metadata returned by the engine. Each one holds a reference to the + // The collections of metadata returned by the engine MUST be closed + // in a finally block. Each one holds a reference to the // engine's data set until it is closed. If it is left open, closing // the pipeline cannot free the data set, and with the max performance // profile that is the whole data file held in memory until the // garbage collector happens to finalize the collection. ComponentMetaData network = null; - try (CloseableIterable components = - engine.getComponents()) { + CloseableIterable components = + engine.getComponents(); + try { for (ComponentMetaData component : components) { if (network == null && "Network".equalsIgnoreCase(component.getName())) { @@ -526,6 +530,8 @@ private static int addRanges(IPIntelligenceOnPremiseEngine engine, component.close(); } } + } finally { + components.close(); } if (network == null) { logger.warn("No 'Network' component found in the data file. " + @@ -534,29 +540,33 @@ private static int addRanges(IPIntelligenceOnPremiseEngine engine, } // The Network component is kept to compare each profile against, so // it is closed with the collection of profiles once that is done. - try (ComponentMetaData networkComponent = network; - CloseableIterable profiles = - engine.getProfiles()) { - for (ProfileMetaData profile : profiles) { - try (ComponentMetaData component = profile.getComponent()) { - if (networkComponent.equals(component) && - isRegisteredCountryValid(profile)) { - String start = getValue(profile, "IpRangeStart"); - String end = getValue(profile, "IpRangeEnd"); - if (start != null && end != null) { - String[] range = new String[]{start, end}; - if (condition == null || condition.test(range)) { - ranges.put(range); - added++; - if (maxRanges > 0 && added >= maxRanges) { - break; + try (ComponentMetaData networkComponent = network) { + CloseableIterable profiles = + engine.getProfiles(); + try { + for (ProfileMetaData profile : profiles) { + try (ComponentMetaData component = profile.getComponent()) { + if (networkComponent.equals(component) && + isRegisteredCountryValid(profile)) { + String start = getValue(profile, "IpRangeStart"); + String end = getValue(profile, "IpRangeEnd"); + if (start != null && end != null) { + String[] range = new String[]{start, end}; + if (condition == null || condition.test(range)) { + ranges.put(range); + added++; + if (maxRanges > 0 && added >= maxRanges) { + break; + } } } } + } finally { + profile.close(); } - } finally { - profile.close(); } + } finally { + profiles.close(); } } return added; @@ -585,13 +595,16 @@ private static String getValue(ProfileMetaData profile, String name) String result = null; // Every value is closed, not only the first, as each one wraps a // native object of its own. - try (CloseableIterable values = profile.getValues(name)) { + CloseableIterable values = profile.getValues(name); + try { for (ValueMetaData value : values) { if (result == null) { result = value.getName(); } value.close(); } + } finally { + values.close(); } return result; } @@ -642,7 +655,8 @@ private static void processIp(Pipeline pipeline, Map groups, InetAddress ipAddress) throws Exception { // Get the data for the IP address. - try (FlowData flowData = pipeline.createFlowData()) { + FlowData flowData = pipeline.createFlowData(); + try { flowData.addEvidence("query.client-ip", ipAddress.getHostAddress()); flowData.process(); IPIntelligenceData data = flowData.get(IPIntelligenceData.class); @@ -678,6 +692,8 @@ private static void processIp(Pipeline pipeline, metric.areaCount++; } } + } finally { + flowData.close(); } } diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/OfflineProcessing.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/OfflineProcessing.java index 79fe0f5dd..54c9204a5 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/OfflineProcessing.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/OfflineProcessing.java @@ -173,9 +173,9 @@ public static void run(String dataFile, InputStream is, OutputStream os) throws logger.info("Constructing pipeline with on-premise IP Intelligence " + "engine from file " + dataFile); - // Build a new on-premise IP Intelligence engine in a try/resources so - // that the pipeline is disposed when done - try (Pipeline pipeline = new IPIntelligencePipelineBuilder() + // Build a new on-premise IP Intelligence engine and close it in a finally + // block so that the pipeline is disposed when done + Pipeline pipeline = new IPIntelligencePipelineBuilder() .useOnPremise(dataFileLocation, false) // Usage sharing is off because this example's evidence is already // known to 51Degrees. In production, leave usage sharing on, which adds @@ -196,7 +196,8 @@ public static void run(String dataFile, InputStream is, OutputStream os) throws // loads the whole data file into memory, which makes each // lookup faster where there is memory to hold it. .setPerformanceProfile(Constants.PerformanceProfiles.LowMemory) - .build()) { + .build(); + try { // get the details of the IP Intelligence engine from the pipeline, // to find out what data file we are using @@ -216,8 +217,9 @@ public static void run(String dataFile, InputStream is, OutputStream os) throws // Flow data is the container for inputs and outputs that // flow through the pipeline a flowdata instance is // created by the pipeline factory method it's important - // to dispose flowdata - so wrap in a try/resources - try (FlowData flowData = pipeline.createFlowData()) { + // to dispose flowdata - so close it in a finally block + FlowData flowData = pipeline.createFlowData(); + try { // the evidence values in the test YAML data are read // as a Map - add the evidence to the // flowData @@ -266,6 +268,8 @@ public static void run(String dataFile, InputStream is, OutputStream os) throws yaml.dump(flowData.getEvidence().asKeyMap(), writer); yaml.dump(resultMap, writer); writer.flush(); + } finally { + flowData.close(); } count++; } @@ -284,6 +288,8 @@ public static void run(String dataFile, InputStream is, OutputStream os) throws writer.flush(); logger.info("Finished processing {} records", count); } + } finally { + pipeline.close(); } } diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/PerformanceBenchmark.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/PerformanceBenchmark.java index 44ac1c5fb..3cf767daf 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/PerformanceBenchmark.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/PerformanceBenchmark.java @@ -276,14 +276,17 @@ private void setPipelinePerformanceProperties( */ static List benchmarkProperties(String dataFileLocation) throws Exception { - try (IPIntelligenceOnPremiseEngine engine = - new IPIntelligenceOnPremiseEngineBuilder() - .setPerformanceProfile(LowMemory) - .setAutoUpdate(false) - .build(dataFileLocation, false)) { + IPIntelligenceOnPremiseEngine engine = + new IPIntelligenceOnPremiseEngineBuilder() + .setPerformanceProfile(LowMemory) + .setAutoUpdate(false) + .build(dataFileLocation, false); + try { return Collections.singletonList( DataFileHelper.hasProperty(engine, "RegisteredName") ? "RegisteredName" : "AsnName"); + } finally { + engine.close(); } } @@ -377,33 +380,38 @@ public BenchmarkResult call() { for (Map evidence : testList) { // the benchmark is for processing time only - // A try-with-resource block MUST be used for the - // FlowData instance. This ensures that native resources + // The FlowData instance MUST be closed in a finally + // block. This ensures that native resources // created by the IP Intelligence engine are freed. - try (FlowData flowData = pipeline.createFlowData()) { - flowData - .addEvidence(evidence) - .process(); - - // Calculate a checksum to compare different runs on - // the same data. - IPIntelligenceData ipData = flowData.get(IPIntelligenceData.class); - if (ipData != null) { - AspectPropertyValue name = readRegisteredName ? - ipData.getRegisteredName() : ipData.getAsnName(); - if (name.hasValue()) { - String value = name.getValue(); - if (value != null) { - result.checkSum += value.hashCode(); + try { + FlowData flowData = pipeline.createFlowData(); + try { + flowData + .addEvidence(evidence) + .process(); + + // Calculate a checksum to compare different runs on + // the same data. + IPIntelligenceData ipData = flowData.get(IPIntelligenceData.class); + if (ipData != null) { + AspectPropertyValue name = readRegisteredName ? + ipData.getRegisteredName() : ipData.getAsnName(); + if (name.hasValue()) { + String value = name.getValue(); + if (value != null) { + result.checkSum += value.hashCode(); // for (IWeightedValue weightedValue : value) { // result.checkSum += weightedValue.getValue().hashCode(); // } + } } } - } - result.count++; - if (result.count >= TESTS_PER_THREAD) { - break; + result.count++; + if (result.count >= TESTS_PER_THREAD) { + break; + } + } finally { + flowData.close(); } } catch (Exception e) { logger.error("Exception getting flow data", e); diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/SuspiciousOnPrem.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/SuspiciousOnPrem.java index fb84c3f1d..cb508b940 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/SuspiciousOnPrem.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/SuspiciousOnPrem.java @@ -163,8 +163,8 @@ public static void run(String dataFile, For more information about builders in general see the documentation at https://51degrees.com/documentation/_pipeline_api__concepts__configuration__builders__index.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=console-src-main-java-fiftyone-ipintelligence-examples-console-suspiciousonprem.java&utm_term=configuration-builders - Note that we wrap the creation of a pipeline in a try/resources to control its lifecycle */ - try (Pipeline pipeline = new IPIntelligencePipelineBuilder() + Note that we close the pipeline in a finally block to control its lifecycle */ + Pipeline pipeline = new IPIntelligencePipelineBuilder() .useOnPremise(dataFileLocation, false) // We use the low memory profile, because this example needs // properties only the Enterprise data file has, and that file @@ -183,7 +183,8 @@ public static void run(String dataFile, .setAutoUpdate(false) .setDataUpdateOnStartup(false) .setDataFileSystemWatcher(false) - .build()) { + .build(); + try { // carry out some sample detections for (Map evidence : evidenceList) { @@ -195,6 +196,8 @@ public static void run(String dataFile, DataFileHelper.logDataFileInfo(engine); logger.info("All done"); + } finally { + pipeline.close(); } } @@ -209,7 +212,8 @@ private static void analyzeEvidence(Map evidence, Pipeline pipeline, OutputStream out) throws Exception { PrintWriter writer = new PrintWriter(out); - try (FlowData data = pipeline.createFlowData()) { + FlowData data = pipeline.createFlowData(); + try { // Add the evidence values to the flow data and process it data.addEvidence(evidence); @@ -276,6 +280,8 @@ private static void analyzeEvidence(Map evidence, writer.println("\tRegisteredCountry: " + registeredCountry); writer.println("\tHumanProbability: " + human); writer.println("\tIsSuspicious: " + isSuspicious); + } finally { + data.close(); } writer.println(); writer.flush(); diff --git a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/UpdateDataFile.java b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/UpdateDataFile.java index 2e1cb194e..69860618b 100644 --- a/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/UpdateDataFile.java +++ b/examples/ip-intelligence/console/src/main/java/fiftyone/ipintelligence/examples/console/UpdateDataFile.java @@ -24,6 +24,7 @@ import fiftyone.ipintelligence.examples.shared.FindOutMore; import fiftyone.ipintelligence.IPIntelligencePipelineBuilder; +import fiftyone.ipintelligence.engine.onpremise.flowelements.IPIntelligenceOnPremiseEngine; import fiftyone.ipintelligence.examples.shared.DataFileHelper; import fiftyone.ipintelligence.shared.testhelpers.KeyUtils; import fiftyone.pipeline.core.flowelements.Pipeline; @@ -339,7 +340,7 @@ static void run(String dataFilename, String licenseKey, String product, // Build the IP Intelligence pipeline and pass in the desired settings to configure // automatic updates. - try (Pipeline pipeline = new IPIntelligencePipelineBuilder() + Pipeline pipeline = new IPIntelligencePipelineBuilder() // specify the filename for the data file. When using update on start-up // the file need not exist, but the directory it is in must exist. // Any file that is present is overwritten. Because the file will be @@ -380,7 +381,8 @@ static void run(String dataFilename, String licenseKey, String product, // by default this is 30 mins .setUpdatePollingInterval(1) // build the pipeline - .build()) { + .build(); + try { // thread blocks till update checking is complete - or if there is an // exception we don't get this far @@ -413,7 +415,15 @@ static void run(String dataFilename, String licenseKey, String product, completionListener.args.getStatus()); } + // The engine now uses the data file the update loaded. + IPIntelligenceOnPremiseEngine engine = + pipeline.getElement(IPIntelligenceOnPremiseEngine.class); + logger.info("The data file in use was published {}", + engine.getDataFilePublishedDate()); + logger.info("Finished Example"); + } finally { + pipeline.close(); } } } diff --git a/examples/ip-intelligence/console/src/test/java/fiftyone/ipintelligence/examples/console/areas/CalculationsTest.java b/examples/ip-intelligence/console/src/test/java/fiftyone/ipintelligence/examples/console/areas/CalculationsTest.java index 6a0b1e307..a46641a33 100644 --- a/examples/ip-intelligence/console/src/test/java/fiftyone/ipintelligence/examples/console/areas/CalculationsTest.java +++ b/examples/ip-intelligence/console/src/test/java/fiftyone/ipintelligence/examples/console/areas/CalculationsTest.java @@ -179,6 +179,12 @@ public void testContains() throws Exception { * is given the same point, as compiled code can for Math.sin. */ private static class DriftingTransform implements CoordinateTransform { + /** + * CoordinateTransform is Serializable, so this class gives its + * serialized form a version of its own. + */ + private static final long serialVersionUID = 1L; + private final Set seen = new HashSet<>(); @Override diff --git a/examples/ip-intelligence/pom.xml b/examples/ip-intelligence/pom.xml index 7adfc06b3..2e9cd989d 100644 --- a/examples/ip-intelligence/pom.xml +++ b/examples/ip-intelligence/pom.xml @@ -64,6 +64,7 @@ 2.0.20 1.3.16 3.28.0 + 3.9.0 @@ -77,6 +78,20 @@ ${project.version} + + + release-8 + + [9,) + + + 8 + + @@ -136,6 +151,21 @@ + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + true + + -Xlint:all + -Werror + + + org.apache.maven.plugins maven-surefire-plugin diff --git a/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/DataFileHelper.java b/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/DataFileHelper.java index f6f1515ed..ca9b4f12a 100644 --- a/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/DataFileHelper.java +++ b/examples/ip-intelligence/shared/src/main/java/fiftyone/ipintelligence/examples/shared/DataFileHelper.java @@ -185,12 +185,15 @@ public boolean isFree() { * @throws Exception if the data file cannot be opened */ public static DatafileInfo getDatafileMetaData(String dataFileLocation) throws Exception { - try(IPIntelligenceOnPremiseEngine ddhe = new IPIntelligenceOnPremiseEngineBuilder() + IPIntelligenceOnPremiseEngine ddhe = new IPIntelligenceOnPremiseEngineBuilder() .setPerformanceProfile(Constants.PerformanceProfiles.LowMemory) .setAutoUpdate(false) - .build(dataFileLocation,false)) { + .build(dataFileLocation,false); + try { return new DatafileInfo((FiftyOneDataFile) ddhe.getDataFileMetaData(), ddhe.getDataSourceTier(), isFreeDataFile(ddhe)); + } finally { + ddhe.close(); } } @@ -267,12 +270,15 @@ public static boolean lacksEnterpriseProperties(String dataFile, List properties, PrintWriter output, String contactUs) throws Exception { - try (IPIntelligenceOnPremiseEngine engine = new IPIntelligenceOnPremiseEngineBuilder() + IPIntelligenceOnPremiseEngine engine = new IPIntelligenceOnPremiseEngineBuilder() .setPerformanceProfile(Constants.PerformanceProfiles.LowMemory) .setAutoUpdate(false) - .build(dataFile, false)) { + .build(dataFile, false); + try { return lacksEnterpriseProperties( engine, purpose, properties, output, contactUs); + } finally { + engine.close(); } } diff --git a/examples/ip-intelligence/web/getting-started.api/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedApi.java b/examples/ip-intelligence/web/getting-started.api/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedApi.java index 1d36cd8d1..e7673f996 100644 --- a/examples/ip-intelligence/web/getting-started.api/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedApi.java +++ b/examples/ip-intelligence/web/getting-started.api/src/main/java/fiftyone/ipintelligence/examples/web/GettingStartedApi.java @@ -267,7 +267,8 @@ private void processEvidence(HttpServletRequest request, HttpServletResponse res // A Flow Data cannot be used by two threads at once. Work handed to // another thread or task gets the values it needs, read here on the // request's thread, not the Flow Data. - try (FlowData flowData = pipeline.createFlowData()) { + FlowData flowData = pipeline.createFlowData(); + try { flowData.addEvidence(evidence); flowData.process(); @@ -280,6 +281,8 @@ private void processEvidence(HttpServletRequest request, HttpServletResponse res } response.setContentType("application/json"); response.getWriter().write(jsonData.getJson()); + } finally { + flowData.close(); } } diff --git a/examples/ip-intelligence/web/getting-started.api/src/test/java/fiftyone/ipintelligence/examples/web/GettingStartedApiNotesTest.java b/examples/ip-intelligence/web/getting-started.api/src/test/java/fiftyone/ipintelligence/examples/web/GettingStartedApiNotesTest.java index 897d74f93..bc867bf23 100644 --- a/examples/ip-intelligence/web/getting-started.api/src/test/java/fiftyone/ipintelligence/examples/web/GettingStartedApiNotesTest.java +++ b/examples/ip-intelligence/web/getting-started.api/src/test/java/fiftyone/ipintelligence/examples/web/GettingStartedApiNotesTest.java @@ -52,11 +52,12 @@ public class GettingStartedApiNotesTest { public void startupNotes_FreeDataFile() throws Exception { String lite = DataFileHelper.getDataFileLocation( DataFileHelper.LITE_DATA_FILE_REL_PATH); - try (IPIntelligenceOnPremiseEngine engine = - new IPIntelligenceOnPremiseEngineBuilder( - LoggerFactory.getILoggerFactory()) - .setAutoUpdate(false) - .build(lite, false)) { + IPIntelligenceOnPremiseEngine engine = + new IPIntelligenceOnPremiseEngineBuilder( + LoggerFactory.getILoggerFactory()) + .setAutoUpdate(false) + .build(lite, false); + try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); GettingStartedApi.writeStartupNotes( new PrintStream(buffer, true, "UTF-8"), engine); @@ -75,6 +76,8 @@ public void startupNotes_FreeDataFile() throws Exception { assertTrue("The '" + FindOutMore.HEADING + "' section should end with its rule:\n" + output, output.indexOf(FindOutMore.RULE, heading) > heading); + } finally { + engine.close(); } } } diff --git a/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/HardwareProfileCloudEngine.java b/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/HardwareProfileCloudEngine.java index ed7910e5a..d87f8e405 100644 --- a/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/HardwareProfileCloudEngine.java +++ b/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/HardwareProfileCloudEngine.java @@ -32,7 +32,8 @@ import org.slf4j.Logger; /** - * Engine that takes the JSON response from the {@link CloudRequestEngine} and + * Engine that takes the JSON response from the + * {@link fiftyone.pipeline.cloudrequestengine.flowelements.CloudRequestEngine} and * uses it to populate a {@link MultiIPIDataCloud} instance for easier * consumption. * @see Specification @@ -40,6 +41,12 @@ public class HardwareProfileCloudEngine extends PropertyKeyedCloudEngineBase { + /** + * Create a new instance. + * + * @param logger used for logging + * @param aspectDataFactory creates the element data this engine returns + */ public HardwareProfileCloudEngine( Logger logger, ElementDataFactory aspectDataFactory) { diff --git a/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/HardwareProfileCloudEngineBuilder.java b/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/HardwareProfileCloudEngineBuilder.java index eaf1fabe9..660db55e2 100644 --- a/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/HardwareProfileCloudEngineBuilder.java +++ b/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/HardwareProfileCloudEngineBuilder.java @@ -35,16 +35,28 @@ import java.util.List; +/** Builder for the {@link HardwareProfileCloudEngine}. */ @ElementBuilder public class HardwareProfileCloudEngineBuilder extends AspectEngineBuilderBase< HardwareProfileCloudEngineBuilder, HardwareProfileCloudEngine> { private final ILoggerFactory loggerFactory; + /** + * Create a new builder. + * + * @param loggerFactory creates the loggers the engine uses + */ public HardwareProfileCloudEngineBuilder(ILoggerFactory loggerFactory) { this.loggerFactory = loggerFactory; } + /** + * Build an engine using the current options. + * + * @return a new engine + * @throws Exception if the engine could not be created + */ public HardwareProfileCloudEngine build() throws Exception { return buildEngine(); } diff --git a/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/IPIntelligenceCloudEngineBuilder.java b/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/IPIntelligenceCloudEngineBuilder.java index cf0297c90..f053c2cdf 100644 --- a/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/IPIntelligenceCloudEngineBuilder.java +++ b/ip-intelligence/ip-intelligence.cloud/src/main/java/fiftyone/ipintelligence/cloud/flowelements/IPIntelligenceCloudEngineBuilder.java @@ -61,6 +61,7 @@ protected IPIntelligenceCloudEngine newEngine(List properties) { /** * Build an engine using the current options. * @return new instance + * @throws Exception if the engine could not be created */ public IPIntelligenceCloudEngine build() throws Exception { return buildEngine(); diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/pom.xml b/ip-intelligence/ip-intelligence.engine.on-premise/pom.xml index da9985ff0..06488f8b3 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/pom.xml +++ b/ip-intelligence/ip-intelligence.engine.on-premise/pom.xml @@ -150,6 +150,19 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + + + + -Xdoclint/package:-fiftyone.ipintelligence.engine.onpremise.interop.swig + + + diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/Enums.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/Enums.java index 4acf48bde..b288c1d4d 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/Enums.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/Enums.java @@ -22,14 +22,23 @@ package fiftyone.ipintelligence.engine.onpremise; +/** Enumerations used by the on-premise engine. */ public class Enums { + /** Create a new instance. */ + public Enums() { + } + /** * Enumeration of possible match methods used by the Hash engine. */ public enum MatchMethods { + /** No hash nodes were matched. */ NONE, + /** Every match came from the performance graph. */ PERFORMANCE, + /** Matches came from both the performance and predictive graphs. */ COMBINED, + /** Every match came from the predictive graph. */ PREDICTIVE } } \ No newline at end of file diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ComponentMetaDataIPI.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ComponentMetaDataIPI.java index 528e1d737..ef26e7bbc 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ComponentMetaDataIPI.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ComponentMetaDataIPI.java @@ -111,6 +111,12 @@ public boolean equals(Object obj) { return super.equals(obj); } + /** + * Whether this component has the same id as another. + * + * @param other the component to compare with + * @return true if the ids are equal + */ public boolean equals(ComponentMetaData other) { return getComponentId() == other.getComponentId(); } diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ProfileMetaDataIPI.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ProfileMetaDataIPI.java index 3f2645723..624ac919d 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ProfileMetaDataIPI.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ProfileMetaDataIPI.java @@ -165,6 +165,12 @@ public boolean equals(Object obj) { return super.equals(obj); } + /** + * Whether this profile has the same id as another. + * + * @param other the profile to compare with + * @return true if the ids are equal + */ public boolean equals(ProfileMetaData other) { return getProfileId() == other.getProfileId(); } diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/PropertyMetaDataIPI.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/PropertyMetaDataIPI.java index bcd58b4de..8e4c025ea 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/PropertyMetaDataIPI.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/PropertyMetaDataIPI.java @@ -241,10 +241,22 @@ public boolean equals(Object obj) { return super.equals(obj); } + /** + * Whether this property has the same name as another. + * + * @param other the property to compare with + * @return true if the names are equal + */ public boolean equals(FiftyOneAspectPropertyMetaData other) { return getName().equals(other.getName()); } + /** + * Whether this property has the given name. + * + * @param other the name to compare with + * @return true if the names are equal + */ public boolean equals(String other) { return getName().equals(other); } diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ValueMetaDataIPI.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ValueMetaDataIPI.java index 7ccb3f271..36db52ef6 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ValueMetaDataIPI.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/data/ValueMetaDataIPI.java @@ -86,6 +86,12 @@ public boolean equals(Object obj) { return super.equals(obj); } + /** + * Whether this value has the same property and name as another. + * + * @param other the value to compare with + * @return true if both are equal + */ public boolean equals(ValueMetaData other) { return getProperty().equals(other.getProperty()) && getName().equals(other.getName()); diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceDataHashDefault.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceDataHashDefault.java index b2b6cfcf0..52fe073c4 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceDataHashDefault.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceDataHashDefault.java @@ -43,6 +43,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; @@ -161,9 +162,15 @@ protected boolean propertyIsAvailable(String propertyName) { return false; } + /** + * Sets the result to the weighted values of a native list, or to its no + * value message. The native list and the value holding it are freed with + * the close methods given, whose native types throw no checked + * exception, unlike AutoCloseable's close(). + */ private static < - TListValueSwig extends AutoCloseable, - TListSwig extends AutoCloseable & List, + TListValueSwig, + TListSwig extends List, TWeightedValueSwig, TElement> void populateWeightedValues( @@ -172,22 +179,56 @@ void populateWeightedValues( Predicate listValueSwigHasValue, Function listValueSwigGetNoValueMessage, Function listSwigExtractor, - Function elementConverter) { - try (TListValueSwig listValueSwig = listValueSwigSupplier.get()) - { + Function elementConverter, + Consumer listValueSwigClose, + Consumer listSwigClose) { + useAndClose(listValueSwigSupplier.get(), listValueSwig -> { if (listValueSwigHasValue.test(listValueSwig)) { - try (TListSwig listSwig = listSwigExtractor.apply(listValueSwig)) { + useAndClose(listSwigExtractor.apply(listValueSwig), listSwig -> { List convertedWeightedElements = listSwig.stream() .map(elementConverter) .collect(Collectors.toList()); result.setValue(Collections.unmodifiableList(convertedWeightedElements)); - } + }, listSwigClose); } else { result.setNoValueMessage(listValueSwigGetNoValueMessage.apply(listValueSwig)); } - } catch (Exception e) { - throw new RuntimeException(e); + }, listValueSwigClose); + } + + /** + * Passes a native object to the action and then closes it, as a + * try-with-resources statement does. A null object is not closed, and + * when the action throws, an exception from the close is added to the + * action's exception as suppressed rather than replacing it. + * @param resource the native object, or null + * @param action what to do with the object + * @param close how to close the object + * @param the type of the native object + */ + static void useAndClose( + T resource, + Consumer action, + Consumer close) { + Throwable primary = null; + try { + action.accept(resource); + } catch (Throwable t) { + primary = t; + throw t; + } finally { + if (resource != null) { + if (primary != null) { + try { + close.accept(resource); + } catch (Throwable suppressed) { + primary.addSuppressed(suppressed); + } + } else { + close.accept(resource); + } + } } } @@ -230,7 +271,9 @@ private AspectPropertyValue> readValues(String propertyName, WeightedBoolListValueSwig::hasValue, WeightedBoolListValueSwig::getNoValueMessage, WeightedBoolListValueSwig::getValue, - x -> new WeightedValue<>(x.getShortRawWeight(), x.getValue()) + x -> new WeightedValue<>(x.getShortRawWeight(), x.getValue()), + WeightedBoolListValueSwig::close, + WeightedBoolListSwig::close ); } else if (valueType.equals(Double.class)) { populateWeightedValues( @@ -241,7 +284,9 @@ private AspectPropertyValue> readValues(String propertyName, WeightedDoubleListValueSwig::hasValue, WeightedDoubleListValueSwig::getNoValueMessage, WeightedDoubleListValueSwig::getValue, - x -> new WeightedValue<>(x.getShortRawWeight(), x.getValue()) + x -> new WeightedValue<>(x.getShortRawWeight(), x.getValue()), + WeightedDoubleListValueSwig::close, + WeightedDoubleListSwig::close ); } else if (valueType.equals(Float.class)) { populateWeightedValues( @@ -252,7 +297,9 @@ private AspectPropertyValue> readValues(String propertyName, WeightedDoubleListValueSwig::hasValue, WeightedDoubleListValueSwig::getNoValueMessage, WeightedDoubleListValueSwig::getValue, - x -> new WeightedValue<>(x.getShortRawWeight(), (float)x.getValue()) + x -> new WeightedValue<>(x.getShortRawWeight(), (float)x.getValue()), + WeightedDoubleListValueSwig::close, + WeightedDoubleListSwig::close ); } else if (valueType.equals(Integer.class)) { populateWeightedValues( @@ -263,7 +310,9 @@ private AspectPropertyValue> readValues(String propertyName, WeightedIntListValueSwig::hasValue, WeightedIntListValueSwig::getNoValueMessage, WeightedIntListValueSwig::getValue, - x -> new WeightedValue<>(x.getShortRawWeight(), x.getValue()) + x -> new WeightedValue<>(x.getShortRawWeight(), x.getValue()), + WeightedIntListValueSwig::close, + WeightedIntListSwig::close ); } else if (valueType.equals(InetAddress.class) || valueType.equals(Inet4Address.class) @@ -282,7 +331,9 @@ private AspectPropertyValue> readValues(String propertyName, } catch (UnknownHostException e) { throw new RuntimeException(e); } - } + }, + WeightedStringListValueSwig::close, + WeightedStringListSwig::close ); } else if (valueType.equals(String.class)) { populateWeightedValues( @@ -303,7 +354,9 @@ private AspectPropertyValue> readValues(String propertyName, theString = new String(bytes, StandardCharsets.UTF_8); } return new WeightedValue<>(x.getShortRawWeight(), theString); - } + }, + WeightedUTF8StringListValueSwig::close, + WeightedUTF8StringListSwig::close ); } else { throw new IllegalArgumentException("Unsupported value type: " + valueType.getName()); diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceOnPremiseEngineBuilder.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceOnPremiseEngineBuilder.java index cd7a9010e..43ea77674 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceOnPremiseEngineBuilder.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceOnPremiseEngineBuilder.java @@ -190,7 +190,8 @@ public IPIntelligenceOnPremiseEngineBuilder setPerformanceProfile( /** * Provide a hint as to how many threads will access the pipeline simultaneously *

- * Default is the result of {@link Runtime#getRuntime()#getAvailableProcessors()} + * Default is the result of + * {@code Runtime.getRuntime().availableProcessors()} * @see Concurrent processing * @param concurrency expected concurrent accesses * @return this builder diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ComponentIterable.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ComponentIterable.java index a4b1627e6..e43e05f5c 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ComponentIterable.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ComponentIterable.java @@ -58,7 +58,7 @@ protected ComponentMetaData get(long index) { } @Override - public void close() throws Exception { + public void close() { collection.delete(); } } diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/Constants.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/Constants.java index 7c09eb920..e3fe9cfba 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/Constants.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/Constants.java @@ -22,7 +22,12 @@ package fiftyone.ipintelligence.engine.onpremise.interop; +/** Messages used when the native library cannot be loaded. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } + private static final String USE_PACKAGE_MANAGER = "use your Linux " + "package manager to install it on your system. If this is not " + diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ProfileIterable.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ProfileIterable.java index 0aea340e7..6d9f882c2 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ProfileIterable.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ProfileIterable.java @@ -58,7 +58,7 @@ protected ProfileMetaData get(long index) { } @Override - public void close() throws Exception { + public void close() { collection.delete(); } } \ No newline at end of file diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/PropertyIterable.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/PropertyIterable.java index e2294565d..20445ce1e 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/PropertyIterable.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/PropertyIterable.java @@ -44,6 +44,7 @@ public class PropertyIterable /** * Create a new instance. * @param engine the engine which the meta data relates to + * @param list holds the properties once they have been read * @param collection the native collection of properties */ public PropertyIterable( @@ -61,7 +62,7 @@ protected FiftyOneAspectPropertyMetaData get(long index) { } @Override - public void close() throws Exception { + public void close() { collection.delete(); } } \ No newline at end of file diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/Swig.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/Swig.java index d24342f0a..db309ea28 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/Swig.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/Swig.java @@ -34,6 +34,10 @@ * Static methods to help interoperability through the SWIG layer to C++. */ public class Swig { + /** Create a new instance. */ + public Swig() { + } + /** * Copy the values in the native string vector to a {@link List}. * @param vector native instance to copy diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ValueIterable.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ValueIterable.java index d21675b23..095f98792 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ValueIterable.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/main/java/fiftyone/ipintelligence/engine/onpremise/interop/ValueIterable.java @@ -58,7 +58,7 @@ protected ValueMetaData get(long index) { } @Override - public void close() throws Exception { + public void close() { collection.delete(); } } \ No newline at end of file diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/test/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceDataTests.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/test/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceDataTests.java index 161a3ce1f..8aa68aa3a 100644 --- a/ip-intelligence/ip-intelligence.engine.on-premise/src/test/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceDataTests.java +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/test/java/fiftyone/ipintelligence/engine/onpremise/flowelements/IPIntelligenceDataTests.java @@ -70,6 +70,7 @@ public void cleanup() { */ @Test public void IPIData_ResultsClose() throws Exception { + ResultsIpiSwig results = mock(ResultsIpiSwig.class); try (FlowData flowData = getWrapper().getPipeline().createFlowData()) { IPIntelligenceDataHashDefault data = new IPIntelligenceDataHashDefault( logger, @@ -77,14 +78,12 @@ public void IPIData_ResultsClose() throws Exception { getWrapper().getEngine(), missingPropertyService); - ResultsIpiSwig results = mock(ResultsIpiSwig.class); data.setResults(results); flowData.getOrAdd( getWrapper().getEngine().getTypedDataKey(), arg -> data); - flowData.close(); - verify(results, times(1)).close(); - } + } + verify(results, times(1)).close(); } /** diff --git a/ip-intelligence/ip-intelligence.engine.on-premise/src/test/java/fiftyone/ipintelligence/engine/onpremise/flowelements/UseAndCloseTests.java b/ip-intelligence/ip-intelligence.engine.on-premise/src/test/java/fiftyone/ipintelligence/engine/onpremise/flowelements/UseAndCloseTests.java new file mode 100644 index 000000000..d1d90404b --- /dev/null +++ b/ip-intelligence/ip-intelligence.engine.on-premise/src/test/java/fiftyone/ipintelligence/engine/onpremise/flowelements/UseAndCloseTests.java @@ -0,0 +1,89 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.ipintelligence.engine.onpremise.flowelements; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +/** + * The native lists of weighted values are closed as a try-with-resources + * statement closes its resources. + */ +public class UseAndCloseTests { + + @Test + public void actionSucceeds_ClosesOnce() { + List closed = new ArrayList<>(); + IPIntelligenceDataHashDefault.useAndClose( + "native", r -> { }, closed::add); + assertEquals(1, closed.size()); + assertEquals("native", closed.get(0)); + } + + @Test + public void nullResource_IsNotClosed() { + List closed = new ArrayList<>(); + IPIntelligenceDataHashDefault.useAndClose( + null, r -> { }, closed::add); + assertEquals(0, closed.size()); + } + + @Test + public void actionAndCloseThrow_CloseIsSuppressed() { + IllegalStateException action = new IllegalStateException("action"); + IllegalArgumentException close = + new IllegalArgumentException("close"); + try { + IPIntelligenceDataHashDefault.useAndClose( + "native", + r -> { throw action; }, + r -> { throw close; }); + fail("The action's exception was not thrown"); + } catch (IllegalStateException e) { + assertSame(action, e); + assertEquals(1, e.getSuppressed().length); + assertSame(close, e.getSuppressed()[0]); + } + } + + @Test + public void onlyCloseThrows_CloseIsThrown() { + IllegalArgumentException close = + new IllegalArgumentException("close"); + try { + IPIntelligenceDataHashDefault.useAndClose( + "native", + r -> { }, + r -> { throw close; }); + fail("The close's exception was not thrown"); + } catch (IllegalArgumentException e) { + assertSame(close, e); + } + } +} diff --git a/ip-intelligence/ip-intelligence.shared/pom.xml b/ip-intelligence/ip-intelligence.shared/pom.xml index 3f2271d0a..8f1485cc1 100644 --- a/ip-intelligence/ip-intelligence.shared/pom.xml +++ b/ip-intelligence/ip-intelligence.shared/pom.xml @@ -43,6 +43,18 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + + + all,-missing + + diff --git a/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/Constants.java b/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/Constants.java index 22e7ee9a7..c6bbbd9f0 100644 --- a/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/Constants.java +++ b/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/Constants.java @@ -25,6 +25,7 @@ import static fiftyone.pipeline.core.Constants.EVIDENCE_QUERY_PREFIX; import static fiftyone.pipeline.core.Constants.EVIDENCE_SEPERATOR; +/** Evidence keys and other constants shared by the IP Intelligence engines. */ public class Constants { /** diff --git a/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/IPIntelligenceDataBaseOnPremise.java b/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/IPIntelligenceDataBaseOnPremise.java index 8a043be37..fb97aac9a 100644 --- a/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/IPIntelligenceDataBaseOnPremise.java +++ b/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/IPIntelligenceDataBaseOnPremise.java @@ -59,6 +59,10 @@ public abstract class IPIntelligenceDataBaseOnPremise extends IPIntelligenceDataBase implements ProvidesValuesAsString { + /** + * Maps each primitive type to its boxed type, used when converting native + * values. + */ protected final Map, Class> primitiveTypes; private final Object dataLock = new Object(); private final Object getLock = new Object(); diff --git a/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/testhelpers/FileUtils.java b/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/testhelpers/FileUtils.java index e9fd65796..52f6b0419 100644 --- a/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/testhelpers/FileUtils.java +++ b/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/testhelpers/FileUtils.java @@ -36,6 +36,7 @@ import static fiftyone.pipeline.util.FileFinder.getFilePath; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; +/** Finds the data and evidence files the tests use. */ @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public class FileUtils { /** @@ -45,11 +46,18 @@ public class FileUtils { */ public static final String IPI_PATH_VARIABLE = "_51DEGREES_IPI_PATH"; + /** + * Name of an Enterprise data file, searched for when + * {@link #ENTERPRISE_IPI_V41_DATA_FILE_NAME} is not found. + */ public static final String ENTERPRISE_IPI_DATA_FILE_NAME = "Enterprise-IpIntelligenceV41.ipi"; + /** Name of the Enterprise data file, searched for first. */ public static final String ENTERPRISE_IPI_V41_DATA_FILE_NAME = "51Degrees-EnterpriseIpiV41.ipi"; + /** Name of the free Lite data file. */ public static final String LITE_IPI_DATA_FILE_NAME = "51Degrees-LiteV41.ipi"; private static Optional IPI_DATA_FILE; + /** Name of the evidence file the tests use. */ public static final String EVIDENCE_FILE_NAME = "evidence.yml"; private static Optional EVIDENCE_FILE; @@ -127,6 +135,12 @@ private static String environmentOrProperty(String name) { return Objects.isNull(value) || value.isEmpty() ? null : value; } + /** + * Find the evidence file the tests use, searching once and keeping the + * result. + * + * @return the file, or null if it was not found + */ public static File getEvidenceFile() { if (Objects.nonNull(EVIDENCE_FILE)) { return EVIDENCE_FILE.orElse(null); diff --git a/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/testhelpers/KeyUtils.java b/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/testhelpers/KeyUtils.java index 78cea3329..e90bd348d 100644 --- a/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/testhelpers/KeyUtils.java +++ b/ip-intelligence/ip-intelligence.shared/src/main/java/fiftyone/ipintelligence/shared/testhelpers/KeyUtils.java @@ -51,6 +51,8 @@ public static String getResourceKey() { /** * Obtain a key from the environment variable of the name given, or * from the system property of the same name when that is not set. + * @param keyName name of the environment variable and system property + * @return the key, or null when neither is set */ public static String getNamedKey(String keyName) { return getNamedKey(keyName, System::getenv); diff --git a/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/Enums.java b/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/Enums.java index 722016308..1e32a0be5 100644 --- a/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/Enums.java +++ b/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/Enums.java @@ -27,8 +27,15 @@ */ @Deprecated public class Enums { + /** Create a new instance. */ + public Enums() { + } + + /** The detection algorithms an engine can use. */ public enum IPIntelligenceAlgorithm { + /** The Hash algorithm. */ Hash, + /** Not supported by any engine. */ Pattern } } diff --git a/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligenceCloudPipelineBuilder.java b/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligenceCloudPipelineBuilder.java index 1706cc0ee..6913f8d60 100644 --- a/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligenceCloudPipelineBuilder.java +++ b/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligenceCloudPipelineBuilder.java @@ -45,8 +45,9 @@ public class IPIntelligenceCloudPipelineBuilder * Internal Constructor. * This builder should only be created through the * IPIntelligencePipelineBuilder - * @param loggerFactory - * @param httpClient + * @param loggerFactory creates the loggers for the Pipeline and its + * elements + * @param httpClient used to make requests to the cloud service */ public IPIntelligenceCloudPipelineBuilder( ILoggerFactory loggerFactory, @@ -60,7 +61,7 @@ public IPIntelligenceCloudPipelineBuilder( * @return A new pipeline instance that contains a cloud request engine for * making requests to the 51Degrees Cloud service and a * IPIntelligenceCloudEngine to interpret the IP Intelligence results. - * @throws Exception + * @throws Exception if the Pipeline could not be built */ @Override public Pipeline build() throws Exception { diff --git a/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligenceOnPremisePipelineBuilder.java b/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligenceOnPremisePipelineBuilder.java index 52f455e39..26017cfcf 100644 --- a/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligenceOnPremisePipelineBuilder.java +++ b/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligenceOnPremisePipelineBuilder.java @@ -49,6 +49,7 @@ public class IPIntelligenceOnPremisePipelineBuilder extends PrePackagedPipelineBuilderBase { + /** Whether the Pipeline shares usage data with 51Degrees. */ protected boolean shareUsageEnabled = fiftyone.pipeline.engines.fiftyone.flowelements.Constants .SHARE_USAGE_DEFAULT_ENABLED; diff --git a/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligencePipelineBuilder.java b/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligencePipelineBuilder.java index c71e48141..539699a5e 100644 --- a/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligencePipelineBuilder.java +++ b/ip-intelligence/ip-intelligence/src/main/java/fiftyone/ipintelligence/IPIntelligencePipelineBuilder.java @@ -34,6 +34,7 @@ */ public class IPIntelligencePipelineBuilder { + /** Creates the loggers for the Pipeline and its elements. */ protected final ILoggerFactory loggerFactory; private final DataUpdateService dataUpdateService; private final HttpClient httpClient; diff --git a/ip-intelligence/ip-intelligence/src/test/java/fiftyone/ipintelligence/IPIntelligenceOnPremisePipelineBuilderTest.java b/ip-intelligence/ip-intelligence/src/test/java/fiftyone/ipintelligence/IPIntelligenceOnPremisePipelineBuilderTest.java index 737c81db7..c35826357 100644 --- a/ip-intelligence/ip-intelligence/src/test/java/fiftyone/ipintelligence/IPIntelligenceOnPremisePipelineBuilderTest.java +++ b/ip-intelligence/ip-intelligence/src/test/java/fiftyone/ipintelligence/IPIntelligenceOnPremisePipelineBuilderTest.java @@ -170,13 +170,13 @@ public void setDataFileSystemWatcher_PropertyPropagatedToDataFileConfiguration() @Test public void setDataUpdateService_RegisterDataFileTriggered() throws Exception { DataUpdateServiceDefault dataUpdateServiceDefault = mock(DataUpdateServiceDefault.class); - try (Pipeline ignored = builder - .setAutoUpdate(true) - .setDataUpdateLicenseKey("licence_key") - .setDataUpdateService(dataUpdateServiceDefault) - .build()) { - verify(dataUpdateServiceDefault).registerDataFile(any()); - } + builder + .setAutoUpdate(true) + .setDataUpdateLicenseKey("licence_key") + .setDataUpdateService(dataUpdateServiceDefault) + .build() + .close(); + verify(dataUpdateServiceDefault).registerDataFile(any()); } @Test diff --git a/ip-intelligence/pom.xml b/ip-intelligence/pom.xml index 26c5b0eba..b41b20f64 100644 --- a/ip-intelligence/pom.xml +++ b/ip-intelligence/pom.xml @@ -137,7 +137,7 @@ ${maven.compiler.target} true - -Xlint:all,-try,-options + -Xlint:all -Werror @@ -275,8 +275,11 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - none - true + + all + true false @@ -405,4 +408,21 @@ scm:git:https://github.com/51Degrees/51degrees-java.git scm:git:https://github.com/51Degrees/51degrees-java.git + + + + + release-8 + + [9,) + + + 8 + + + diff --git a/location/geo-location.cloud/src/main/java/fiftyone/geolocation/data/CloudGeoDataDefault.java b/location/geo-location.cloud/src/main/java/fiftyone/geolocation/data/CloudGeoDataDefault.java index f6080b94c..345e2feb0 100644 --- a/location/geo-location.cloud/src/main/java/fiftyone/geolocation/data/CloudGeoDataDefault.java +++ b/location/geo-location.cloud/src/main/java/fiftyone/geolocation/data/CloudGeoDataDefault.java @@ -38,6 +38,14 @@ */ public class CloudGeoDataDefault extends GeoDataDefault implements CloudGeoData { + /** + * Create a new instance. + * + * @param logger used for logging + * @param flowData the Flow Data this element data belongs to + * @param engine the engine which created the instance + * @param missingPropertyService explains why a property has no value + */ public CloudGeoDataDefault(Logger logger, FlowData flowData, AspectEngine engine, MissingPropertyService missingPropertyService) { super(logger, flowData, engine, missingPropertyService); } diff --git a/location/geo-location.cloud/src/main/java/fiftyone/geolocation/flowelements/GeoLocationCloudEngine.java b/location/geo-location.cloud/src/main/java/fiftyone/geolocation/flowelements/GeoLocationCloudEngine.java index 8bec6d6f0..c501f8f87 100644 --- a/location/geo-location.cloud/src/main/java/fiftyone/geolocation/flowelements/GeoLocationCloudEngine.java +++ b/location/geo-location.cloud/src/main/java/fiftyone/geolocation/flowelements/GeoLocationCloudEngine.java @@ -48,6 +48,10 @@ import java.util.*; import org.json.JSONArray; +/** + * Engine that reads the location results from the response of the Cloud Request + * Engine. + */ public class GeoLocationCloudEngine extends CloudAspectEngineBase { private CloudRequestEngine cloudRequestEngine = null; @@ -108,10 +112,22 @@ public String getElementDataKey() { return elementDataKey; } + /** + * The prefix the cloud service gives the properties of the chosen provider. + * + * @return the provider's property prefix + */ public String getDataProviderPrefix() { return dataProviderPrefix; } + /** + * Create a new instance. + * + * @param logger used for logging + * @param aspectDataFactory creates the element data this engine returns + * @param provider the location data provider whose results the engine reads + */ public GeoLocationCloudEngine( Logger logger, ElementDataFactory aspectDataFactory, @@ -194,6 +210,13 @@ protected void processEngine(FlowData data, CloudGeoData aspectData) { } } + /** + * Get the reason the response gives for a property having no value. + * + * @param jsonObj the JSON object holding the property + * @param key the property name + * @return the reason, or null if the response gives none + */ public static Object tryToGet(JSONObject jsonObj, String key) { return jsonObj.opt(key + "nullreason"); } diff --git a/location/geo-location.cloud/src/main/java/fiftyone/geolocation/flowelements/GeoLocationCloudEngineBuilder.java b/location/geo-location.cloud/src/main/java/fiftyone/geolocation/flowelements/GeoLocationCloudEngineBuilder.java index 82143dd1a..4233e4e78 100644 --- a/location/geo-location.cloud/src/main/java/fiftyone/geolocation/flowelements/GeoLocationCloudEngineBuilder.java +++ b/location/geo-location.cloud/src/main/java/fiftyone/geolocation/flowelements/GeoLocationCloudEngineBuilder.java @@ -37,6 +37,7 @@ import java.util.List; +/** Builder for the {@link GeoLocationCloudEngine}. */ @ElementBuilder(alternateName = "CloudGeoLocation") public class GeoLocationCloudEngineBuilder extends CloudAspectEngineBuilderBase< GeoLocationCloudEngineBuilder, @@ -45,19 +46,44 @@ public class GeoLocationCloudEngineBuilder extends CloudAspectEngineBuilderBase< private CloudRequestEngine requestEngine; private Enums.GeoLocationProvider provider; + /** + * Create a new builder. + * + * @param loggerFactory creates the loggers the engine uses + */ public GeoLocationCloudEngineBuilder(ILoggerFactory loggerFactory) { super(loggerFactory); } + /** + * Set the location data provider by name. + * + * @param provider name of a {@link Enums.GeoLocationProvider} value + * @return this builder + * @throws Exception if the name is not a provider + */ public GeoLocationCloudEngineBuilder setGeoLocationProvider(String provider) throws Exception { this.provider = Enums.GeoLocationProvider.valueOf(provider); return this; } + /** + * Build an engine using the current options. + * + * @return a new engine + * @throws Exception if the engine could not be created + */ public GeoLocationCloudEngine build() throws Exception { return buildEngine(); } + /** + * Build an engine for the provider given. + * + * @param provider the location data provider + * @return a new engine + * @throws Exception if the engine could not be created + */ public GeoLocationCloudEngine build(Enums.GeoLocationProvider provider) throws Exception { this.provider = provider; return buildEngine(); diff --git a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/Constants.java b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/Constants.java index 4a8f4a1b7..8e4e829c0 100644 --- a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/Constants.java +++ b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/Constants.java @@ -27,16 +27,33 @@ import java.util.Arrays; +/** Evidence keys and messages used by the location engines. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } + + /** Evidence key for the latitude. */ public static final String EVIDENCE_GEO_LAT_KEY = "location.latitude"; + /** Evidence key for the longitude. */ public static final String EVIDENCE_GEO_LON_KEY = "location.longitude"; + /** Name of the cookie the client-side JavaScript sets to the latitude. */ public static final String EVIDENCE_GEO_LAT_COOKIE_NAME = "51D_Pos_latitude"; + /** Name of the cookie the client-side JavaScript sets to the longitude. */ public static final String EVIDENCE_GEO_LON_COOKIE_NAME = "51D_Pos_longitude"; + /** Evidence key for the latitude cookie. */ public static final String EVIDENCE_GEO_LAT_COOKIE_KEY = "cookie." + EVIDENCE_GEO_LAT_COOKIE_NAME; + /** Evidence key for the longitude cookie. */ public static final String EVIDENCE_GEO_LON_COOKIE_KEY = "cookie." + EVIDENCE_GEO_LON_COOKIE_NAME; + /** Evidence key for the latitude in the query string. */ public static final String EVIDENCE_GEO_LAT_PARAM_KEY = "query." + EVIDENCE_GEO_LAT_COOKIE_NAME; + /** Evidence key for the longitude in the query string. */ public static final String EVIDENCE_GEO_LON_PARAM_KEY = "query." + EVIDENCE_GEO_LON_COOKIE_NAME; + /** + * Accepts the client IP address and every latitude and longitude key, + * ignoring case. + */ public static final EvidenceKeyFilter DefaultGeoEvidenceKeyFilter = new EvidenceKeyFilterWhitelist(Arrays.asList( fiftyone.pipeline.core.Constants.EVIDENCE_CLIENTIP_KEY, @@ -48,6 +65,10 @@ public class Constants { Constants.EVIDENCE_GEO_LON_PARAM_KEY), String.CASE_INSENSITIVE_ORDER); + /** + * Explains why a property has no value before the client has sent its + * position. + */ public static final String NO_EVIDENCE_MESSAGE = "This property requires evidence" + " values from JavaScript running on the client. It cannot be" + " populated until a future request is made that contains this" + diff --git a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/Enums.java b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/Enums.java index e649bcd34..cf79158b0 100644 --- a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/Enums.java +++ b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/Enums.java @@ -22,9 +22,17 @@ package fiftyone.geolocation.core; +/** Enumerations used by the location engines. */ public class Enums { + /** Create a new instance. */ + public Enums() { + } + + /** The providers of location data. */ public enum GeoLocationProvider { + /** Location data from 51Degrees. */ FiftyOneDegrees, + /** Location data from Digital Element. */ DigitalElement } } diff --git a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/GeoEngineHelper.java b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/GeoEngineHelper.java index a9c122bc0..eb1d97751 100644 --- a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/GeoEngineHelper.java +++ b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/GeoEngineHelper.java @@ -42,10 +42,18 @@ * different engine base class functionality. */ public class GeoEngineHelper { + /** Create a new instance. */ + public GeoEngineHelper() { + } + /** * The result of a call to performGeoLookup. */ public static class GeoLookupResult { + /** Create a new instance. */ + public GeoLookupResult() { + } + /** * The raw string response from the geo-location web service. * If the FlowData does not contain the required evidence then the @@ -101,6 +109,7 @@ private static boolean tryAddCoordinates( * web service. * If not, it will contain the JavaScript to run on the client * device in order to supply the required evidence. + * @throws IOException if the request to the web service fails */ public static GeoLookupResult performGeoLookup( FlowData data, diff --git a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/JavaScriptResource.java b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/JavaScriptResource.java index 0774df491..ac264b2d8 100644 --- a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/JavaScriptResource.java +++ b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/JavaScriptResource.java @@ -22,7 +22,15 @@ package fiftyone.geolocation.core; +/** + * Holds the JavaScript that asks the browser for its position and stores it in + * cookies. + */ public class JavaScriptResource { + /** Create a new instance. */ + public JavaScriptResource() { + } + private static final String javaScript = "if (navigator.geolocation) {\n" + "\tnavigator.geolocation.getCurrentPosition(function(pos) {\n" + @@ -36,6 +44,11 @@ public class JavaScriptResource { " });\n" + "}\n"; + /** + * Get the JavaScript that sends the position. + * + * @return the JavaScript source + */ public static String getJavaScript() { return javaScript; } diff --git a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/RequestFormatter.java b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/RequestFormatter.java index a5ce3b7b9..b3710e5c4 100644 --- a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/RequestFormatter.java +++ b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/RequestFormatter.java @@ -27,6 +27,14 @@ import java.net.MalformedURLException; import java.net.URL; +/** Creates the URL of a request to a location web service. */ public interface RequestFormatter { + /** + * Create the URL for the evidence given. + * + * @param evidence the position or IP address to look up + * @return the URL to request + * @throws MalformedURLException if the URL is not valid + */ URL format(GeoEvidence evidence) throws MalformedURLException; } diff --git a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoData.java b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoData.java index e10b50f64..8114390f5 100644 --- a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoData.java +++ b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoData.java @@ -26,49 +26,200 @@ import fiftyone.pipeline.engines.data.AspectData; import fiftyone.pipeline.engines.data.AspectPropertyValue; +/** The location results an engine returns for the evidence it was given. */ public interface GeoData extends AspectData { + /** + * The JavaScript that sends the position from the client. + * + * @return the JavaScript that sends the position from the client + */ AspectPropertyValue getJavaScript(); + /** + * Set the JavaScript that sends the position from the client. + * + * @param javaScript the JavaScript that sends the position from the client + */ void setJavaScript(AspectPropertyValue javaScript); + /** + * The road name. + * + * @return the road name + */ AspectPropertyValue getRoad(); + /** + * Set the road name. + * + * @param road the road name + */ void setRoad(AspectPropertyValue road); + /** + * The town name. + * + * @return the town name + */ AspectPropertyValue getTown(); + /** + * Set the town name. + * + * @param town the town name + */ void setTown(AspectPropertyValue town); + /** + * The suburb name. + * + * @return the suburb name + */ AspectPropertyValue getSuburb(); + /** + * Set the suburb name. + * + * @param suburb the suburb name + */ void setSuburb(AspectPropertyValue suburb); + /** + * The county name. + * + * @return the county name + */ AspectPropertyValue getCounty(); + /** + * Set the county name. + * + * @param county the county name + */ void setCounty(AspectPropertyValue county); + /** + * The region name. + * + * @return the region name + */ AspectPropertyValue getRegion(); + /** + * Set the region name. + * + * @param region the region name + */ void setRegion(AspectPropertyValue region); + /** + * The state name. + * + * @return the state name + */ AspectPropertyValue getState(); + /** + * Set the state name. + * + * @param state the state name + */ void setState(AspectPropertyValue state); + /** + * The zip or postal code. + * + * @return the zip or postal code + */ AspectPropertyValue getZipCode(); + /** + * Set the zip or postal code. + * + * @param zipCode the zip or postal code + */ void setZipCode(AspectPropertyValue zipCode); + /** + * The country name. + * + * @return the country name + */ AspectPropertyValue getCountry(); + /** + * Set the country name. + * + * @param country the country name + */ void setCountry(AspectPropertyValue country); + /** + * The two letter country code. + * + * @return the two letter country code + */ AspectPropertyValue getCountryCode(); + /** + * Set the two letter country code. + * + * @param countryCode the two letter country code + */ void setCountryCode(AspectPropertyValue countryCode); + /** + * The three letter country code. + * + * @return the three letter country code + */ AspectPropertyValue getCountryCode3(); + /** + * Set the three letter country code. + * + * @param countryCode3 the three letter country code + */ void setCountryCode3(AspectPropertyValue countryCode3); + /** + * The time zone offset. + * + * @return the time zone offset + */ AspectPropertyValue getTimeZoneOffset(); + /** + * Set the time zone offset. + * + * @param timeZoneOffset the time zone offset + */ void setTimeZoneOffset(AspectPropertyValue timeZoneOffset); + /** + * The full address. + * + * @return the full address + */ AspectPropertyValue getAddress(); + /** + * Set the full address. + * + * @param address the full address + */ void setAddress(AspectPropertyValue address); + /** + * The building name. + * + * @return the building name + */ AspectPropertyValue getBuilding(); + /** + * Set the building name. + * + * @param building the building name + */ void setBuilding(AspectPropertyValue building); + /** + * The street number. + * + * @return the street number + */ AspectPropertyValue getStreetNumber(); + /** + * Set the street number. + * + * @param streetNumber the street number + */ void setStreetNumber(AspectPropertyValue streetNumber); } diff --git a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoDataDefault.java b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoDataDefault.java index cee5eced3..1b3cb27cf 100644 --- a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoDataDefault.java +++ b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoDataDefault.java @@ -33,8 +33,19 @@ import fiftyone.pipeline.engines.services.MissingPropertyService; import org.slf4j.Logger; +/** + * Default implementation of {@link GeoData}, which holds the values in a map. + */ public class GeoDataDefault extends AspectDataBase implements GeoData { + /** + * Create a new instance. + * + * @param logger used for logging + * @param flowData the Flow Data this element data belongs to + * @param engine the engine which created the instance + * @param missingPropertyService explains why a property has no value + */ public GeoDataDefault(Logger logger, FlowData flowData, AspectEngine engine, MissingPropertyService missingPropertyService) { super(logger, flowData, engine, missingPropertyService); setJavaScript(new AspectPropertyValueDefault(new JavaScript(""))); diff --git a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoEvidence.java b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoEvidence.java index 4acaafc47..e7d8d3e52 100644 --- a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoEvidence.java +++ b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/data/GeoEvidence.java @@ -22,26 +22,61 @@ package fiftyone.geolocation.core.data; +/** The position or IP address to look up. */ public class GeoEvidence { + /** Create a new instance. */ + public GeoEvidence() { + } + private String latitude; private String longitude; private String ipAddress; + /** + * The latitude. + * + * @return the latitude + */ public String getLatitude() { return latitude; } + /** + * The longitude. + * + * @return the longitude + */ public String getLongitude() { return longitude; } + /** + * The IP address. + * + * @return the IP address + */ public String getIpAddress() { return ipAddress; } + /** + * Set the latitude. + * + * @param latitude the latitude + */ public void setLatitude(String latitude) { this.latitude = latitude; } + /** + * Set the longitude. + * + * @param longitude the longitude + */ public void setLongitude(String longitude) { this.longitude = longitude; } + /** + * Set the IP address. + * + * @param ipAddress the IP address + */ public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } diff --git a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/test/MavenRunListener.java b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/test/MavenRunListener.java index 99eb7f688..2360851c9 100644 --- a/location/geo-location.core/src/main/java/fiftyone/geolocation/core/test/MavenRunListener.java +++ b/location/geo-location.core/src/main/java/fiftyone/geolocation/core/test/MavenRunListener.java @@ -38,6 +38,10 @@ */ @RunListener.ThreadSafe public class MavenRunListener extends RunListener { + /** Create a new instance. */ + public MavenRunListener() { + } + static Logger logger = LoggerFactory.getLogger(MavenRunListener.class); static Marker marker = MarkerFactory.getMarker("Starting Test"); static Marker endMarker = MarkerFactory.getMarker("Finished Test"); diff --git a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/CombiningServices.java b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/CombiningServices.java index 3db4b6fe6..c982c9bf4 100644 --- a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/CombiningServices.java +++ b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/CombiningServices.java @@ -47,7 +47,7 @@ import static fiftyone.pipeline.core.Constants.EVIDENCE_HEADER_USERAGENT_KEY; /** - * @example CombiningServices.java + * \example CombiningServices.java * * Getting started example of using 51Degrees geo-location alongside 51Degrees * device detection. @@ -110,12 +110,15 @@ * ``` * * 5. Extract the value of a property as a string from the results. - * ``` + *

{@code
  * AspectPropertyValue isMobile = data.get(Device.class).getIsMobile();
  * AspectPropertyValue country = data.get(GeoData.class).getCountry();
- * ```
+ * }
*/ public class CombiningServices { + /** Create a new instance. */ + public CombiningServices() { + } private static ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); @@ -126,6 +129,12 @@ public class CombiningServices { "AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile" + "/11D167 Safari/9537.53"; + /** + * Run the example. + * + * @param args not used + * @throws Exception if the example fails + */ public static void main(String[] args) throws Exception { // Obtain a resource key for free at https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=geo-location.shell.examples-src-main-java-fiftyone-geolocation-examples-combiningservices.java&utm_term=main // Make sure to include the 'Country' and 'IsMobile' properties as they diff --git a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/ExampleBase.java b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/ExampleBase.java index 69365a790..213bdb4b7 100644 --- a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/ExampleBase.java +++ b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/ExampleBase.java @@ -25,10 +25,16 @@ import java.io.PrintWriter; import java.io.StringWriter; +/** Output helpers the examples share. */ public class ExampleBase { private final boolean printOutput; + /** + * Create a new instance. + * + * @param printOutput false to print nothing, for example in tests + */ public ExampleBase(boolean printOutput) { this.printOutput = printOutput; } @@ -41,24 +47,46 @@ private static void addToMessage(StringBuilder message, String textToAdd, int de message.append("\n"); } + /** + * Print text when output is on. + * + * @param string the text + */ protected void print(String string) { if (printOutput) { System.out.print(string); } } + /** + * Print a line when output is on. + * + * @param string the line + */ protected void println(String string) { if (printOutput) { System.out.println(string); } } + /** + * Print formatted text when output is on. + * + * @param format the format string + * @param args the values to format + */ protected void printf(String format, Object... args) { if (printOutput) { System.out.printf(format, args); } } + /** + * Print an exception and its causes when output is on. + * + * @param ex the exception + * @param depth how far to indent the output + */ protected void outputException(Throwable ex, int depth) { StringBuilder message = new StringBuilder(); addToMessage(message, ex.getClass().getSimpleName() + " - " + ex.getMessage(), depth); diff --git a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/cloud/GettingStarted.java b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/cloud/GettingStarted.java index 94a12c08e..ea534e891 100644 --- a/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/cloud/GettingStarted.java +++ b/location/geo-location.shell.examples/src/main/java/fiftyone/geolocation/examples/cloud/GettingStarted.java @@ -39,7 +39,7 @@ import static fiftyone.geolocation.core.Constants.EVIDENCE_GEO_LON_PARAM_KEY; /** - * @example cloud/GettingStarted.java + * \example cloud/GettingStarted.java * * Getting started example of using cloud geo-location. * @@ -72,14 +72,23 @@ * ``` * * 4. Extract the value of a property as a string from the results. - * ``` + *
{@code
  * AspectPropertyValue country = data.get(GeoData.class).getCoutnry();
- * ```
+ * }
*/ public class GettingStarted { + /** Create a new instance. */ + public GettingStarted() { + } private static ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); + /** + * Run the example. + * + * @param args not used + * @throws Exception if the example fails + */ public static void main(String[] args) throws Exception { // Obtain a resource key for free at https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-java&utm_content=geo-location.shell.examples-src-main-java-fiftyone-geolocation-examples-cloud-gettingstarted.java&utm_term=main // Make sure to include the 'Country' property as it is used by this example. diff --git a/location/geo-location.web.examples/geo-location.web.examples.mvc/pom.xml b/location/geo-location.web.examples/geo-location.web.examples.mvc/pom.xml index df23c9a3e..a2e9674d2 100644 --- a/location/geo-location.web.examples/geo-location.web.examples.mvc/pom.xml +++ b/location/geo-location.web.examples/geo-location.web.examples.mvc/pom.xml @@ -95,12 +95,11 @@ ${maven-war-plugin.version} src/main/webapp - GeoLocationWebMVCExample false - PipelineWebMVCExample + GeoLocationWebMVCExample diff --git a/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/ExampleLauncher.java b/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/ExampleLauncher.java index 61263567b..68ecef61c 100644 --- a/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/ExampleLauncher.java +++ b/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/ExampleLauncher.java @@ -26,7 +26,18 @@ import static fiftyone.geolocation.web.examples.shared.EmbedTomcat.runWebApp; +/** Starts the Spring MVC example in an embedded Tomcat. */ public class ExampleLauncher { + /** Create a new instance. */ + public ExampleLauncher() { + } + + /** + * Start the example. + * + * @param args not used + * @throws LifecycleException if Tomcat could not start + */ public static void main(String[] args) throws LifecycleException { runWebApp( "geo-location.web.examples/geo-location.web.examples.mvc/src/main/webapp", diff --git a/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/configuration/ExampleInitializer.java b/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/configuration/ExampleInitializer.java index 06d48daef..ef28c8f71 100644 --- a/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/configuration/ExampleInitializer.java +++ b/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/configuration/ExampleInitializer.java @@ -24,7 +24,11 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; +/** Sets up the Spring dispatcher servlet with {@link ExampleMvcConfig}. */ public class ExampleInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + /** Create a new instance. */ + public ExampleInitializer() { + } @Override protected Class[] getRootConfigClasses() { diff --git a/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/configuration/ExampleMvcConfig.java b/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/configuration/ExampleMvcConfig.java index 4229c9dbb..f7eea9245 100644 --- a/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/configuration/ExampleMvcConfig.java +++ b/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/configuration/ExampleMvcConfig.java @@ -43,14 +43,14 @@ /** - * @example mvc/configuration/ExampleMvcConfig.java - * Spring MVC device detection example + * \example mvc/configuration/ExampleMvcConfig.java + * Spring MVC location example * * This example shows how to: * * 1. Set up configuration options to add elements to the 51Degrees Pipeline. * - * @include geo-location.web.examples.mvc/src/main/webapp/WEB-INF/51Degrees-Cloud.xml + * \include geo-location.web.examples.mvc/src/main/webapp/WEB-INF/51Degrees-Cloud.xml * * 2. Set up MVC, enable configuration, and add the Pipeline component. * @@ -61,26 +61,27 @@ * 5. Add the interceptor. * * 6. Inject the `FlowDataProvider` into a controller. - * ```{java} - * @Controller - * @RequestMapping("/") + *
+ * {@literal @}Controller
+ * {@literal @}RequestMapping("/")
  * public class ExampleController {
  *     private FlowDataProvider flowDataProvider;
  *
- *     @Autowired
+ *     {@literal @}Autowired
  *     public ExampleController(FlowDataProvider flowDataProvider) {
  *         this.flowDataProvider = flowDataProvider;
  *     }
  *     ...
- * ```
+ * }
+ * 
* * 7. Use the results contained in the flow data to display something on a page view. - * ```{java} - * @Controller - * @RequestMapping("/") + *
+ * {@literal @}Controller
+ * {@literal @}RequestMapping("/")
  * public class ExampleController {
  *     ...
- *     @RequestMapping(method = RequestMethod.GET)
+ *     {@literal @}RequestMapping(method = RequestMethod.GET)
  *     public String get(ModelMap model, HttpServletRequest request) {
  *         // A Flow Data cannot be used by two threads at once. Work handed to
  *         // another thread or task gets the values it needs, read here on the
@@ -95,10 +96,11 @@
  *         return "example";
  *     }
  *     ...
- * ```
+ * }
+ * 
* ## Controller - * @include mvc/controller/ExampleController.java + * \include mvc/controller/ExampleController.java * * ## Config */ @@ -107,6 +109,7 @@ @ComponentScan({"fiftyone.geolocation.web.examples.mvc.controller","fiftyone.pipeline.web.mvc"}) public class ExampleMvcConfig implements WebMvcConfigurer { + /** Create a new instance. */ public ExampleMvcConfig() { super(); } @@ -119,6 +122,11 @@ public void addViewControllers(final ViewControllerRegistry registry) { @Autowired ServletContext servletContext; + /** + * Configure the interceptor from the Pipeline options file. + * + * @return the interceptor configuration + */ @Bean public FiftyOneInterceptorConfig fiftyOneInterceptorConfig() { final FiftyOneInterceptorConfigDefault bean = new FiftyOneInterceptorConfigDefault(); @@ -129,6 +137,11 @@ public FiftyOneInterceptorConfig fiftyOneInterceptorConfig() { return bean; } + /** + * Resolve views to the JSP files in WEB-INF/views. + * + * @return the view resolver + */ @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); diff --git a/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/controller/ExampleController.java b/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/controller/ExampleController.java index 9b92046a9..7b8c66e28 100644 --- a/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/controller/ExampleController.java +++ b/location/geo-location.web.examples/geo-location.web.examples.mvc/src/main/java/fiftyone/geolocation/web/examples/mvc/controller/ExampleController.java @@ -33,17 +33,30 @@ import javax.servlet.http.HttpServletRequest; +/** Shows the location of the request on the example page. */ @Controller @RequestMapping("/") public class ExampleController { private FlowDataProvider flowDataProvider; + /** + * Create a new instance. + * + * @param flowDataProvider gives the Flow Data for each request + */ @Autowired public ExampleController(FlowDataProvider flowDataProvider) { this.flowDataProvider = flowDataProvider; } + /** + * Show the location of the request. + * + * @param model holds the values the page shows + * @param request the request to find the location of + * @return the name of the view + */ @RequestMapping(method = RequestMethod.GET) public String get(ModelMap model, HttpServletRequest request) { // A Flow Data cannot be used by two threads at once. Work handed to diff --git a/location/geo-location.web.examples/geo-location.web.examples.servlet/pom.xml b/location/geo-location.web.examples/geo-location.web.examples.servlet/pom.xml index f36d5eda4..8416e61b9 100644 --- a/location/geo-location.web.examples/geo-location.web.examples.servlet/pom.xml +++ b/location/geo-location.web.examples/geo-location.web.examples.servlet/pom.xml @@ -79,15 +79,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - - - ${endorsed.dir} - - - org.apache.maven.plugins maven-war-plugin @@ -95,30 +86,6 @@ false - - org.apache.maven.plugins - maven-dependency-plugin - - - validate - - copy - - - ${endorsed.dir} - true - - - javax - javaee-endorsed-api - ${javaee-endorsed-api.version} - jar - - - - - - diff --git a/location/geo-location.web.examples/geo-location.web.examples.servlet/src/main/java/fiftyone/geolocation/web/examples/servlet/Example.java b/location/geo-location.web.examples/geo-location.web.examples.servlet/src/main/java/fiftyone/geolocation/web/examples/servlet/Example.java index 5452e232f..410273dd3 100644 --- a/location/geo-location.web.examples/geo-location.web.examples.servlet/src/main/java/fiftyone/geolocation/web/examples/servlet/Example.java +++ b/location/geo-location.web.examples/geo-location.web.examples.servlet/src/main/java/fiftyone/geolocation/web/examples/servlet/Example.java @@ -38,17 +38,17 @@ import java.io.PrintWriter; /** - * @example servlet/Example.java + * \example servlet/Example.java * Servlet geo location example * * This example shows how to: * * 1. Set up configuration options to add elements to the 51Degrees Pipeline. * - * @include geo-location.web.examples.servlet/src/main/webapp/WEB-INF/51Degrees-Cloud.xml + * \include geo-location.web.examples.servlet/src/main/webapp/WEB-INF/51Degrees-Cloud.xml * * 2. Configure the filter and map it to be run for all URLs. - * ```{xml} + *
{@code
  * 
  *     ...
  *     
@@ -64,7 +64,7 @@
  *         /*
  *     
  *     ...
- * ```
+ * }
* * 3. Add the `FlowDataProvider` to the servlet. * @@ -74,6 +74,16 @@ * ## Servlet */ public class Example extends HttpServlet { + /** Create a new instance. */ + public Example() { + } + + /** + * Start the example in an embedded Tomcat. + * + * @param args not used + * @throws LifecycleException if Tomcat could not start + */ public static void main(String[] args) throws LifecycleException { EmbedTomcat.runWebApp("geo-location.web.examples/geo-location.web.examples.servlet/src/main/webapp", "geo-location.web.examples/geo-location.web.examples.servlet/target", @@ -83,6 +93,7 @@ public static void main(String[] args) throws LifecycleException { * Serializable class version number, which is used during deserialization. */ private static final long serialVersionUID = -7420567024186859548L; + /** Gives the Flow Data for each request. */ FlowDataProviderCore flowDataProvider = new FlowDataProviderCore.Default(); /** diff --git a/location/geo-location.web.examples/geo-location.web.examples.shared/src/main/java/fiftyone/geolocation/web/examples/shared/EmbedTomcat.java b/location/geo-location.web.examples/geo-location.web.examples.shared/src/main/java/fiftyone/geolocation/web/examples/shared/EmbedTomcat.java index c7f598f67..85e8625d4 100644 --- a/location/geo-location.web.examples/geo-location.web.examples.shared/src/main/java/fiftyone/geolocation/web/examples/shared/EmbedTomcat.java +++ b/location/geo-location.web.examples/geo-location.web.examples.shared/src/main/java/fiftyone/geolocation/web/examples/shared/EmbedTomcat.java @@ -33,19 +33,27 @@ import java.nio.file.Files; import java.util.Scanner; -/* +/** * Create and start embedded Tomcat server for Servlet Web Examples */ public class EmbedTomcat { + /** The running server. */ public static Tomcat tomcat; + /** Create a new instance. Every member is static. */ + public EmbedTomcat() { + } + /** * Utility to start Tomcat with the servlet supplied * @param servletName a name * @param urlPattern a mapping for the addresses the servlet will respond to * @param servlet an instantiated servlet + * @param port the port to listen on * @return a server context + * @throws LifecycleException if Tomcat could not start + * @throws IOException if the temporary folder could not be created */ public static Context startTomcat(String servletName, String urlPattern, HttpServlet servlet, int port) throws LifecycleException, IOException { tomcat = new Tomcat(); @@ -83,10 +91,12 @@ public static void stopTomcat() { } /** - * Utility to run a servlet in Tomcat at the server root address - wait and then shut down + * Utility to run a webapp in Tomcat at the server root address, wait + * and then shut down * @param pathname path to the webapp folder from project root * @param workingDir where Tomcat should put its temp files etc * @param port the port to listen on + * @throws LifecycleException if Tomcat could not start or stop */ public static void runWebApp(String pathname, String workingDir, int port) throws LifecycleException { System.setProperty("logback.configurationFile", "./logback.xml"); @@ -107,11 +117,12 @@ public static void runWebApp(String pathname, String workingDir, int port) throw } /** - * Utility to run a webapp in Tomcat - wait and then shut down + * Utility to run a servlet in Tomcat - wait and then shut down * @param servlet a servlet * @param workingDir where Tomcat should put its temp files etc - * @param urlPattern where servlet should be releative to server root + * @param urlPattern where servlet should be relative to server root * @param port the port to listen on + * @throws LifecycleException if Tomcat could not start or stop */ public static void runServlet(HttpServlet servlet, String workingDir, String urlPattern, int port) throws LifecycleException { System.setProperty("logback.configurationFile", "./logback.xml"); diff --git a/location/geo-location.web.examples/pom.xml b/location/geo-location.web.examples/pom.xml index a508a0e88..94dadaee2 100644 --- a/location/geo-location.web.examples/pom.xml +++ b/location/geo-location.web.examples/pom.xml @@ -51,9 +51,7 @@ 3.3.2 3.2.0 - 7.0 - ${project.build.directory}/endorsed UTF-8
diff --git a/location/geo-location/src/main/java/fiftyone/geolocation/GeoLocationCloudPipelineBuilder.java b/location/geo-location/src/main/java/fiftyone/geolocation/GeoLocationCloudPipelineBuilder.java index 0c2e328bc..2e0b4beb4 100644 --- a/location/geo-location/src/main/java/fiftyone/geolocation/GeoLocationCloudPipelineBuilder.java +++ b/location/geo-location/src/main/java/fiftyone/geolocation/GeoLocationCloudPipelineBuilder.java @@ -36,11 +36,20 @@ import fiftyone.pipeline.engines.services.HttpClient; import org.slf4j.ILoggerFactory; +/** Builds a Pipeline that finds locations with the cloud service. */ public class GeoLocationCloudPipelineBuilder extends CloudPipelineBuilderBase { private final HttpClient httpClient; private final Enums.GeoLocationProvider geoLocationProvider; + /** + * Create a new builder. + * + * @param loggerFactory creates the loggers for the Pipeline and its + * elements + * @param httpClient used to make requests to the cloud service + * @param geoLocationProvider the location data provider to use + */ public GeoLocationCloudPipelineBuilder( ILoggerFactory loggerFactory, HttpClient httpClient, diff --git a/location/geo-location/src/main/java/fiftyone/geolocation/GeoLocationPipelineBuilder.java b/location/geo-location/src/main/java/fiftyone/geolocation/GeoLocationPipelineBuilder.java index ecb3d61a2..1fa56cc09 100644 --- a/location/geo-location/src/main/java/fiftyone/geolocation/GeoLocationPipelineBuilder.java +++ b/location/geo-location/src/main/java/fiftyone/geolocation/GeoLocationPipelineBuilder.java @@ -28,10 +28,12 @@ import org.slf4j.ILoggerFactory; import org.slf4j.LoggerFactory; +/** Starts building a Pipeline that finds locations. */ public class GeoLocationPipelineBuilder { private ILoggerFactory loggerFactory; private HttpClient httpClient; + /** Create a new builder with the default logger factory. */ public GeoLocationPipelineBuilder() { this(LoggerFactory.getILoggerFactory()); } @@ -63,11 +65,10 @@ public GeoLocationPipelineBuilder( * Use the 51Degrees cloud service to perform Geo Location. * @param resourceKey the resource key to use when querying the * service. - * Obtain one from https://51degrees.com/configure?utm_source=code&utm_medium=comment&utm_campaign=51degrees-java&utm_content=geo-location-src-main-java-fiftyone-geolocation-geolocationpipelinebuilder.java&utm_term=usecloud + * Obtain one from 51degrees.com/configure * @param provider the Geo Location provider to use * @return builder that can be used to configure and build a pipeline * that will use the cloud Geo Location engine - * */ public GeoLocationCloudPipelineBuilder useCloud( String resourceKey, @@ -79,7 +80,7 @@ public GeoLocationCloudPipelineBuilder useCloud( /** * Use the 51Degrees cloud service to perform Geo Location * @param resourceKey the resource to use when querying the cloud service. - * Obtain one from https://51degrees.com/configure?utm_source=code&utm_medium=comment&utm_campaign=51degrees-java&utm_content=geo-location-src-main-java-fiftyone-geolocation-geolocationpipelinebuilder.java&utm_term=usecloud-2 + * Obtain one from 51degrees.com/configure * @param endpoint the 51Degrees cloud URL * @param provider the Geo Location provider to use * @return a builder that can be used to configure and build a pipeline that diff --git a/location/pom.xml b/location/pom.xml index f78363d8f..80cb39bfc 100644 --- a/location/pom.xml +++ b/location/pom.xml @@ -139,8 +139,8 @@ ${maven.compiler.target} true - -Xlint:all,-try,-options - + -Xlint:all + -Werror @@ -231,8 +231,11 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - none - true + + all + true false @@ -345,4 +348,21 @@ scm:git:https://github.com/51Degrees/51degrees-java.git scm:git:https://github.com/51Degrees/51degrees-java.git + + + + + release-8 + + [9,) + + + 8 + + + diff --git a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LoadingCache.java b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LoadingCache.java index 6a6dee4c3..02cb6efcc 100644 --- a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LoadingCache.java +++ b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LoadingCache.java @@ -30,6 +30,8 @@ * already instantiated value of the type V to avoid construction * costs of that value. (In other words the loader has the signature * "extends V implements IValueLoader"). + * @param the type of the keys + * @param the type of the values */ public interface LoadingCache extends Cache { diff --git a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruCacheBase.java b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruCacheBase.java index 72d4006bd..a5a6670b2 100644 --- a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruCacheBase.java +++ b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruCacheBase.java @@ -107,6 +107,7 @@ public long getCacheSize() { } /** + * Returns number of cache misses. * @return number of cache misses. */ public long getCacheMisses() { @@ -114,6 +115,7 @@ public long getCacheMisses() { } /** + * Returns number of requests received by the cache. * @return number of requests received by the cache. */ public long getCacheRequests() { @@ -121,6 +123,7 @@ public long getCacheRequests() { } /** + * Returns the percentage of times cache request did not return a result. * @return the percentage of times cache request did not return a result. */ public double getPercentageMisses() { @@ -145,6 +148,14 @@ public V get(K key) { return node.value; } + /** + * Add a value, or move the existing item for the key to the head of its + * list. The existing value is replaced only when updateExisting is set. + * + * @param key the key + * @param value the value + * @return the item now held for the key + */ protected CachedItem add(K key, V value) { // Get a randomly selected linked list to add // the item to. @@ -203,6 +214,11 @@ public void close() { close(true); } + /** + * Clear the cache once. + * + * @param closing true when called from {@link #close()} + */ protected void close(boolean closing) { // Clear the map and linked lists. if (closed == false) { diff --git a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruLoadingCache.java b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruLoadingCache.java index acb7bc0b4..3f90c86e9 100644 --- a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruLoadingCache.java +++ b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruLoadingCache.java @@ -125,6 +125,9 @@ public V get(K key, ValueLoader loader) throws IOException { * Implementation of {@link CacheBuilder} for {@link LruLoadingCache} caches. */ public static class Builder implements LoadingCacheBuilder { + /** Create a new instance. */ + public Builder() { + } @Override public Cache build(Cache c, int cacheSize) { diff --git a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruPutCache.java b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruPutCache.java index f2727d17f..272b19b1e 100644 --- a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruPutCache.java +++ b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/LruPutCache.java @@ -49,6 +49,9 @@ public void put(K key, V value) { * Implementation of {@link CacheBuilder} for {@link LruPutCache} caches. */ public static class Builder implements PutCacheBuilder { + /** Create a new instance. */ + public Builder() { + } private boolean updateExisting = false; private int concurrency = Runtime.getRuntime().availableProcessors(); diff --git a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/NoCache.java b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/NoCache.java index 222482945..265627a57 100644 --- a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/NoCache.java +++ b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/NoCache.java @@ -25,10 +25,20 @@ import java.io.Closeable; import java.io.IOException; +/** + * A cache that holds nothing and loads the value on every call. + * + * @param type of the values + */ public class NoCache implements Cache { private final ValueLoader loader; + /** + * Create a new instance. + * + * @param loader loads each value + */ public NoCache(ValueLoader loader) { this.loader = loader; } diff --git a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/PutCache.java b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/PutCache.java index cf24b4499..cb268bf92 100644 --- a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/PutCache.java +++ b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/PutCache.java @@ -23,9 +23,11 @@ /** * A cache that supports a thread safe put method for inserting to cache. - + * * By contrast, for example, {@link LruLoadingCache} is a loading cache, it * automatically updates itself by being provided with a data loader. + * @param the type of the keys + * @param the type of the values */ public interface PutCache extends Cache { diff --git a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/PutCacheBuilder.java b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/PutCacheBuilder.java index ec91af23e..993f4e40c 100644 --- a/pipeline/pipeline.caching/src/main/java/fiftyone/caching/PutCacheBuilder.java +++ b/pipeline/pipeline.caching/src/main/java/fiftyone/caching/PutCacheBuilder.java @@ -22,6 +22,7 @@ package fiftyone.caching; +/** Builds caches that values can be put into. */ public interface PutCacheBuilder extends CacheBuilder { /** * Set whether or not an existing item in the cache should be updated diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/CloudDiscoveryState.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/CloudDiscoveryState.java index 0731e46d8..7ca3ac00d 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/CloudDiscoveryState.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/CloudDiscoveryState.java @@ -70,6 +70,7 @@ public CloudDiscoveryState( } /** + * Returns the evidence keys the cloud service accepts. * @return the evidence keys the cloud service accepts */ public List getEvidenceKeys() { @@ -77,6 +78,7 @@ public List getEvidenceKeys() { } /** + * Returns the answer to the accessibleproperties request, as JSON. * @return the answer to the accessibleproperties request, as JSON */ public String getAccessibleProperties() { @@ -84,6 +86,8 @@ public String getAccessibleProperties() { } /** + * Returns this copy as one JSON document, which {@link #fromJson} reads + * back. * @return this copy as one JSON document, which {@link #fromJson} * reads back */ diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/CloudRequestException.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/CloudRequestException.java index 1a9350b97..24c685e9b 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/CloudRequestException.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/CloudRequestException.java @@ -37,6 +37,7 @@ public class CloudRequestException extends PipelineDataException { */ private static final long serialVersionUID = 2110016714691972118L; + /** The HTTP status code of the answer. */ private int httpStatusCode; private transient Map> responseHeaders; diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/Constants.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/Constants.java index 71080b387..227ec45e2 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/Constants.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/Constants.java @@ -22,11 +22,22 @@ package fiftyone.pipeline.cloudrequestengine; +/** Constants used by the Cloud Request Engine. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } + /** Name of the Origin header sent with each request. */ public static final String OriginHeaderName = "Origin"; + /** The messages the Cloud Request Engine logs and throws. */ public class Messages { + /** Create a new instance. */ + public Messages() { + } + + /** Error when neither a resource key nor a license key is set. */ public static final String NoCredential = "The Cloud Request Engine needs a resource key or a license key " + "to authenticate with, as the cloud service answers 401 to a " @@ -34,6 +45,7 @@ public class Messages { + "a resource key created for free at " + "https://51degrees.com/configure?utm_source=code&utm_medium=comment&utm_campaign=51degrees-java&utm_content=pipeline.cloudrequestengine-src-main-java-fiftyone-pipeline-cloudrequestengine-constants.java&utm_term=no-credential"; + /** Error when a license key is set with no requested properties. */ public static final String LicenseKeyNeedsProperties = "The Cloud Request Engine has a license key and no requested " + "properties. A license key names no properties of its own, so " @@ -43,12 +55,14 @@ public class Messages { + "properties wanted, for example \"device.ismobile\" and " + "\"device.iscrawler\"."; + /** Warning naming requested properties the keys in use do not give. */ public static final String PropertiesNotCovered = "The cloud service did not return the requested properties %s " + "in its answer. They are not covered by the keys in use, so " + "they will be missing from every result. The other requested " + "properties came back and are usable."; + /** Warning naming requested names that are not properties. */ public static final String RequestedNamesNotProperties = "The cloud service did not return the requested properties %s " + "in its answer. Every property is answered, with a reason " @@ -56,6 +70,9 @@ public class Messages { + "Check the spelling of each one. The other requested " + "properties came back and are usable."; + /** + * Error when two pieces of evidence give different values for one key. + */ public static final String EvidenceConflict = "'%s:%s' evidence conflicts with %s"; @@ -68,22 +85,34 @@ public class Messages { + "response. The Cloud Request Engine's error in the log says " + "why."; + /** Error when the answer from the cloud service holds no data. */ public static final String MessageNoDataInResponse = "No data in response from cloud service at '%s'"; + /** + * Error when the cloud service answers with a status code that is not + * 200. + */ public static final String MessageErrorCodeReturned = "Cloud service at '%s' returned status code '%d' with content: %s"; + /** Error when the cloud service returns more than one error. */ public static final String ExceptionCloudErrorsMultiple = "Multiple errors returned from 51Degrees cloud service. See inner " + "exceptions for details."; + /** Error when the cloud service returns an error. */ public static final String ExceptionCloudError = "Error returned from 51Degrees cloud service: %s"; + /** Error when the answer from the cloud service is not JSON. */ public static final String ExceptionResponseNotJson = "Cloud service returned status code '%d' with content that is " + "not JSON"; + /** + * Error when the resource key gives no properties of the product an + * element needs. + */ public static final String ExceptionFailedToLoadProperties = "Failed to load aspect properties for element '%s'. This is " + "because your resource key does not include access to any " @@ -91,6 +120,10 @@ public class Messages { + "see our explainer: " + "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=comment&utm_campaign=51degrees-java&utm_content=pipeline.cloudrequestengine-src-main-java-fiftyone-pipeline-cloudrequestengine-constants.java&utm_term=exceptionfailedtoloadproperties"; + /** + * Warning that the properties and evidence keys will be fetched when + * the engine is first used. + */ public static final String MessageDiscoveryDeferred = "The cloud request engine could not fetch its accessible " + "properties or accepted evidence keys when it was built, " @@ -98,11 +131,19 @@ public class Messages { + "again when it is first used, and sends no data request " + "until it has both."; + /** + * Warning that the resource key does not include a product, so its + * engine returns no values. + */ public static final String MessageProductNotInResourceKey = "The resource key does not include the '%s' product, so " + "%s has no properties and its results hold no values. " + "Use a resource key that includes the product to get them."; + /** + * Error from a cloud engine that does not override the method which + * reads the response. + */ public static final String ProcessCloudEngineNotImplemented = "This method should be overridden in the class derived from " + "CloudAspectEngineBase class. The implementation should use " diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/NotImplementedException.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/NotImplementedException.java index e7f5870a2..883fc26cf 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/NotImplementedException.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/NotImplementedException.java @@ -22,17 +22,30 @@ package fiftyone.pipeline.cloudrequestengine; +/** Thrown by a method that a subclass must override. */ public class NotImplementedException extends RuntimeException{ private static final long serialVersionUID = 1L; + /** Create a new instance with no message. */ public NotImplementedException() {}; + /** + * Create a new instance. + * + * @param message the detail message + */ public NotImplementedException(String message) { super(message); }; + /** + * Create a new instance. + * + * @param message the detail message + * @param cause the cause + */ public NotImplementedException(String message, Throwable cause) { super(message, cause); } diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/data/CloudRequestData.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/data/CloudRequestData.java index 6ff01c64b..afd04f004 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/data/CloudRequestData.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/data/CloudRequestData.java @@ -29,8 +29,16 @@ import fiftyone.pipeline.engines.flowelements.AspectEngine; import org.slf4j.Logger; +/** The response from the cloud service, which the cloud engines read. */ public class CloudRequestData extends CloudRequestDataInternal { + /** + * Create a new instance. + * + * @param logger used for logging + * @param flowData the Flow Data this element data belongs to + * @param engine the engine which created the instance + */ public CloudRequestData( Logger logger, FlowData flowData, diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudAspectEngineBase.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudAspectEngineBase.java index 51c2d99c0..fe9ae50a6 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudAspectEngineBase.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudAspectEngineBase.java @@ -57,6 +57,7 @@ /** * Base class for 51Degrees Cloud Aspect Engines + * @param the type of element data the engine returns * @see Specification */ public abstract class CloudAspectEngineBase @@ -72,6 +73,12 @@ protected class RequestEngineAccessor { private volatile CloudRequestEngine cloudRequestEngine; private FlowElement currentElement; + /** + * Create a new instance. + * + * @param pipelines the Pipelines the engine has been added to + * @param currentElement the engine that needs the Cloud Request Engine + */ public RequestEngineAccessor(List pipelines, FlowElement currentElement) { this.pipelines = pipelines; this.currentElement = currentElement; @@ -143,6 +150,11 @@ protected RequestEngineAccessor getRequestEngine() { return requestEngine; } + /** + * Set the accessor that finds the Cloud Request Engine. + * + * @param requestEngine the accessor + */ protected void setRequestEngine(RequestEngineAccessor requestEngine) { this.requestEngine = requestEngine; } diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestDataInternal.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestDataInternal.java index 656eba700..dc91dd8a3 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestDataInternal.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestDataInternal.java @@ -34,6 +34,10 @@ import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicBoolean; +/** + * Holds the response from the cloud service and whether the request has + * started. + */ public class CloudRequestDataInternal extends AspectDataBase implements AutoCloseable { private static final String JSON_RESPONSE_KEY = "json-response"; @@ -167,6 +171,13 @@ boolean isRequestRunning() { } + /** + * Create a new instance. + * + * @param logger used for logging + * @param flowData the Flow Data this element data belongs to + * @param engine the engine which created the instance + */ public CloudRequestDataInternal( Logger logger, FlowData flowData, @@ -174,6 +185,11 @@ public CloudRequestDataInternal( super(logger, flowData, engine); } + /** + * Set the JSON response from the cloud service. + * + * @param value the response + */ public void setJsonResponse(String value) { super.put(JSON_RESPONSE_KEY, value); } @@ -189,6 +205,11 @@ public Boolean getProcessStarted() { return false; } + /** + * Set whether the Cloud Request Engine has started processing. + * + * @param value true once it has started + */ public void setProcessStarted(Boolean value) { super.put(PROCESS_STARTED_KEY, value); } diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestEngineBuilder.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestEngineBuilder.java index 617aed802..0c3a6de38 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestEngineBuilder.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestEngineBuilder.java @@ -72,10 +72,21 @@ public class CloudRequestEngineBuilder extends return System.getenv(name); }; + /** + * Create a new builder with the default HTTP client. + * + * @param loggerFactory creates the loggers the engine uses + */ public CloudRequestEngineBuilder(ILoggerFactory loggerFactory) { this(loggerFactory, new HttpClientDefault()); } + /** + * Create a new builder. + * + * @param loggerFactory creates the loggers the engine uses + * @param httpClient used to make requests to the cloud service + */ public CloudRequestEngineBuilder( ILoggerFactory loggerFactory, HttpClient httpClient) { @@ -210,6 +221,12 @@ private static void checkCredentials( } } + /** + * Build an engine using the current options. + * + * @return a new engine + * @throws Exception if the engine could not be created + */ public CloudRequestEngine build() throws Exception { return buildEngine(); } diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestEngineDefault.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestEngineDefault.java index ec10340ca..293120a52 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestEngineDefault.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/CloudRequestEngineDefault.java @@ -162,6 +162,18 @@ public class CloudRequestEngineDefault return thread; }); + /** + * Create a new instance with a resource key. + * + * @param logger used for logging + * @param aspectDataFactory creates the element data this engine returns + * @param httpClient used to make requests to the cloud service + * @param endPoint the cloud service endpoint + * @param resourceKey the resource key, or null + * @param propertiesEndpoint the properties endpoint + * @param evidenceKeysEndpoint the evidence keys endpoint + * @param timeoutMillis the request timeout in milliseconds + */ public CloudRequestEngineDefault( Logger logger, ElementDataFactory aspectDataFactory, @@ -183,6 +195,20 @@ public CloudRequestEngineDefault( timeoutMillis, null); } + /** + * Create a new instance with a resource key and Origin header. + * + * @param logger used for logging + * @param aspectDataFactory creates the element data this engine returns + * @param httpClient used to make requests to the cloud service + * @param endPoint the cloud service endpoint + * @param resourceKey the resource key, or null + * @param propertiesEndpoint the properties endpoint + * @param evidenceKeysEndpoint the evidence keys endpoint + * @param timeoutMillis the request timeout in milliseconds + * @param cloudRequestOrigin the value of the Origin header, or null for + * none + */ public CloudRequestEngineDefault( Logger logger, ElementDataFactory aspectDataFactory, @@ -206,6 +232,21 @@ public CloudRequestEngineDefault( cloudRequestOrigin); } + /** + * Create a new instance with a resource key or license key. + * + * @param logger used for logging + * @param aspectDataFactory creates the element data this engine returns + * @param httpClient used to make requests to the cloud service + * @param endPoint the cloud service endpoint + * @param resourceKey the resource key, or null + * @param licenseKey the license key, or null + * @param propertiesEndpoint the properties endpoint + * @param evidenceKeysEndpoint the evidence keys endpoint + * @param timeoutMillis the request timeout in milliseconds + * @param cloudRequestOrigin the value of the Origin header, or null for + * none + */ public CloudRequestEngineDefault( Logger logger, ElementDataFactory aspectDataFactory, @@ -233,6 +274,17 @@ public CloudRequestEngineDefault( /** * Constructor. + * @param logger used for logging + * @param aspectDataFactory creates the element data this engine returns + * @param httpClient used to make requests to the cloud service + * @param endPoint the cloud service endpoint + * @param resourceKey the resource key, or null + * @param licenseKey the license key, or null + * @param propertiesEndpoint the properties endpoint + * @param evidenceKeysEndpoint the evidence keys endpoint + * @param timeoutMillis the request timeout in milliseconds + * @param cloudRequestOrigin the value of the Origin header, or null for + * none * @param requestedProperties the fully qualified names of the * properties to ask for, sent as {@code values} * when the list is not empty diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/Constants.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/Constants.java index 1a77c3537..33fb0f1cc 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/Constants.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/Constants.java @@ -22,14 +22,21 @@ package fiftyone.pipeline.cloudrequestengine.flowelements; +/** Default settings of the Cloud Request Engine. */ public class Constants { - // Default end point + /** Create a new instance. */ + public Constants() { + } + + /** The default cloud service endpoint. */ public static final String END_POINT_DEFAULT = "https://cloud.51degrees.com/api/v4"; - // Environment variable name to set end point + /** Environment variable that sets the cloud service endpoint. */ public static final String CLOUD_ENDPOINT_VARIABLE = "_51DEGREES_CLOUD_ENDPOINT"; - // Default timeout for each request to the cloud service, as the - // specification's Configuration options table gives. + /** + * Default timeout of each request to the cloud service, in milliseconds, as + * the Configuration options table of the specification gives. + */ public static final int DEFAULT_TIMEOUT_MILLIS = 2000; } diff --git a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/PropertyKeyedCloudEngineBase.java b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/PropertyKeyedCloudEngineBase.java index 805178b73..973b9d2a0 100644 --- a/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/PropertyKeyedCloudEngineBase.java +++ b/pipeline/pipeline.cloudrequestengine/src/main/java/fiftyone/pipeline/cloudrequestengine/flowelements/PropertyKeyedCloudEngineBase.java @@ -62,6 +62,12 @@ public EvidenceKeyFilter getEvidenceKeyFilter() { return evidenceKeyFilter; } + /** + * Create a new instance. + * + * @param logger used for logging + * @param aspectDataFactory creates the element data this engine returns + */ public PropertyKeyedCloudEngineBase( Logger logger, ElementDataFactory aspectDataFactory) { @@ -117,5 +123,11 @@ public TypedKey getTypedDataKey() { return typedKey; } + /** + * Create the element data for one profile in the response. + * + * @param flowData the Flow Data being processed + * @return a new element data + */ protected abstract TProfile createProfileData(FlowData flowData); } diff --git a/pipeline/pipeline.common/src/main/java/fiftyone/common/testhelpers/LogbackHelper.java b/pipeline/pipeline.common/src/main/java/fiftyone/common/testhelpers/LogbackHelper.java index 76be1c5c1..58aefea6d 100644 --- a/pipeline/pipeline.common/src/main/java/fiftyone/common/testhelpers/LogbackHelper.java +++ b/pipeline/pipeline.common/src/main/java/fiftyone/common/testhelpers/LogbackHelper.java @@ -46,8 +46,17 @@ * Helpers to configure logback directly (in the course of a test, possibly) and other helpers */ public class LogbackHelper { + /** Create a new instance. Every member is static. */ + public LogbackHelper() { + } + + /** Accepts logging events at level WARN or higher. */ public static class WarnEvaluator extends EventEvaluatorBase { + /** Create a new instance. */ + public WarnEvaluator() { + } + /** * Return true if event passed as parameter has level WARN or higher, returns * false otherwise. @@ -82,6 +91,11 @@ public static void defaultConfig() { StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); } + /** + * Replace the logback configuration with the one read from a stream. + * + * @param logbackConfig the configuration XML + */ public static void configureLogback(InputStream logbackConfig){ // assume SLF4J is bound to logback in the current environment LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); @@ -99,6 +113,11 @@ public static void configureLogback(InputStream logbackConfig){ StatusPrinter.printInCaseOfErrorsOrWarnings(context); } + /** + * Replace the logback configuration with the one read from a file. + * + * @param logbackConfig the configuration file + */ public static void configureLogback(File logbackConfig){ // assume SLF4J is bound to logback in the current environment LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); @@ -116,6 +135,11 @@ public static void configureLogback(File logbackConfig){ StatusPrinter.printInCaseOfErrorsOrWarnings(context); } + /** + * Replace the logback configuration with the one in a string. + * + * @param logbackConfig the configuration XML + */ public static void configureLogbackFromString(String logbackConfig){ // assume SLF4J is bound to logback in the current environment LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); diff --git a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/BinaryReader.java b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/BinaryReader.java index 95ccc2912..a03310382 100644 --- a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/BinaryReader.java +++ b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/BinaryReader.java @@ -30,11 +30,18 @@ import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; +/** Reads little-endian values from a byte buffer. */ public class BinaryReader implements Closeable { private final FileChannel channel; private ByteBuffer byteBuffer; + /** + * Create a reader over the whole file, mapped into memory. + * + * @param fileInputStream the file to read + * @throws IOException if the file could not be mapped + */ public BinaryReader(FileInputStream fileInputStream) throws IOException { channel = fileInputStream.getChannel(); byteBuffer = channel.map( @@ -44,44 +51,95 @@ public BinaryReader(FileInputStream fileInputStream) throws IOException { byteBuffer.order(ByteOrder.LITTLE_ENDIAN); } + /** + * Create a reader over the buffer given. + * + * @param byteBuffer the bytes to read + */ public BinaryReader(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; this.byteBuffer.order(ByteOrder.LITTLE_ENDIAN); channel = null; } + /** + * The number of bytes the reader holds. + * + * @return the size in bytes + */ public long getSize() { return byteBuffer.limit(); } + /** + * The buffer the reader reads from. + * + * @return the buffer + */ public ByteBuffer getBuffer() { return byteBuffer; } + /** + * The position of the next byte to read. + * + * @return the position + */ public int getPosition() { return byteBuffer.position(); } + /** + * Move to a new position. + * + * @param position the position of the next byte to read + */ public void setPosition(int position) { byteBuffer.position(position); } + /** + * Read a 4 byte float. + * + * @return the value + */ public float readFloat() { return byteBuffer.getFloat(); } + /** + * Read a 2 byte integer. + * + * @return the value + */ public short readInt16() { return byteBuffer.getShort(); } + /** + * Read a 4 byte integer. + * + * @return the value + */ public int readInt32() { return byteBuffer.getInt(); } + /** + * Read an 8 byte integer. + * + * @return the value + */ public long readInt64() { return byteBuffer.getLong(); } + /** + * Read bytes as characters up to the next line feed, dropping any carriage + * return. + * + * @return the line, or null at the end of the buffer + */ public String readLine() { char c; boolean read = false; @@ -97,12 +155,23 @@ public String readLine() { return read == true ? result.toString() : null; } + /** + * Read the number of bytes given. + * + * @param length the number of bytes + * @return the bytes + */ public byte[] readBytes(final int length) { byte[] bytes = new byte[length]; byteBuffer.get(bytes); return bytes; } + /** + * Copy every byte the reader holds, from the start, into a new array. + * + * @return the bytes + */ public byte[] toByteArray() { ByteBuffer result = ByteBuffer.allocate((int) getSize()); // https://www.morling.dev/blog/bytebuffer-and-the-dreaded-nosuchmethoderror/ @@ -111,10 +180,21 @@ public byte[] toByteArray() { return result.array(); } + /** + * Write every byte the reader holds to a writer. + * + * @param writer where the bytes are written + * @throws IOException if the writer fails + */ public void copyTo(BinaryWriter writer) throws IOException { writer.writeBytes(toByteArray()); } + /** + * Read one byte. + * + * @return the value + */ public byte readByte() { return byteBuffer.get(); } diff --git a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/BinaryWriter.java b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/BinaryWriter.java index c55835179..0f0bc63b9 100644 --- a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/BinaryWriter.java +++ b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/BinaryWriter.java @@ -26,6 +26,7 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; +/** Writes little-endian values to an output stream. */ public class BinaryWriter implements AutoCloseable { /** @@ -58,6 +59,12 @@ public BinaryWriter(FileOutputStream outputStream) throws IOException { stream = new WritableSeekable.File(outputStream); } + /** + * Construct a new instance of the binary writer that writes to the byte + * array output stream given. + * + * @param outputStream where the data should be written + */ public BinaryWriter(ByteArrayOutputStream outputStream) { this(); stream = new WritableSeekable.Memory(outputStream); @@ -120,6 +127,13 @@ private void writeBytesBuffered(byte[] value, int length) throws IOException { } } + /** + * Write the first bytes of an array. + * + * @param value the bytes + * @param length how many bytes to write + * @throws IOException if the stream fails + */ public void writeBytes(byte[] value, int length) throws IOException { buffer.clear(); if (buffer.limit() < value.length) { diff --git a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/ReaderPool.java b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/ReaderPool.java index 1fdca7ab2..e123e1462 100644 --- a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/ReaderPool.java +++ b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/ReaderPool.java @@ -27,6 +27,9 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; +/** + * A pool of readers, each with exclusive use of the source while it is taken. + */ public class ReaderPool implements Closeable { /** @@ -46,6 +49,11 @@ public class ReaderPool implements Closeable { */ private final AtomicInteger readerCount = new AtomicInteger(0); + /** + * Create a pool which creates its readers from the source given. + * + * @param source creates the buffers the readers read + */ public ReaderPool(Source source) { this.source = source; } diff --git a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/Source.java b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/Source.java index 8edb5d746..feade0888 100644 --- a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/Source.java +++ b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/Source.java @@ -25,6 +25,13 @@ import java.io.IOException; import java.nio.ByteBuffer; +/** A source of data that readers read from. */ public interface Source { + /** + * Create a buffer over the data, positioned at the start. + * + * @return a new buffer + * @throws IOException if the data could not be read + */ ByteBuffer createStream() throws IOException; } diff --git a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/direct/SourceMemory.java b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/direct/SourceMemory.java index 6dfe7e81a..614a4f73a 100644 --- a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/direct/SourceMemory.java +++ b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/direct/SourceMemory.java @@ -27,10 +27,16 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; +/** A source held in memory. */ public class SourceMemory implements Source { private final byte[] memory; + /** + * Create a source over the bytes given. + * + * @param memory the data + */ public SourceMemory(byte[] memory) { this.memory = memory; } diff --git a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/indirect/SourceFile.java b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/indirect/SourceFile.java index 21dd55863..39b759b6f 100644 --- a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/indirect/SourceFile.java +++ b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/data/indirect/SourceFile.java @@ -32,9 +32,17 @@ import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; +/** A source held in a file. */ public class SourceFile implements Source { private final FileChannel channel; + /** + * Create a source for the file given. + * + * @param fileName path of the file + * @throws IOException if the file could not be opened + * @throws FileNotFoundException if the file does not exist + */ public SourceFile(String fileName) throws IOException, FileNotFoundException { try(FileInputStream fis = new FileInputStream(fileName)){ diff --git a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapper.java b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapper.java index f50ae0952..5c714181f 100644 --- a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapper.java +++ b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapper.java @@ -66,7 +66,13 @@ public interface FileWrapper { */ String getPath(); + /** + * Whether the file exists. + * + * @return true if it exists + */ boolean exists(); + /** Delete the file. */ void delete(); } diff --git a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapperFactory.java b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapperFactory.java index b3cb620ae..a1b1286ec 100644 --- a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapperFactory.java +++ b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapperFactory.java @@ -40,10 +40,27 @@ public interface FileWrapperFactory { */ FileWrapper build(String path); + /** + * Whether a file exists. + * + * @param path path of the file + * @return true if it exists + */ boolean exists(String path); + /** + * Get the time a file was last modified. + * + * @param path path of the file + * @return the time in milliseconds since the epoch + */ long getLastModified(String path); + /** + * Delete a file. + * + * @param path path of the file + */ void delete(String path); } diff --git a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapperFactoryDefault.java b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapperFactoryDefault.java index 0fbf48264..120e5fc76 100644 --- a/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapperFactoryDefault.java +++ b/pipeline/pipeline.common/src/main/java/fiftyone/common/wrappers/io/FileWrapperFactoryDefault.java @@ -27,6 +27,10 @@ * the OS file system. */ public class FileWrapperFactoryDefault implements FileWrapperFactory { + /** Create a new instance. */ + public FileWrapperFactoryDefault() { + } + @Override public FileWrapper build(String path) { FileWrapper file = null; diff --git a/pipeline/pipeline.common/src/test/java/fiftyone/common/wrappers/data/BinaryWriterTests.java b/pipeline/pipeline.common/src/test/java/fiftyone/common/wrappers/data/BinaryWriterTests.java new file mode 100644 index 000000000..875cc63d7 --- /dev/null +++ b/pipeline/pipeline.common/src/test/java/fiftyone/common/wrappers/data/BinaryWriterTests.java @@ -0,0 +1,48 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.common.wrappers.data; + +import org.junit.Test; + +import java.io.ByteArrayOutputStream; + +import static org.junit.Assert.assertArrayEquals; + +public class BinaryWriterTests { + + /** + * A writer made with a byte array output stream writes its values to + * that stream, little-endian. + */ + @Test + public void byteArrayOutputStream_IsWrittenTo() throws Exception { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + try (BinaryWriter writer = new BinaryWriter(stream)) { + writer.writeInt32(0x01020304); + writer.writeByte((byte) 5); + } + assertArrayEquals( + new byte[]{4, 3, 2, 1, 5}, + stream.toByteArray()); + } +} diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/AlternateName.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/AlternateName.java index bfb4a3be4..ff9b0cf3d 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/AlternateName.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/AlternateName.java @@ -42,5 +42,10 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AlternateName { + /** + * The other name the method answers to. + * + * @return the alternate name + */ String value(); } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/BuildArg.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/BuildArg.java index 8a8a120d2..b5d3f4801 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/BuildArg.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/BuildArg.java @@ -40,5 +40,10 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface BuildArg { + /** + * The name of the build argument. + * + * @return the argument name + */ String value(); } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/DefaultValue.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/DefaultValue.java index 82c12c74f..5e2d433e7 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/DefaultValue.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/annotations/DefaultValue.java @@ -24,12 +24,36 @@ import java.lang.annotation.*; +/** + * Gives the default value of a builder setting, which the builder listing + * shows. The first of the values that is set is used. + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface DefaultValue { + /** + * The default as text. + * + * @return the value, or empty when not set + */ String value() default ""; + /** + * The default as an integer. + * + * @return the value, or Integer.MIN_VALUE when not set + */ int intValue() default Integer.MIN_VALUE; + /** + * The default as a double. + * + * @return the value, or Double.MIN_VALUE when not set + */ double doubleValue() default Double.MIN_VALUE; + /** + * The default as a boolean, used when no other value is set. + * + * @return the value + */ boolean booleanValue() default false; } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/Constants.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/Constants.java index 15bc17786..bfac5c8c4 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/Constants.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/Constants.java @@ -22,32 +22,47 @@ package fiftyone.pipeline.core; +/** Evidence prefixes, suffixes and keys shared by every element. */ public class Constants { - // Evidence Separator + /** Create a new instance. */ + public Constants() { + } + + /** Separates the parts of an evidence key. */ public static final String EVIDENCE_SEPERATOR = "."; - // Evidence Prefixes + /** Prefix of evidence from HTTP headers. */ public static final String EVIDENCE_HTTPHEADER_PREFIX = "header"; + /** Prefix of evidence from cookies. */ public static final String EVIDENCE_COOKIE_PREFIX = "cookie"; + /** Prefix of evidence from the session. */ public static final String EVIDENCE_SESSION_PREFIX = "session"; + /** Prefix of evidence from the query string. */ public static final String EVIDENCE_QUERY_PREFIX = "query"; + /** Prefix of evidence from the server. */ public static final String EVIDENCE_SERVER_PREFIX = "server"; - // Evidence Suffixes + /** Suffix of the User-Agent evidence. */ public static final String EVIDENCE_USERAGENT = "user-agent"; + /** Suffix of the web context root evidence. */ public static final String EVIDENCE_WEB_CONTEXT_ROOT_SUFFIX = "contextroot"; - // Evidence Keys + /** Evidence key of the client IP address. */ public static final String EVIDENCE_CLIENTIP_KEY = EVIDENCE_SERVER_PREFIX + EVIDENCE_SEPERATOR + "client-ip"; + /** Evidence key of a User-Agent in the query string. */ public static final String EVIDENCE_QUERY_USERAGENT_KEY = EVIDENCE_QUERY_PREFIX + EVIDENCE_SEPERATOR + EVIDENCE_USERAGENT; + /** Evidence key of the User-Agent header. */ public static final String EVIDENCE_HEADER_USERAGENT_KEY = EVIDENCE_HTTPHEADER_PREFIX + EVIDENCE_SEPERATOR + EVIDENCE_USERAGENT; + /** Evidence key of the web context root. */ public static final String EVIDENCE_WEB_CONTEXT_ROOT = EVIDENCE_SERVER_PREFIX + EVIDENCE_SEPERATOR + EVIDENCE_WEB_CONTEXT_ROOT_SUFFIX; + /** Evidence key of the request protocol. */ public static final String EVIDENCE_PROTOCOL = EVIDENCE_HTTPHEADER_PREFIX + EVIDENCE_SEPERATOR + "protocol"; + /** Evidence key of the session. */ public static final String EVIDENCE_SESSION_KEY = EVIDENCE_SESSION_PREFIX + EVIDENCE_SEPERATOR + "session"; /** diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/MapAdapter.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/MapAdapter.java index d8dc61b14..ed1454d1b 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/MapAdapter.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/MapAdapter.java @@ -35,6 +35,9 @@ * {@link XmlAdapter#marshal(Object)} as this is only ever used to unmarshal. */ public class MapAdapter extends XmlAdapter> { + /** Create a new instance. */ + public MapAdapter() { + } @Override public Map unmarshal(Object v) throws Exception { diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/PipelineOptions.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/PipelineOptions.java index c05f6f454..9b5c567bf 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/PipelineOptions.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/PipelineOptions.java @@ -44,6 +44,9 @@ */ @XmlRootElement(name = "PipelineOptions") public class PipelineOptions { + /** Create a new instance. */ + public PipelineOptions() { + } /** * Configuration information for the {@link FlowElement}s that the Pipeline diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/PipelineOptionsFactory.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/PipelineOptionsFactory.java index fa5376137..36db07f65 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/PipelineOptionsFactory.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/configuration/PipelineOptionsFactory.java @@ -37,12 +37,30 @@ * Instantiate pipeline options from an XML config file */ public class PipelineOptionsFactory { + /** Create a new instance. */ + public PipelineOptionsFactory() { + } + /** Name of the schema the options file is checked against. */ public static final String PIPELINE_OPTIONS_SCHEMA = "pipelineOptions.xsd"; + /** + * Read Pipeline options from an XML file. + * + * @param configFile path of the file + * @return the options + * @throws Exception if the file cannot be read or does not match the schema + */ public static PipelineOptions getOptionsFromFile(String configFile) throws Exception{ return getOptionsFromFile(new File(configFile)); } + /** + * Read Pipeline options from an XML file. + * + * @param configFile the file + * @return the options + * @throws Exception if the file cannot be read or does not match the schema + */ public static PipelineOptions getOptionsFromFile(File configFile) throws Exception{ JAXBContext jaxbContext = JAXBContext.newInstance(PipelineOptions.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/AccessiblePropertyMetaData.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/AccessiblePropertyMetaData.java index bc2017365..9c7cd4403 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/AccessiblePropertyMetaData.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/AccessiblePropertyMetaData.java @@ -35,6 +35,9 @@ * Contains classes which deserialise JSON property definitions. */ public class AccessiblePropertyMetaData { + /** Create a new instance. */ + public AccessiblePropertyMetaData() { + } /** * Class containing a list of {@link ProductMetaData}s. @@ -51,6 +54,7 @@ public LicencedProducts(JSONObject json) { products.put(key, new ProductMetaData(json.getJSONObject(key))); } } + /** The products, by name. */ public final Map products; } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/DataBase.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/DataBase.java index af87e7ac0..9ba17a6ff 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/DataBase.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/DataBase.java @@ -37,6 +37,7 @@ */ public abstract class DataBase implements Data { + /** Used for logging. */ protected final Logger logger; private final Map data; diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/DataKeyBuilderDefault.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/DataKeyBuilderDefault.java index dac329744..75fec67c6 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/DataKeyBuilderDefault.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/DataKeyBuilderDefault.java @@ -30,6 +30,9 @@ * The default implementation of {@link DataKeyBuilder}. */ public class DataKeyBuilderDefault implements DataKeyBuilder { + /** Create a new instance. */ + public DataKeyBuilderDefault() { + } private final List>> keys = new ArrayList<>(); diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/ElementDataBase.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/ElementDataBase.java index e17a6f55a..f9eb59485 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/ElementDataBase.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/ElementDataBase.java @@ -127,6 +127,9 @@ public void startWriting() { } /** + * Returns true once a Flow Element that writes this instance has finished, + * until one that shares it starts to process or its pool gives it to + * another Flow Data. * @return true once a Flow Element that writes this instance has * finished, until one that shares it starts to process or its pool gives * it to another Flow Data @@ -155,6 +158,7 @@ protected boolean isPoolable() { } /** + * Returns true if this instance can be returned to its Flow Element's pool. * @return true if this instance can be returned to its Flow Element's * pool */ diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/EvidenceKeyFilterWhitelist.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/EvidenceKeyFilterWhitelist.java index 0885ef1c9..57f9447dc 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/EvidenceKeyFilterWhitelist.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/EvidenceKeyFilterWhitelist.java @@ -30,8 +30,10 @@ */ public class EvidenceKeyFilterWhitelist implements EvidenceKeyFilter { + /** The keys to include, each with its order of importance. */ protected final Map whitelist; + /** Compares keys, for example ignoring case. */ protected final Comparator comparator; /** diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/FlowData.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/FlowData.java index 20f624592..0c957069e 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/FlowData.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/FlowData.java @@ -48,6 +48,16 @@ */ public interface FlowData extends AutoCloseable { + /** + * Close the Element Data that needs it and give pooled Element Data back + * to its pool. It throws no checked exception, so a try-with-resources + * block needs no catch for it. + * @throws fiftyone.pipeline.core.exceptions.CloseException if closing + * Element Data threw a checked exception, which is the cause + */ + @Override + void close(); + /** * Process this FlowData via the owning Pipeline. Once this method returns * the FlowData will not be changed further and cannot be processed again. diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/FlowError.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/FlowError.java index 7abb9db88..37347cc2f 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/FlowError.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/FlowError.java @@ -50,6 +50,12 @@ class Default implements FlowError { private final Throwable throwable; private final FlowElement flowElement; + /** + * Create a new instance. + * + * @param throwable the error + * @param flowElement the element where it happened + */ public Default(Throwable throwable, FlowElement flowElement) { this.throwable = throwable; this.flowElement = getNotNull(flowElement, "Flow element can't be null"); diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/TryGetResult.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/TryGetResult.java index bc9904930..7ef2f422c 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/TryGetResult.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/TryGetResult.java @@ -28,6 +28,9 @@ * @param the type of value contained in the result */ public class TryGetResult { + /** Create a new instance. */ + public TryGetResult() { + } private T value = null; diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/types/JavaScript.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/types/JavaScript.java index 36ca97628..9939d603d 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/types/JavaScript.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/data/types/JavaScript.java @@ -32,6 +32,11 @@ public class JavaScript implements Comparable { private final String value; + /** + * Create a new instance. + * + * @param value the JavaScript + */ public JavaScript(String value) { this.value = value; } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/exceptions/CloseException.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/exceptions/CloseException.java new file mode 100644 index 000000000..c93dcde91 --- /dev/null +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/exceptions/CloseException.java @@ -0,0 +1,63 @@ +/* ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* */ + +package fiftyone.pipeline.core.exceptions; + +/** + * Thrown by close() of a Pipeline or Flow Data when something it closes in + * turn throws, which is the cause. Their close() methods throw no checked + * exception, so a try-with-resources block needs no catch for them. + */ +public class CloseException extends RuntimeException { + /** + * Serializable class version number, which is used during deserialization. + */ + private static final long serialVersionUID = 4061943563212306174L; + + /** + * Constructor + * @param message the exception message + * @param cause the exception thrown by what was being closed + */ + public CloseException(String message, Throwable cause) { + super(message, cause); + } + + /** + * The exception to throw for one that close() of a member threw. An + * unchecked exception is given back as it is, and a checked one becomes + * the cause of a CloseException. An InterruptedException sets the + * thread's interrupt status again, so the interrupt is not lost. + * @param message the message for a CloseException + * @param cause the exception close() of the member threw + * @return the exception to throw + */ + public static RuntimeException of(String message, Exception cause) { + if (cause instanceof RuntimeException) { + return (RuntimeException) cause; + } + if (cause instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + return new CloseException(message, cause); + } +} diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/exceptions/PropertyNotLoadedException.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/exceptions/PropertyNotLoadedException.java index f09b6b14e..a85e05e9f 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/exceptions/PropertyNotLoadedException.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/exceptions/PropertyNotLoadedException.java @@ -32,22 +32,47 @@ public class PropertyNotLoadedException extends RuntimeException { */ private static final long serialVersionUID = -8356317224796833123L; + /** Create a new instance with no message. */ public PropertyNotLoadedException() { super(); } + /** + * Create a new instance. + * + * @param message the detail message + */ public PropertyNotLoadedException(String message) { super(message); } + /** + * Create a new instance. + * + * @param message the detail message + * @param cause the cause + */ public PropertyNotLoadedException(String message, Throwable cause) { super(message, cause); } + /** + * Create a new instance. + * + * @param cause the cause + */ public PropertyNotLoadedException(Throwable cause) { super(cause); } + /** + * Create a new instance. + * + * @param message the detail message + * @param cause the cause + * @param enableSuppression whether suppressed exceptions are kept + * @param writableStackTrace whether the stack trace can be written + */ protected PropertyNotLoadedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowDataDefault.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowDataDefault.java index 1f7655824..e82efb082 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowDataDefault.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowDataDefault.java @@ -23,6 +23,7 @@ package fiftyone.pipeline.core.flowelements; import fiftyone.pipeline.core.data.*; +import fiftyone.pipeline.core.exceptions.CloseException; import fiftyone.pipeline.core.exceptions.PipelineDataException; import fiftyone.pipeline.core.typed.TypedKey; import fiftyone.pipeline.core.typed.TypedKeyDefault; @@ -541,13 +542,18 @@ public EvidenceKeyFilter getEvidenceKeyFilter() { * call the pool may have given an instance to another request. */ @Override - public void close() throws Exception { + public void close() { if (closed.getAndSet(true)) { return; } for (Object elementData : data.asStringKeyMap().values()) { if (AutoCloseable.class.isAssignableFrom(elementData.getClass())) { - ((AutoCloseable) elementData).close(); + try { + ((AutoCloseable) elementData).close(); + } catch (Exception e) { + throw CloseException.of( + "Closing Element Data of the Flow Data failed", e); + } } } // Pooled Element Data goes back to its Flow Element's pool. A diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowDataFactoryDefault.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowDataFactoryDefault.java index 55f5525df..f38bbf008 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowDataFactoryDefault.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowDataFactoryDefault.java @@ -36,6 +36,11 @@ public class FlowDataFactoryDefault implements FlowDataFactory { private final ILoggerFactory loggerFactory; + /** + * Create a new instance. + * + * @param loggerFactory creates the loggers for each Flow Data + */ public FlowDataFactoryDefault(ILoggerFactory loggerFactory) { this.loggerFactory = loggerFactory; } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowElement.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowElement.java index b03878a83..d933b5bf6 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowElement.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowElement.java @@ -44,6 +44,14 @@ public interface FlowElement< TData extends ElementData, TProperty extends ElementPropertyMetaData> extends AutoCloseable { + + /** + * Free the resources the element holds. It throws no checked exception, + * so a try-with-resources block needs no catch for it. + */ + @Override + void close(); + /** * Carry out whatever operations this element is designed to do using the * {@link FlowData} passed. diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowElementBase.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowElementBase.java index fe713261c..1a3892ed3 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowElementBase.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/FlowElementBase.java @@ -40,7 +40,7 @@ * {@link #process(FlowData)} method deals with {@link FlowData#isStopped()} and * any errors that may be thrown, and calls the abstract * {@link #processInternal(FlowData)} method to do the actual processing. - *

+ * * @see Specification * * @param the type of element data that the flow element will write to @@ -53,7 +53,9 @@ public abstract class FlowElementBase< TProperty extends ElementPropertyMetaData> implements FlowElement { + /** Used for logging. */ protected final Logger logger; + /** The key the element's data is stored under in the Flow Data. */ protected TypedKey typedKey = null; private boolean closed = false; private final List pipelines = new ArrayList<>(); @@ -226,6 +228,12 @@ public boolean isClosed() { */ protected abstract void unmanagedResourcesCleanup(); + /** + * Release the element's resources. + * + * @param closing true to release managed resources as well as unmanaged + * ones + */ protected void close(boolean closing) { if (closed) { logger.debug("FlowElement '{}'-'{}' already closed.", getClass().getSimpleName(), hashCode()); @@ -261,7 +269,7 @@ protected void finalize() throws Throwable { */ @Override - public void close() throws Exception { + public void close() { close(true); } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/Pipeline.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/Pipeline.java index f36061939..8a2266d5b 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/Pipeline.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/Pipeline.java @@ -39,6 +39,18 @@ */ public interface Pipeline extends AutoCloseable { + /** + * Close the Pipeline and, if it was built to, its Flow Elements and the + * services added to it. It throws no checked exception, so a + * try-with-resources block needs no catch for it. + * @throws fiftyone.pipeline.core.exceptions.CloseException if closing a + * Flow Element or service threw. Every Flow Element and service is + * closed first, and the first failure is the cause, with any others + * suppressed in it. + */ + @Override + void close(); + /** * Create a new {@link FlowData} instance linked to this Pipeline. The * resulting FlowData's {@link FlowData#process()} method will cause @@ -90,7 +102,7 @@ default boolean isSuppressProcessExceptions() { * Add a service to be used by this Pipeline. If the service supports * Closeable or AutoCloseable, it will be closed automatically when the * pipeline is closed. - * @param service + * @param service the service to add */ void addService(PipelineService service); diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineBuilder.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineBuilder.java index d177ba55c..268e9cff8 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineBuilder.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineBuilder.java @@ -194,10 +194,10 @@ private static void closeAfterFailure( } /** - * Uses reflection to populate {@link #elementBuilders} with all classes - * which are annotated with the {@link ElementBuilder} annotation. + * Uses reflection to find all classes which are annotated with the + * {@link ElementBuilder} annotation. * - * @return + * @return the classes found */ public static Set> getAvailableElementBuilders() { @@ -1075,6 +1075,8 @@ private static boolean hasParseMethod(Class type) { /** * Evaluate strings for substitution of system properties etc. + * @param value the string to evaluate + * @return the string with each variable replaced */ public static String evaluate(String value) { StringSubstitutor substitutor = FiftyOneLookup.getSubstitutor(); diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineBuilderBase.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineBuilderBase.java index 8df57efad..b940f84fd 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineBuilderBase.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineBuilderBase.java @@ -71,9 +71,14 @@ public abstract class PipelineBuilderBase { */ protected final List services = new ArrayList<>(); + /** Whether the Pipeline closes its elements when it is closed. */ protected boolean autoCloseElements = Constants.DEFAULT_AUTO_CLOSE_ELEMENTS; + /** + * Whether the Pipeline records errors from processing instead of throwing + * them. + */ protected boolean suppressProcessExceptions = Constants.DEFAULT_SUPPRESS_PROCESS_EXCEPTIONS; @@ -97,6 +102,11 @@ public PipelineBuilderBase(ILoggerFactory loggerFactory) { this.logger = loggerFactory.getLogger(getClass().getName()); } + /** + * The elements added so far. + * + * @return the elements + */ protected List getFlowElements() { return flowElements; } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineDefault.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineDefault.java index bc9ee45d3..2e2a51ab0 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineDefault.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/flowelements/PipelineDefault.java @@ -24,12 +24,12 @@ import fiftyone.pipeline.core.data.*; import fiftyone.pipeline.core.data.factories.FlowDataFactory; +import fiftyone.pipeline.core.exceptions.CloseException; import fiftyone.pipeline.core.exceptions.PipelineDataException; import fiftyone.pipeline.core.services.PipelineService; import fiftyone.pipeline.exceptions.AggregateException; import org.slf4j.Logger; -import java.io.Closeable; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -406,7 +406,7 @@ private boolean allPropertiesLoaded() { return true; } - public void close(boolean closing) throws Exception { + public void close(boolean closing) { if (isClosed == false) { synchronized (lock) { if (isClosed == false) { @@ -425,24 +425,31 @@ public void close(boolean closing) throws Exception { // Dispose the services after all elements have been // disposed. for (PipelineService service : services) { - if (service instanceof Closeable) { - ((Closeable)service).close(); - } - else if (service instanceof AutoCloseable){ - try { - ((AutoCloseable)service).close(); - } - catch (Exception e) { - exceptions.add(e); - } - } + if (service instanceof AutoCloseable) { + try { + ((AutoCloseable) service).close(); + } catch (Exception e) { + exceptions.add(e); + } + } } - - // Throw an exception if an exception occurred + + // Once everything is closed, throw with the first + // failure as the cause and the others suppressed. if (exceptions.size() > 0) { - throw new Exception( - "One or more exceptions occurred while closing the pipeline", + CloseException failure = new CloseException( + "One or more exceptions occurred while " + + "closing the pipeline", exceptions.get(0)); + for (Exception e : exceptions) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + if (e != exceptions.get(0)) { + failure.addSuppressed(e); + } + } + throw failure; } } } @@ -451,7 +458,7 @@ else if (service instanceof AutoCloseable){ } @Override - public void close() throws Exception { + public void close() { logger.debug("Pipeline '" + hashCode() + "' closed."); close(true); } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/typed/TypedKeyMap.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/typed/TypedKeyMap.java index c9ef59db3..ad03cf2e1 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/typed/TypedKeyMap.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/core/typed/TypedKeyMap.java @@ -49,8 +49,26 @@ public interface TypedKeyMap extends Closeable { T get(TypedKey typedKey); + /** + * Get the one value whose class is the type given, or failing that the one + * value assignable to it. + * + * @param type the type of the value + * @param type of the value + * @return the value + * @throws fiftyone.pipeline.core.exceptions.PipelineDataException if no + * value or more than one matches + */ T get(Class type); + /** + * Get a value without failing when the key is missing or the type does not + * match. + * + * @param key the key of the value + * @param type of the value + * @return the result, which says whether a value was found + */ TryGetResult tryGet(TypedKey key); /** @@ -79,18 +97,53 @@ default T putIfAbsent(TypedKey typedKey, T value) { return get(typedKey); } + /** + * Remove a key and close its value. + * + * @param typedKey the key to remove + * @param type of the value + * @return the value removed, or null if the key was not present + */ T removeIfExists(TypedKey typedKey); + /** + * Whether a key of this name is present. + * + * @param key the name of the key + * @return true if present + */ boolean containsKey(String key); + /** + * Whether a key of this name is present. + * + * @param typedKey the key + * @param type of the value + * @return true if present + */ boolean containsKey(TypedKey typedKey); + /** + * The map as a map of names to values. + * + * @return the map + */ Map asStringKeyMap(); @Override void close(); + /** + * The names of every key. + * + * @return the names + */ List getKeys(); + /** + * The number of keys. + * + * @return the number of keys + */ int size(); } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/exceptions/AggregateException.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/exceptions/AggregateException.java index bf4de9565..565458def 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/exceptions/AggregateException.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/exceptions/AggregateException.java @@ -26,8 +26,8 @@ /** * Aggregation of multiple exceptions. All exceptions which caused an instance - * of this are added to the {@link #suppressedExceptions} list and can be - * retrieved via the {@link #getSuppressed()} method. + * of this are added as suppressed exceptions and can be retrieved with the + * {@link #getSuppressed()} method. */ public class AggregateException extends RuntimeException { diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Builders.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Builders.java index 7b8fd90a3..4a5139f7c 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Builders.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Builders.java @@ -49,6 +49,9 @@ * and hence will transitively include Pipeline. */ public class Builders { + /** Create a new instance. */ + public Builders() { + } private static final Logger logger = LoggerFactory.getLogger("Builders"); // what methods have we already seen for this builder (can be from superclass or interface) @@ -56,8 +59,8 @@ public class Builders { /** * Output a Markdown table listing builders and properties + * @param out where the table is written */ - public static void doTable(PrintStream out) { for (Class clazz : getAvailableElementBuilders()) { out.println("# " + clazz.getName()); @@ -87,8 +90,8 @@ public static void doTable(PrintStream out) { /** * Output an XML property file with all builders and parameters + * @param out where the file is written */ - public static void doXml(PrintStream out) { out.println(""); out.println(" "); diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Check.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Check.java index 0867a2a4b..a35fa9232 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Check.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Check.java @@ -31,6 +31,10 @@ * Helper to guard that an argument fulfills its contract */ public class Check { + /** Create a new instance. */ + public Check() { + } + /** * Throw an {@link IllegalArgumentException} if a condition is not met. * @param condition result of a conditional expression @@ -57,20 +61,44 @@ public static T getNotNull(T value, String message) { return value; } + /** + * Whether a string has a character other than white space. + * + * @param arg the string + * @return true if it is not null and not blank + */ public static boolean notNullOrBlank(String arg){ return Objects.nonNull(arg) && isFalse(arg.trim().isEmpty()); } + /** + * Whether a string is null or holds only white space. + * + * @param arg the string + * @return true if it is null or blank + */ public static boolean isNullOrBlank(String arg){ return Objects.isNull(arg) || arg.trim().isEmpty(); } + /** + * Whether a file exists at the path given. + * + * @param pathString the path + * @return false if the path is blank or nothing is there + */ public static boolean fileExists(String pathString) { if (isNullOrBlank(pathString)) { return false; } return Paths.get(pathString).toFile().exists(); } + /** + * Whether no file exists at the path given. + * + * @param pathString the path + * @return true if the path is blank or nothing is there + */ public static boolean notFileExists(String pathString) { return !fileExists(pathString); } diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/FiftyOneLookup.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/FiftyOneLookup.java index 027f124d1..e93ca58b8 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/FiftyOneLookup.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/FiftyOneLookup.java @@ -37,12 +37,18 @@ * Used for Interpolation of ${variable} in PipelineOptions and elsewhere */ public class FiftyOneLookup { + /** Create a new instance. */ + public FiftyOneLookup() { + } private static final Map customLookups= new HashMap<>(); static { customLookups.put("envsys", new EnvSysLookup()); customLookups.put("filepath", new FilePathLookup()); } + /** + * Resolves the envsys and filepath lookups as well as the standard ones. + */ public static StringLookup FIFTYONE_LOOKUP = StringLookupFactory.INSTANCE.interpolatorStringLookup(customLookups,null,true); /** @@ -79,6 +85,11 @@ public String lookup(String key) { } } } + /** + * Create a substitutor that uses {@link #FIFTYONE_LOOKUP}. + * + * @return a new substitutor + */ public static StringSubstitutor getSubstitutor() { return new FiftyOneStringSubstitutor(FIFTYONE_LOOKUP); } @@ -91,6 +102,11 @@ public static StringSubstitutor getSubstitutor() { * which is not what we want. */ public static class FiftyOneStringSubstitutor extends StringSubstitutor { + /** + * Create a new instance. + * + * @param variableResolver resolves each variable + */ @SuppressWarnings("this-escape") public FiftyOneStringSubstitutor(StringLookup variableResolver) { super(variableResolver); diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/FileFinder.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/FileFinder.java index bc4952080..272ceca42 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/FileFinder.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/FileFinder.java @@ -31,7 +31,12 @@ import static java.util.Objects.isNull; +/** Finds files by searching the folders below a root. */ public class FileFinder { + /** Create a new instance. */ + public FileFinder() { + } + /** * MAX depth to iterate when searching for files below specified root */ diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/StringManipulation.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/StringManipulation.java index 262cc48c3..2b66499c0 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/StringManipulation.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/StringManipulation.java @@ -30,6 +30,10 @@ * Static helper methods for manipulating strings. */ public class StringManipulation { + /** Create a new instance. */ + public StringManipulation() { + } + /** * Join a list of strings using the delimiter provided. * @param strings to join diff --git a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Types.java b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Types.java index ebe33557f..bff78728b 100644 --- a/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Types.java +++ b/pipeline/pipeline.core/src/main/java/fiftyone/pipeline/util/Types.java @@ -34,6 +34,9 @@ * Static type methods. */ public class Types { + /** Create a new instance. */ + public Types() { + } /** * Get a map of primitive types to their boxed type e.g. boolean and Boolean diff --git a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/ElementDataPoolTests.java b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/ElementDataPoolTests.java index b6a5f37a2..3d90a9fd8 100644 --- a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/ElementDataPoolTests.java +++ b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/ElementDataPoolTests.java @@ -292,9 +292,9 @@ public void runningLazyTask_KeepsTheInstanceFromItsPool() throws Exception { } /** - * Closing a Flow Data a second time, as a try-with-resources around one - * that a web filter also closes does, must not give back an instance - * that the pool has since given to another request. + * Closing a Flow Data a second time, as happens when the code that used + * it and a web filter both close it, must not give back an instance that + * the pool has since given to another request. */ @Test public void closingTwice_GivesNoInstanceToTwoRequests() throws Exception { @@ -303,36 +303,40 @@ public void closingTwice_GivesNoInstanceToTwoRequests() throws Exception { LoggerFactory.getILoggerFactory()) .addFlowElement(new Counter(allocated)) .setAutoCloseElements(true) - .build(); - FlowData first = pipeline.createFlowData()) { - first.addEvidence("query.request", "first"); - first.process(); - Object pooled = first.get("counter"); - first.close(); - - try (FlowData second = pipeline.createFlowData()) { - second.addEvidence("query.request", "second"); - second.process(); - assertSame( - "The instance was not reused, so this proves nothing", - pooled, - second.get("counter")); - + .build()) { + FlowData first = pipeline.createFlowData(); + try { + first.addEvidence("query.request", "first"); + first.process(); + Object pooled = first.get("counter"); first.close(); - try (FlowData third = pipeline.createFlowData()) { - third.addEvidence("query.request", "third"); - third.process(); - assertNotSame( - "A second close gave an instance that another " + - "request holds back to its pool", + try (FlowData second = pipeline.createFlowData()) { + second.addEvidence("query.request", "second"); + second.process(); + assertSame( + "The instance was not reused, so this proves nothing", pooled, - third.get("counter")); + second.get("counter")); + + first.close(); + + try (FlowData third = pipeline.createFlowData()) { + third.addEvidence("query.request", "third"); + third.process(); + assertNotSame( + "A second close gave an instance that another " + + "request holds back to its pool", + pooled, + third.get("counter")); + } + assertEquals( + "The second request's value was overwritten", + "second", + ((ElementDataBase) second.get("counter")).get("request")); } - assertEquals( - "The second request's value was overwritten", - "second", - ((ElementDataBase) second.get("counter")).get("request")); + } finally { + first.close(); } } assertEquals( diff --git a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/FlowDataTests.java b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/FlowDataTests.java index 70a741e2f..fa24825ed 100644 --- a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/FlowDataTests.java +++ b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/FlowDataTests.java @@ -706,7 +706,8 @@ public boolean isMatch(ElementPropertyMetaData property) { } private interface CloseableData extends ElementData, AutoCloseable { - + @Override + void close(); } /** diff --git a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/PipelineAutoCloseTests.java b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/PipelineAutoCloseTests.java index 737a2a5da..16c1134c8 100644 --- a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/PipelineAutoCloseTests.java +++ b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/PipelineAutoCloseTests.java @@ -50,15 +50,14 @@ public class PipelineAutoCloseTests { public void autoCloseOff_SharedElementStaysOpen() throws Exception { MultiplyByFiveElement shared = new MultiplyByFiveElement(mock(Logger.class)); - try (Pipeline first = new PipelineBuilder(loggerFactory) - .setAutoCloseElements(false) - .addFlowElement(shared) - .build(); - Pipeline second = new PipelineBuilder(loggerFactory) + Pipeline first = new PipelineBuilder(loggerFactory) + .setAutoCloseElements(false) + .addFlowElement(shared) + .build(); + try (Pipeline second = new PipelineBuilder(loggerFactory) .setAutoCloseElements(false) .addFlowElement(shared) .build()) { - // Closing again at the end of the block does nothing. first.close(); assertFalse("Closing one Pipeline closed the shared element.", @@ -69,6 +68,8 @@ public void autoCloseOff_SharedElementStaysOpen() throws Exception { assertEquals(10, flowData.getFromElement(shared).getResult()); } } finally { + // Closing again does nothing. + first.close(); shared.close(); } } @@ -77,11 +78,14 @@ public void autoCloseOff_SharedElementStaysOpen() throws Exception { public void autoCloseOn_ClosesTheElement() throws Exception { MultiplyByFiveElement element = new MultiplyByFiveElement(mock(Logger.class)); - try (Pipeline pipeline = new PipelineBuilder(loggerFactory) - .setAutoCloseElements(true) - .addFlowElement(element) - .build()) { + Pipeline pipeline = new PipelineBuilder(loggerFactory) + .setAutoCloseElements(true) + .addFlowElement(element) + .build(); + try { assertFalse(element.isClosed()); + } finally { + pipeline.close(); } assertTrue(element.isClosed()); } diff --git a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/PipelineBuilderBaseTests.java b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/PipelineBuilderBaseTests.java index 22ad433b5..1023607e2 100644 --- a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/PipelineBuilderBaseTests.java +++ b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/PipelineBuilderBaseTests.java @@ -51,7 +51,7 @@ public void PipelineBuilderBase_Build() throws Exception { TestAutoCloseableService service2 = mock(TestAutoCloseableService.class); builder.addService(service1); builder.addService(service2); - try (Pipeline pipeline = builder.build()) {} + builder.build().close(); verify(service1, times(1)).close(); verify(service2, times(1)).close(); } diff --git a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/RunsLastTests.java b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/RunsLastTests.java index 65dfec4dc..ff704b567 100644 --- a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/RunsLastTests.java +++ b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/RunsLastTests.java @@ -48,7 +48,8 @@ public class RunsLastTests { "must be the last Flow Element and outside any parallel group"; private static void assertRefused(PipelineBuilder builder) { - try (Pipeline pipeline = builder.build()) { + try { + builder.build().close(); fail("A Pipeline with the element anywhere but last was built."); } catch (PipelineConfigurationException e) { assertTrue(e.getMessage(), e.getMessage().contains(MUST_BE_LAST)); @@ -100,8 +101,8 @@ private static ElementOptions multiplyBy() { } private static void assertRefusedFrom(PipelineOptions options) { - try (Pipeline pipeline = - new PipelineBuilder().buildFromConfiguration(options)) { + try { + new PipelineBuilder().buildFromConfiguration(options).close(); fail("A Pipeline with the element anywhere but last was built " + "from a configuration."); } catch (PipelineConfigurationException e) { diff --git a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/TestPipeline.java b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/TestPipeline.java index 777a5cba4..29dec6f5a 100644 --- a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/TestPipeline.java +++ b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/flowelements/TestPipeline.java @@ -92,7 +92,7 @@ public FlowData createFlowData() { } @Override - public void close() throws Exception { + public void close() { pipeline.close(); } diff --git a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/testclasses/services/TestAutoCloseableService.java b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/testclasses/services/TestAutoCloseableService.java index 0c80405ce..4cdc3a8be 100644 --- a/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/testclasses/services/TestAutoCloseableService.java +++ b/pipeline/pipeline.core/src/test/java/fiftyone/pipeline/core/testclasses/services/TestAutoCloseableService.java @@ -25,5 +25,6 @@ import fiftyone.pipeline.core.services.PipelineService; public interface TestAutoCloseableService extends PipelineService, AutoCloseable { - + @Override + void close(); } diff --git a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/DerivedScriptFault.java b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/DerivedScriptFault.java index 0b5bdc6a0..24371c48e 100644 --- a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/DerivedScriptFault.java +++ b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/DerivedScriptFault.java @@ -31,10 +31,15 @@ public final class DerivedScriptFault implements Serializable { private static final long serialVersionUID = 1L; + /** The name the script was given, or empty where it had none. */ private final String script; + /** The built-in script's name, the file path, or "code". */ private final String source; + /** The place in the document, or empty for the document as a whole. */ private final String path; + /** The one based line, or 0 where the parser gave none. */ private final int line; + /** What is wrong. */ private final String message; /** @@ -61,6 +66,7 @@ public DerivedScriptFault( } /** + * Returns the name the script was given, or empty where it had none. * @return the name the script was given, or empty where it had none */ public String getScript() { @@ -68,6 +74,7 @@ public String getScript() { } /** + * Returns the built-in script's name, the file path, or "code". * @return the built-in script's name, the file path, or "code" */ public String getSource() { @@ -75,6 +82,8 @@ public String getSource() { } /** + * Returns the place in the document, such as Rules[3].When.All[1], or empty + * for the document as a whole. * @return the place in the document, such as Rules[3].When.All[1], or * empty for the document as a whole */ @@ -83,6 +92,7 @@ public String getPath() { } /** + * Returns the one based line, or 0 where the parser gave none. * @return the one based line, or 0 where the parser gave none */ public int getLine() { @@ -90,6 +100,7 @@ public int getLine() { } /** + * Returns what is wrong. * @return what is wrong */ public String getMessage() { diff --git a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/DerivedScriptValidationException.java b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/DerivedScriptValidationException.java index 3b0681342..f9d90928d 100644 --- a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/DerivedScriptValidationException.java +++ b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/DerivedScriptValidationException.java @@ -35,6 +35,7 @@ public class DerivedScriptValidationException extends RuntimeException { private static final long serialVersionUID = 1L; + /** Every fault found. */ private final DerivedScriptFault[] faults; /** @@ -47,6 +48,7 @@ public DerivedScriptValidationException(List faults) { } /** + * Returns every fault found, in the order found. * @return every fault found, in the order found */ public List getFaults() { diff --git a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedOutputMetaData.java b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedOutputMetaData.java index 73a03b80b..096d60401 100644 --- a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedOutputMetaData.java +++ b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedOutputMetaData.java @@ -62,6 +62,7 @@ public final class DerivedOutputMetaData { } /** + * Returns the property name published under the derived Element Data key. * @return the property name published under the derived Element Data * key */ @@ -70,6 +71,7 @@ public String getName() { } /** + * Returns what the property asserts. * @return what the property asserts */ public String getDescription() { @@ -77,6 +79,7 @@ public String getDescription() { } /** + * Returns string, bool, int or double. * @return string, bool, int or double */ public String getValueType() { @@ -84,6 +87,8 @@ public String getValueType() { } /** + * Returns the Java type of the value, being {@link String}, {@link + * Boolean}, {@link Integer} or {@link Double}. * @return the Java type of the value, being {@link String}, * {@link Boolean}, {@link Integer} or {@link Double} */ @@ -91,11 +96,17 @@ public Class getValueClass() { return output.getValueType().getValueClass(); } + /** + * The StoredValueType field. + * + * @return the field, or null when the script does not give it + */ public String getStoredValueType() { return output.getStoredValueType(); } /** + * Returns the string form of the default recorded for the property. * @return the string form of the default recorded for the property. * This is metadata only, and nothing reads it while a request is * processed. @@ -105,45 +116,87 @@ public String getDefaultValue() { } /** + * Returns false, as format 1 has no list outputs. * @return false, as format 1 has no list outputs */ public boolean isList() { return output.isList(); } + /** + * The IsMandatory field. + * + * @return the field, or null when the script does not give it + */ public Boolean getIsMandatory() { return output.getIsMandatory(); } + /** + * The IsObsolete field. + * + * @return the field, or null when the script does not give it + */ public Boolean getIsObsolete() { return output.getIsObsolete(); } + /** + * The Category field. + * + * @return the field, or null when the script does not give it + */ public String getCategory() { return output.getCategory(); } + /** + * The IsPopular field. + * + * @return the field, or null when the script does not give it + */ public Boolean getIsPopular() { return output.getIsPopular(); } + /** + * The ExportValues field. + * + * @return the field, or null when the script does not give it + */ public Boolean getExportValues() { return output.getExportValues(); } + /** + * The Url field. + * + * @return the field, or null when the script does not give it + */ public String getUrl() { return output.getUrl(); } + /** + * The DisplayOrder field. + * + * @return the field, or null when the script does not give it + */ public Long getDisplayOrder() { return output.getDisplayOrder(); } + /** + * The PropertyId field. + * + * @return the field, or null when the script does not give it + */ public Long getPropertyId() { return output.getPropertyId(); } /** + * Returns the list as written, with numbers as {@link Double}. * @return the list as written, with numbers as {@link Double} */ public List getVendorIds() { @@ -151,6 +204,8 @@ public List getVendorIds() { } /** + * Returns the list the script gives, or every source property its checks + * and rules name, in elementKey.PropertyName form, where it gives none. * @return the list the script gives, or every source property its * checks and rules name, in elementKey.PropertyName form, where it gives * none @@ -160,6 +215,8 @@ public List getDependencies() { } /** + * Returns the values the property can have, or null where the script gives + * no list. * @return the values the property can have, or null where the script * gives no list */ diff --git a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedPropertyMetaData.java b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedPropertyMetaData.java index 614774c7d..18bdf55f0 100644 --- a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedPropertyMetaData.java +++ b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedPropertyMetaData.java @@ -48,6 +48,7 @@ public final class DerivedPropertyMetaData { } /** + * Returns the script's name, which is what selects it. * @return the script's name, which is what selects it */ public String getName() { @@ -55,6 +56,8 @@ public String getName() { } /** + * Returns the author's semantic version, which plays no part in selecting + * the script. * @return the author's semantic version, which plays no part in * selecting the script */ @@ -63,17 +66,24 @@ public String getVersion() { } /** + * Returns the version of the script language, which is 1. * @return the version of the script language, which is 1 */ public int getFormat() { return format; } + /** + * Whether the script is marked deprecated. + * + * @return true if it is + */ public boolean isDeprecated() { return deprecated; } /** + * Returns what to use instead, or empty where the script is not deprecated. * @return what to use instead, or empty where the script is not * deprecated */ @@ -82,6 +92,7 @@ public String getDeprecationNote() { } /** + * Returns the built-in script's name, the file path, or "code". * @return the built-in script's name, the file path, or "code" */ public String getSource() { @@ -89,6 +100,7 @@ public String getSource() { } /** + * Returns the definition of the property the script produces. * @return the definition of the property the script produces */ public DerivedOutputMetaData getOutput() { diff --git a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedValueMetaData.java b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedValueMetaData.java index 509daa525..03bf1f8f1 100644 --- a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedValueMetaData.java +++ b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/DerivedValueMetaData.java @@ -37,6 +37,7 @@ public final class DerivedValueMetaData { } /** + * Returns the string form of the value, as a rule's value is compared. * @return the string form of the value, as a rule's value is compared */ public String getName() { @@ -44,6 +45,7 @@ public String getName() { } /** + * Returns the description, or null where the script gives none. * @return the description, or null where the script gives none */ public String getDescription() { diff --git a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/IDerivedPropertyElement.java b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/IDerivedPropertyElement.java index fbbaff234..62041dbcb 100644 --- a/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/IDerivedPropertyElement.java +++ b/pipeline/pipeline.derivedproperty/src/main/java/fiftyone/pipeline/derivedproperty/flowelements/IDerivedPropertyElement.java @@ -38,6 +38,8 @@ public interface IDerivedPropertyElement extends FlowElement { /** + * Returns the metadata of every script the element holds, in the order the + * scripts were added. * @return the metadata of every script the element holds, in the order * the scripts were added */ diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/pom.xml b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/pom.xml index 043b261e6..5a0875c46 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/pom.xml +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/pom.xml @@ -96,7 +96,6 @@ ${maven-war-plugin.version} src/main/webapp - SimpleClientSideEngineExample false diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/ExampleLauncher.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/ExampleLauncher.java index a0f3695ab..0d458d9d9 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/ExampleLauncher.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/ExampleLauncher.java @@ -24,7 +24,18 @@ import static fiftyone.pipeline.developerexamples.web.shared.EmbedTomcat.runWebApp; +/** Starts the Spring MVC example in an embedded Tomcat. */ public class ExampleLauncher { + /** Create a new instance. */ + public ExampleLauncher() { + } + + /** + * Start the example in an embedded Tomcat. + * + * @param args not used + * @throws LifecycleException if Tomcat could not start + */ public static void main(String[] args) throws LifecycleException { runWebApp( "pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/webapp", diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/configuration/ExampleConfig.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/configuration/ExampleConfig.java index 8b3330f22..8f14afddc 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/configuration/ExampleConfig.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/configuration/ExampleConfig.java @@ -38,11 +38,13 @@ import static fiftyone.pipeline.web.mvc.components.FiftyOneInterceptor.enableClientsideProperties; +/** Configures Spring MVC and the 51Degrees interceptor for the example. */ @EnableWebMvc @Configuration @ComponentScan({"controller","fiftyone.pipeline.web.mvc"}) public class ExampleConfig implements WebMvcConfigurer { + /** Create a new instance. */ public ExampleConfig() { super(); } @@ -55,6 +57,11 @@ public void addViewControllers(final ViewControllerRegistry registry) { @Autowired ServletContext servletContext; + /** + * Configure the interceptor from the Pipeline options file. + * + * @return the interceptor configuration + */ @Bean public FiftyOneInterceptorConfig fiftyOneInterceptorConfig() { final FiftyOneInterceptorConfigDefault bean = new FiftyOneInterceptorConfigDefault(); @@ -65,6 +72,11 @@ public FiftyOneInterceptorConfig fiftyOneInterceptorConfig() { return bean; } + /** + * Resolve views to the JSP files in WEB-INF/views. + * + * @return the view resolver + */ @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/configuration/ExampleInitializer.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/configuration/ExampleInitializer.java index a2a119cbb..9d10ff2dc 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/configuration/ExampleInitializer.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/configuration/ExampleInitializer.java @@ -24,7 +24,11 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; +/** Sets up the Spring dispatcher servlet with {@link ExampleConfig}. */ public class ExampleInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + /** Create a new instance. */ + public ExampleInitializer() { + } @Override protected Class[] getRootConfigClasses() { diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/controller/ExampleController.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/controller/ExampleController.java index 9c626efbb..8382f4d39 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/controller/ExampleController.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element-mvc/src/main/java/controller/ExampleController.java @@ -35,6 +35,7 @@ import java.util.Random; //! [class] +/** Shows the star sign for the date of birth the browser sends. */ @Controller @RequestMapping("/") public class ExampleController { @@ -43,11 +44,23 @@ public class ExampleController { private final Random rand = new Random(); + /** + * Create a new instance. + * + * @param flowDataProvider gives the Flow Data for each request + */ @Autowired public ExampleController(FlowDataProvider flowDataProvider) { this.flowDataProvider = flowDataProvider; } + /** + * Show the star sign for the request. + * + * @param model holds the values the page shows + * @param request the request + * @return the name of the view + */ @RequestMapping(method = RequestMethod.GET) public String get(ModelMap model, HttpServletRequest request) { String message = ""; diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/data/StarSign.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/data/StarSign.java index cd5a67ed9..0056fb179 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/data/StarSign.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/data/StarSign.java @@ -25,11 +25,19 @@ import java.util.Calendar; //! [class] +/** A star sign and the days of the year it covers. */ public class StarSign { private final Calendar end; private final Calendar start; private final String name; + /** + * Create a new instance. + * + * @param name the name of the star sign + * @param start the first day, as dd/mm + * @param end the last day, as dd/mm + */ public StarSign(String name, String start, String end) { this.name = name; this.start = dayOfYear(start); @@ -70,14 +78,29 @@ public boolean contains(Calendar day) { return day.compareTo(start) >= 0 || day.compareTo(end) <= 0; } + /** + * The name of the star sign. + * + * @return the name + */ public String getName() { return name; } + /** + * The first day of the star sign. Only the day and month are used. + * + * @return the first day + */ public Calendar getStart() { return start; } + /** + * The last day of the star sign. Only the day and month are used. + * + * @return the last day + */ public Calendar getEnd() { return end; } diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/data/StarSignData.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/data/StarSignData.java index c7ad91c39..78e811e13 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/data/StarSignData.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/data/StarSignData.java @@ -26,9 +26,20 @@ import fiftyone.pipeline.core.data.types.JavaScript; //! [class] +/** The star sign the element returns. */ public interface StarSignData extends ElementData { + /** + * The star sign for the date of birth given. + * + * @return the name of the star sign + */ String getStarSign(); + /** + * JavaScript that asks for the date of birth, empty when one was given. + * + * @return the JavaScript + */ JavaScript getDobJavaScript(); } //! [class] diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/flowelements/SimpleClientSideElement.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/flowelements/SimpleClientSideElement.java index f4d75f647..972d17cc2 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/flowelements/SimpleClientSideElement.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/flowelements/SimpleClientSideElement.java @@ -41,6 +41,12 @@ //! [constructor] public class SimpleClientSideElement extends FlowElementBase { + /** + * Create a new instance. + * + * @param logger used for logging + * @param elementDataFactory creates the element data this element returns + */ public SimpleClientSideElement( Logger logger, ElementDataFactory elementDataFactory) { diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/flowelements/SimpleClientSideElementBuilder.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/flowelements/SimpleClientSideElementBuilder.java index fa33b8fcf..b36ba12ca 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/flowelements/SimpleClientSideElementBuilder.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.clientside-element/src/main/java/fiftyone/pipeline/developerexamples/clientsideelement/flowelements/SimpleClientSideElementBuilder.java @@ -30,14 +30,25 @@ import org.slf4j.ILoggerFactory; //! [class] +/** Builder for the {@link SimpleClientSideElement}. */ @ElementBuilder(alternateName = "SimpleClientSideElement") public class SimpleClientSideElementBuilder { private final ILoggerFactory loggerFactory; + /** + * Create a new builder. + * + * @param loggerFactory creates the loggers the element uses + */ public SimpleClientSideElementBuilder(ILoggerFactory loggerFactory) { this.loggerFactory = loggerFactory; } + /** + * Build an element. + * + * @return a new element + */ public SimpleClientSideElement build() { return new SimpleClientSideElement( loggerFactory.getLogger(SimpleClientSideElement.class.getName()), diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/Main.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/Main.java index 95295c8c1..9ac949612 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/Main.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/Main.java @@ -36,7 +36,12 @@ import java.io.PrintStream; +/** Shows how to build and use a custom cloud engine. */ public class Main { + /** Create a new instance. */ + public Main() { + } + private static final ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); private static final HttpClient httpClient = new HttpClientDefault(); @@ -125,7 +130,17 @@ static String env(String name) { return value == null || value.trim().isEmpty() ? null : value.trim(); } + /** Runs the example. */ public static class Example { + /** Create a new instance. */ + public Example() { + } + + /** + * Run the example. + * + * @throws Exception if the example fails + */ public void run() throws Exception { //! [usage] // The endpoint comes from _51DEGREES_CLOUD_ENDPOINT when it is @@ -202,6 +217,12 @@ static void writeFindOutMore(PrintStream output) { output.flush(); } + /** + * Run the example, then print where to find out more. + * + * @param args not used + * @throws Exception if the example fails + */ public static void main(String[] args) throws Exception { new Example().run(); writeFindOutMore(System.out); diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/data/StarSign.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/data/StarSign.java index 2602744ea..d6c91caa8 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/data/StarSign.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/data/StarSign.java @@ -25,11 +25,19 @@ import java.util.Calendar; //! [class] +/** A star sign and the days of the year it covers. */ public class StarSign { private final Calendar end; private final Calendar start; private final String name; + /** + * Create a new instance. + * + * @param name the name of the star sign + * @param start the first day, as dd/mm + * @param end the last day, as dd/mm + */ public StarSign(String name, String start, String end) { this.name = name; this.start = Calendar.getInstance(); @@ -46,14 +54,29 @@ public StarSign(String name, String start, String end) { Integer.parseInt(endDate[0])); } + /** + * The name of the star sign. + * + * @return the name + */ public String getName() { return name; } + /** + * The first day of the star sign. Only the day and month are used. + * + * @return the first day + */ public Calendar getStart() { return start; } + /** + * The last day of the star sign. Only the day and month are used. + * + * @return the last day + */ public Calendar getEnd() { return end; } diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/data/StarSignData.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/data/StarSignData.java index 2540b8adf..6b6bbe598 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/data/StarSignData.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/data/StarSignData.java @@ -25,7 +25,13 @@ import fiftyone.pipeline.engines.data.AspectData; //! [class] +/** The star sign the element returns. */ public interface StarSignData extends AspectData { + /** + * The star sign for the date of birth given. + * + * @return the name of the star sign + */ String getStarSign(); } //! [class] diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/flowelements/SimpleCloudEngine.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/flowelements/SimpleCloudEngine.java index f476acb6e..986e70435 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/flowelements/SimpleCloudEngine.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/flowelements/SimpleCloudEngine.java @@ -41,10 +41,19 @@ //! [class] //! [constructor] +/** + * A cloud engine that reads the star sign from the cloud service's response. + */ public class SimpleCloudEngine extends CloudAspectEngineBase { private List aspectProperties; private String dataSourceTier; + /** + * Create a new instance. + * + * @param logger used for logging + * @param dataFactory creates the element data this engine returns + */ public SimpleCloudEngine( Logger logger, ElementDataFactory dataFactory) { diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/flowelements/SimpleCloudEngineBuilder.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/flowelements/SimpleCloudEngineBuilder.java index 699f4a927..f9338a5a0 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/flowelements/SimpleCloudEngineBuilder.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.cloud-engine/src/main/java/pipeline/developerexamples/cloudengine/flowelements/SimpleCloudEngineBuilder.java @@ -34,11 +34,17 @@ //! [class] +/** Builder for the {@link SimpleCloudEngine}. */ public class SimpleCloudEngineBuilder extends CloudAspectEngineBuilderBase< SimpleCloudEngineBuilder, SimpleCloudEngine> { + /** + * Create a new builder. + * + * @param loggerFactory creates the loggers the element uses + */ public SimpleCloudEngineBuilder( ILoggerFactory loggerFactory) { super(loggerFactory); @@ -62,6 +68,12 @@ public StarSignData create( }); } + /** + * Build an engine using the current options. + * + * @return a new engine + * @throws Exception if the engine could not be created + */ public SimpleCloudEngine build() throws Exception { return buildEngine(); } diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/Main.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/Main.java index 8246fc9cb..e4f1c636c 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/Main.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/Main.java @@ -48,7 +48,7 @@ import java.util.List; /** - * @example derivedproperty/Main.java + * \example derivedproperty/Main.java * * The Derived Property Element computes new properties from properties * that other elements in the Pipeline have already produced, following a @@ -75,12 +75,15 @@ * This example is available in full on [GitHub](https://github.com/51Degrees/51degrees-java/blob/main/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/Main.java). * * The script file the example reads is - * @include pipeline.developer-examples.derivedproperty/src/main/resources/ReaderEngagement.yaml + * \include pipeline.developer-examples.derivedproperty/src/main/resources/ReaderEngagement.yaml * * and the configuration file is - * @include pipeline.developer-examples.derivedproperty/src/main/resources/derived-property.xml + * \include pipeline.developer-examples.derivedproperty/src/main/resources/derived-property.xml */ public class Main { + /** Create a new instance. */ + public Main() { + } private static final ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); @@ -141,7 +144,11 @@ public class Main { private static final String RULE = "----------------------------------------------------------------"; + /** Runs the example. */ public static class Example { + /** Create a new instance. */ + public Example() { + } /** * Run the example. @@ -367,6 +374,12 @@ static void writeFindOutMore(PrintStream output) { output.flush(); } + /** + * Run the example, then print where to find out more. + * + * @param args not used + * @throws Exception if the example fails + */ public static void main(String[] args) throws Exception { new Example().run(System.out); writeFindOutMore(System.out); diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/flowelements/SessionElement.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/flowelements/SessionElement.java index 3820431fc..7611cca1b 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/flowelements/SessionElement.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/flowelements/SessionElement.java @@ -75,8 +75,11 @@ public final class SessionElement */ public static final String POINTER_MOVED_EVIDENCE = "query.pointermoved"; + /** Name of the pages viewed property. */ public static final String PAGES_VIEWED = "PagesViewed"; + /** Name of the seconds since page load property. */ public static final String SECONDS_SINCE_PAGE_LOAD = "SecondsSincePageLoad"; + /** Name of the pointer moved property. */ public static final String POINTER_MOVED = "PointerMoved"; private final EvidenceKeyFilter evidenceKeyFilter = diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/flowelements/SessionElementBuilder.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/flowelements/SessionElementBuilder.java index 6aebf9a6f..159eb8252 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/flowelements/SessionElementBuilder.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.derivedproperty/src/main/java/pipeline/developerexamples/derivedproperty/flowelements/SessionElementBuilder.java @@ -43,6 +43,7 @@ public SessionElementBuilder(ILoggerFactory loggerFactory) { } /** + * Returns a new element. * @return a new element */ public SessionElement build() { diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/Main.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/Main.java index 2fe22edcf..539e84dae 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/Main.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/Main.java @@ -34,11 +34,26 @@ import java.text.SimpleDateFormat; import java.util.Calendar; +/** Shows how to build and use a custom Flow Element. */ public class Main { + /** Create a new instance. */ + public Main() { + } + private static final ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); + /** Runs the example. */ public static class Example { + /** Create a new instance. */ + public Example() { + } + + /** + * Run the example. + * + * @throws Exception if the example fails + */ public void run() throws Exception { //! [usage] @@ -93,6 +108,12 @@ static void writeFindOutMore(PrintStream output) { output.flush(); } + /** + * Run the example, then print where to find out more. + * + * @param args not used + * @throws Exception if the example fails + */ public static void main(String[] args) throws Exception { new Example().run(); writeFindOutMore(System.out); diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/data/StarSign.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/data/StarSign.java index acb708361..80284b03e 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/data/StarSign.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/data/StarSign.java @@ -25,11 +25,19 @@ import java.util.Calendar; //! [class] +/** A star sign and the days of the year it covers. */ public class StarSign { private final Calendar end; private final Calendar start; private final String name; + /** + * Create a new instance. + * + * @param name the name of the star sign + * @param start the first day, as dd/mm + * @param end the last day, as dd/mm + */ public StarSign(String name, String start, String end) { this.name = name; this.start = Calendar.getInstance(); @@ -46,14 +54,29 @@ public StarSign(String name, String start, String end) { Integer.parseInt(endDate[0])); } + /** + * The name of the star sign. + * + * @return the name + */ public String getName() { return name; } + /** + * The first day of the star sign. Only the day and month are used. + * + * @return the first day + */ public Calendar getStart() { return start; } + /** + * The last day of the star sign. Only the day and month are used. + * + * @return the last day + */ public Calendar getEnd() { return end; } diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/data/StarSignData.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/data/StarSignData.java index 10b95cb85..d58888516 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/data/StarSignData.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/data/StarSignData.java @@ -25,7 +25,13 @@ import fiftyone.pipeline.core.data.ElementData; //! [class] +/** The star sign the element returns. */ public interface StarSignData extends ElementData { + /** + * The star sign for the date of birth given. + * + * @return the name of the star sign + */ String getStarSign(); } //! [class] \ No newline at end of file diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/flowelements/SimpleFlowElement.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/flowelements/SimpleFlowElement.java index 7d5fb99b3..03cb658c1 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/flowelements/SimpleFlowElement.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/flowelements/SimpleFlowElement.java @@ -33,8 +33,15 @@ //! [class] //! [constructor] +/** A Flow Element that finds the star sign for a date of birth. */ public class SimpleFlowElement extends FlowElementBase { + /** + * Create a new instance. + * + * @param logger used for logging + * @param elementDataFactory creates the element data this element returns + */ public SimpleFlowElement( Logger logger, ElementDataFactory elementDataFactory) { diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/flowelements/SimpleFlowElementBuilder.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/flowelements/SimpleFlowElementBuilder.java index 56137176e..44a7d92dc 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/flowelements/SimpleFlowElementBuilder.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.flowelement/src/main/java/pipeline/developerexamples/flowelement/flowelements/SimpleFlowElementBuilder.java @@ -29,13 +29,24 @@ import org.slf4j.ILoggerFactory; //! [class] +/** Builder for the {@link SimpleFlowElement}. */ public class SimpleFlowElementBuilder { private final ILoggerFactory loggerFactory; + /** + * Create a new builder. + * + * @param loggerFactory creates the loggers the element uses + */ public SimpleFlowElementBuilder(ILoggerFactory loggerFactory) { this.loggerFactory = loggerFactory; } + /** + * Build an element. + * + * @return a new element + */ public SimpleFlowElement build() { return new SimpleFlowElement( loggerFactory.getLogger(SimpleFlowElement.class.getName()), diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/CreatorContextDemoServer.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/CreatorContextDemoServer.java index 4a8063f38..9b97e7a02 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/CreatorContextDemoServer.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/CreatorContextDemoServer.java @@ -116,6 +116,9 @@ * Then open {@code http://localhost:5151/}. */ public class CreatorContextDemoServer { + /** Create a new instance. */ + public CreatorContextDemoServer() { + } /** Where the page and stylesheet live on the classpath. */ static final String RESOURCES = "/fodid/creator-context/"; @@ -139,6 +142,12 @@ public class CreatorContextDemoServer { */ static DidClient client; + /** + * Start the demo server, or say how to set a resource key when none is set. + * + * @param args not used + * @throws Exception if the server fails + */ public static void main(String[] args) throws Exception { if (RESOURCE == null) { System.out.println("This demo calls the 51Degrees cloud " + diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/Main.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/Main.java index 26d0f0b61..ab3af3b6a 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/Main.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.fodid/src/main/java/pipeline/developerexamples/fodid/Main.java @@ -42,6 +42,9 @@ * is stable. Compare match keys, never envelopes. */ public class Main { + /** Create a new instance. */ + public Main() { + } private static final String DOMAIN = "51degrees.com"; @@ -57,8 +60,17 @@ public class Main { private static final int PAYLOAD_LENGTH = MATCH_KEY_OFFSET + MATCH_KEY_LENGTH; + /** Runs the example. */ public static class Example { + /** Create a new instance. */ + public Example() { + } + /** + * Run the example. + * + * @throws Exception if the example fails + */ public void run() throws Exception { // Generate a key pair and a signer entirely in process. Crypto crypto = Crypto.generate(); @@ -164,6 +176,12 @@ static void writeFindOutMore(PrintStream output) { output.flush(); } + /** + * Run the example, then print where to find out more. + * + * @param args not used + * @throws Exception if the example fails + */ public static void main(String[] args) throws Exception { new Example().run(); writeFindOutMore(System.out); diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/Main.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/Main.java index 0d585136c..a716f10ad 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/Main.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/Main.java @@ -34,11 +34,26 @@ import java.text.SimpleDateFormat; import java.util.Calendar; +/** Shows how to build and use a custom on-premise engine. */ public class Main { + /** Create a new instance. */ + public Main() { + } + private static final ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); + /** Runs the example. */ public static class Example { + /** Create a new instance. */ + public Example() { + } + + /** + * Run the example. + * + * @throws Exception if the example fails + */ public void run() throws Exception { //! [usage] SimpleOnPremiseEngine starSignEngine = @@ -96,6 +111,12 @@ static void writeFindOutMore(PrintStream output) { output.flush(); } + /** + * Run the example, then print where to find out more. + * + * @param args not used + * @throws Exception if the example fails + */ public static void main(String[] args) throws Exception { new Example().run(); writeFindOutMore(System.out); diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/data/StarSign.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/data/StarSign.java index 9cf2b1c22..336c4f62e 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/data/StarSign.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/data/StarSign.java @@ -25,11 +25,19 @@ import java.util.Calendar; //! [class] +/** A star sign and the days of the year it covers. */ public class StarSign { private final Calendar end; private final Calendar start; private final String name; + /** + * Create a new instance. + * + * @param name the name of the star sign + * @param start the first day, as dd/mm + * @param end the last day, as dd/mm + */ public StarSign(String name, String start, String end) { this.name = name; this.start = Calendar.getInstance(); @@ -46,14 +54,29 @@ public StarSign(String name, String start, String end) { Integer.parseInt(endDate[0])); } + /** + * The name of the star sign. + * + * @return the name + */ public String getName() { return name; } + /** + * The first day of the star sign. Only the day and month are used. + * + * @return the first day + */ public Calendar getStart() { return start; } + /** + * The last day of the star sign. Only the day and month are used. + * + * @return the last day + */ public Calendar getEnd() { return end; } diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/data/StarSignData.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/data/StarSignData.java index df37df036..f5fed3931 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/data/StarSignData.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/data/StarSignData.java @@ -25,7 +25,13 @@ import fiftyone.pipeline.engines.data.AspectData; //! [class] +/** The star sign the element returns. */ public interface StarSignData extends AspectData { + /** + * The star sign for the date of birth given. + * + * @return the name of the star sign + */ String getStarSign(); } //! [class] diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/flowelements/SimpleOnPremiseEngine.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/flowelements/SimpleOnPremiseEngine.java index c453bd1a4..529a353d8 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/flowelements/SimpleOnPremiseEngine.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/flowelements/SimpleOnPremiseEngine.java @@ -38,8 +38,21 @@ //! [class] //! [constructor] +/** + * An on-premise engine that finds the star sign for a date of birth from a data + * file. + */ public class SimpleOnPremiseEngine extends OnPremiseAspectEngineBase { + /** + * Create a new instance and read the data file. + * + * @param dataFile path of the data file + * @param logger used for logging + * @param elementDataFactory creates the element data this engine returns + * @param tempDir folder for temporary copies of the data file + * @throws IOException if the data file could not be read + */ public SimpleOnPremiseEngine( String dataFile, Logger logger, diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/flowelements/SimpleOnPremiseEngineBuilder.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/flowelements/SimpleOnPremiseEngineBuilder.java index 310c142fb..2aa1faa0b 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/flowelements/SimpleOnPremiseEngineBuilder.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.onpremise-engine/src/main/java/pipeline/developerexamples/onpremiseengine/flowelements/SimpleOnPremiseEngineBuilder.java @@ -37,11 +37,17 @@ //! [class] +/** Builder for the {@link SimpleOnPremiseEngine}. */ public class SimpleOnPremiseEngineBuilder extends SingleFileAspectEngineBuilderBase< SimpleOnPremiseEngineBuilder, SimpleOnPremiseEngine> { + /** + * Create a new builder. + * + * @param loggerFactory creates the loggers the element uses + */ public SimpleOnPremiseEngineBuilder(ILoggerFactory loggerFactory) { super(loggerFactory); } diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.usage-sharing/src/main/java/pipeline/developerexamples/usagesharing/Main.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.usage-sharing/src/main/java/pipeline/developerexamples/usagesharing/Main.java index cb4ca6e86..7cf16308c 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.usage-sharing/src/main/java/pipeline/developerexamples/usagesharing/Main.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.usage-sharing/src/main/java/pipeline/developerexamples/usagesharing/Main.java @@ -34,11 +34,12 @@ import java.io.File; import java.io.PrintStream; import java.util.Objects; +import java.util.stream.Collectors; /** - * @example usagesharing/Main.java + * \example usagesharing/Main.java * - * @include{doc} example-usage-sharing-intro.txt + * \include{doc} example-usage-sharing-intro.txt * * Usage sharing is enabled by default if using a pipeline builder * that is derived from FiftyOnePipelineBuilder. @@ -54,7 +55,7 @@ * These are all optional, so each can be omitted if the default * for that option is sufficient: * - * @include pipeline.developer-examples.usage-sharing/src/main/resources/51d.xml + * \include pipeline.developer-examples.usage-sharing/src/main/resources/51d.xml * * For details of what each setting does, see the * [Share Usage reference](/documentation/4.5/_pipeline_api__features__usage_sharing.html) @@ -72,6 +73,10 @@ */ public class Main { + /** Create a new instance. */ + public Main() { + } + private static final ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); @@ -79,7 +84,17 @@ public class Main { // data back to 51Degrees. private static final HttpClient http = new HttpClientDefault(); + /** Runs the example. */ public static class Example { + /** Create a new instance. */ + public Example() { + } + + /** + * Run the example. + * + * @throws Exception if the example fails + */ public void run() throws Exception { System.out.println("Constructing pipeline from configuration file."); System.out.println(); @@ -112,6 +127,11 @@ public void run() throws Exception { "Pipeline created with share usage element. Evidence processed " + "with this pipeline will now be periodically shared with " + "51Degrees using the specified configuration."); + System.out.println( + "The Pipeline's elements are " + + pipeline.getFlowElements().stream() + .map(element -> element.getClass().getSimpleName()) + .collect(Collectors.joining(", ")) + "."); } } } @@ -139,6 +159,12 @@ static void writeFindOutMore(PrintStream output) { output.flush(); } + /** + * Run the example, then print where to find out more. + * + * @param args not used + * @throws Exception if the example fails + */ public static void main(String[] args) throws Exception { new Example().run(); writeFindOutMore(System.out); diff --git a/pipeline/pipeline.developer-examples/pipeline.developer-examples.web.shared/src/main/java/fiftyone/pipeline/developerexamples/web/shared/EmbedTomcat.java b/pipeline/pipeline.developer-examples/pipeline.developer-examples.web.shared/src/main/java/fiftyone/pipeline/developerexamples/web/shared/EmbedTomcat.java index 0597349cd..2b27fb99d 100644 --- a/pipeline/pipeline.developer-examples/pipeline.developer-examples.web.shared/src/main/java/fiftyone/pipeline/developerexamples/web/shared/EmbedTomcat.java +++ b/pipeline/pipeline.developer-examples/pipeline.developer-examples.web.shared/src/main/java/fiftyone/pipeline/developerexamples/web/shared/EmbedTomcat.java @@ -33,19 +33,27 @@ import java.nio.file.Files; import java.util.Scanner; -/* +/** * Create and start embedded Tomcat server for Servlet Web Examples */ public class EmbedTomcat { + /** The running server. */ public static Tomcat tomcat; + /** Create a new instance. Every member is static. */ + public EmbedTomcat() { + } + /** * Utility to start Tomcat with the servlet supplied * @param servletName a name * @param urlPattern a mapping for the addresses the servlet will respond to * @param servlet an instantiated servlet + * @param port the port to listen on * @return a server context + * @throws LifecycleException if Tomcat could not start + * @throws IOException if the temporary folder could not be created */ public static Context startTomcat(String servletName, String urlPattern, HttpServlet servlet, int port) throws LifecycleException, IOException { tomcat = new Tomcat(); @@ -83,10 +91,12 @@ public static void stopTomcat() { } /** - * Utility to run a servlet in Tomcat at the server root address - wait and then shut down + * Utility to run a webapp in Tomcat at the server root address, wait + * and then shut down * @param pathname path to the webapp folder from project root * @param workingDir where Tomcat should put its temp files etc * @param port the port to listen on + * @throws LifecycleException if Tomcat could not start or stop */ public static void runWebApp(String pathname, String workingDir, int port) throws LifecycleException { System.setProperty("logback.configurationFile", "./logback.xml"); @@ -107,11 +117,12 @@ public static void runWebApp(String pathname, String workingDir, int port) throw } /** - * Utility to run a webapp in Tomcat - wait and then shut down + * Utility to run a servlet in Tomcat - wait and then shut down * @param servlet a servlet * @param workingDir where Tomcat should put its temp files etc - * @param urlPattern where servlet should be releative to server root + * @param urlPattern where servlet should be relative to server root * @param port the port to listen on + * @throws LifecycleException if Tomcat could not start or stop */ public static void runServlet(HttpServlet servlet, String workingDir, String urlPattern, int port) throws LifecycleException { System.setProperty("logback.configurationFile", "./logback.xml"); diff --git a/pipeline/pipeline.did/pom.xml b/pipeline/pipeline.did/pom.xml index a925f2780..1b0e2c33a 100644 --- a/pipeline/pipeline.did/pom.xml +++ b/pipeline/pipeline.did/pom.xml @@ -122,13 +122,14 @@ - + org.codehaus.mojo animal-sniffer-maven-plugin @@ -150,33 +151,17 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + + + com.swancommunity.owid + + - - - - owid-dangling-doc-comments - - [23,) - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - -Xlint:-dangling-doc-comments - - - - - - - - diff --git a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidClient.java b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidClient.java index c2946082f..bda4bacd2 100644 --- a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidClient.java +++ b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidClient.java @@ -259,6 +259,7 @@ private Builder(String resourceKey) { } /** + * Set a license key of the account, or null. * @param licenceKey a licence key of the account, or null * @return this builder */ @@ -268,6 +269,8 @@ public Builder licenceKey(String licenceKey) { } /** + * Set the API base including {@code /api/v4/}, or null to read {@value + * #CLOUD_ENDPOINT_VARIABLE} and fall back to {@link #DEFAULT_ENDPOINT}. * @param endpoint the API base including {@code /api/v4/}, or null * to read {@value #CLOUD_ENDPOINT_VARIABLE} and * fall back to {@link #DEFAULT_ENDPOINT} @@ -279,6 +282,8 @@ public Builder endpoint(String endpoint) { } /** + * Set the HTTP transport to send through, or null for the default + * {@link java.net.HttpURLConnection} one. * @param transport the HTTP transport to send through, or null for * the default {@link java.net.HttpURLConnection} * one @@ -305,6 +310,8 @@ public Builder executor(Executor executor) { } /** + * Set the clock the key list's age is measured by, or null for the + * system clock. * @param clock the clock the key list's age is measured by, or null * for the system clock * @return this builder @@ -314,23 +321,35 @@ public Builder clock(Clock clock) { return this; } - /** @return the client */ + /** + * Returns the client. + * @return the client + */ public DidClient build() { return new DidClient(this); } } - /** @return the resource key the client sends */ + /** + * Returns the resource key the client sends. + * @return the resource key the client sends + */ public String getResourceKey() { return resourceKey; } - /** @return the API base every request is made under, ending in a slash */ + /** + * Returns the API base every request is made under, ending in a slash. + * @return the API base every request is made under, ending in a slash + */ public String getEndpoint() { return endpoint; } - /** @return whether the client was given a licence key */ + /** + * Returns whether the client was given a license key. + * @return whether the client was given a license key + */ public boolean hasLicenceKey() { return licenceKey != null; } diff --git a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidHttpException.java b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidHttpException.java index 5a1747925..c663e0009 100644 --- a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidHttpException.java +++ b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidHttpException.java @@ -35,10 +35,13 @@ public class DidHttpException extends IOException { private static final long serialVersionUID = 1L; + /** The HTTP status code of the answer. */ private final int statusCode; + /** The content of the answer. */ private final String body; /** + * Create a new instance. * @param message what went wrong * @param statusCode the HTTP status the service answered with * @param body the body the service answered with @@ -49,7 +52,10 @@ public DidHttpException(String message, int statusCode, String body) { this.body = body == null ? "" : body; } - /** @return the HTTP status the service answered with */ + /** + * Returns the HTTP status the service answered with. + * @return the HTTP status the service answered with + */ public int getStatusCode() { return statusCode; } diff --git a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidNotSupportedException.java b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidNotSupportedException.java index c757136c7..275454c06 100644 --- a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidNotSupportedException.java +++ b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/DidNotSupportedException.java @@ -33,6 +33,7 @@ public class DidNotSupportedException extends DidHttpException { private static final long serialVersionUID = 1L; /** + * Create a new instance. * @param endpoint the API base the client was pointed at * @param body the body the host answered with */ diff --git a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/FodId.java b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/FodId.java index 7af5ed21d..3a5cf46fe 100644 --- a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/FodId.java +++ b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/FodId.java @@ -558,6 +558,7 @@ int getFlags() { } /** + * Returns the identifier type carried in bits 6-7 of the Flags byte. * @return the identifier type carried in bits 6-7 of the Flags byte */ public IdType getType() { @@ -565,6 +566,8 @@ public IdType getType() { } /** + * Returns the usage carried in bits 0-2 of the Flags byte, as the highest + * usage granted. * @return the usage carried in bits 0-2 of the Flags byte, as the * highest usage granted; see {@link Usage} for why it is read * that way @@ -649,12 +652,18 @@ public String getTerms() { return Terms.fromIndex(termsIndex).getUrl(); } - /** @return the OWID version. */ + /** + * Returns the OWID version. + * @return the OWID version. + */ public Version getVersion() { return owid.getVersion(); } - /** @return the domain of the OWID creator. */ + /** + * Returns the domain of the OWID creator. + * @return the domain of the OWID creator. + */ public String getDomain() { return owid.getDomain(); } @@ -671,12 +680,18 @@ public Instant getDate() { return owid.getDate(); } - /** @return a copy of the OWID payload bytes. */ + /** + * Returns a copy of the OWID payload bytes. + * @return a copy of the OWID payload bytes. + */ public byte[] getPayload() { return owid.getPayload(); } - /** @return a copy of the 64-byte OWID signature. */ + /** + * Returns a copy of the 64-byte OWID signature. + * @return a copy of the 64-byte OWID signature. + */ public byte[] getSignature() { return owid.getSignature(); } @@ -684,6 +699,8 @@ public byte[] getSignature() { // ----- Encoding ----- /** + * Returns the OWID as a base64 string in the standard alphabet with + * padding, the form the cloud issues. * @return the OWID as a base64 string in the standard alphabet with * padding, the form the cloud issues * @throws OwidException if a field cannot be encoded @@ -707,6 +724,7 @@ public String asBase64Url() throws OwidException { } /** + * Returns the OWID as a byte array including the signature. * @return the OWID as a byte array including the signature * @throws OwidException if a field cannot be encoded */ diff --git a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/FodIdParseResult.java b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/FodIdParseResult.java index e282b880b..5e16dfd43 100644 --- a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/FodIdParseResult.java +++ b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/FodIdParseResult.java @@ -95,6 +95,8 @@ int getPayloadVersion() { } /** + * Returns true when the input was a structurally valid 51Did and {@link + * #getValue()} holds it. * @return true when the input was a structurally valid 51Did and * {@link #getValue()} holds it */ @@ -103,6 +105,7 @@ public boolean isSuccess() { } /** + * Returns the 51Did when {@link #isSuccess()} is true, otherwise null. * @return the 51Did when {@link #isSuccess()} is true, otherwise null. * A parsed 51Did has not had its signature checked. */ @@ -111,6 +114,8 @@ public FodId getValue() { } /** + * Returns {@link FodIdParseStatus#PARSED} on success, otherwise the reason + * the input is not a 51Did. * @return {@link FodIdParseStatus#PARSED} on success, otherwise the * reason the input is not a 51Did */ diff --git a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/HttpTransport.java b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/HttpTransport.java index dc7b7c67d..f85497dcc 100644 --- a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/HttpTransport.java +++ b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/HttpTransport.java @@ -61,6 +61,7 @@ final class Request { private final byte[] body; /** + * Create a new instance. * @param method the HTTP method, {@code GET} or {@code POST} * @param url the full URL to send to * @param headers the headers to send, copied @@ -78,22 +79,34 @@ public Request( this.body = body == null ? null : body.clone(); } - /** @return the HTTP method */ + /** + * Returns the HTTP method. + * @return the HTTP method + */ public String getMethod() { return method; } - /** @return the full URL */ + /** + * Returns the full URL. + * @return the full URL + */ public String getUrl() { return url; } - /** @return the headers, read only */ + /** + * Returns the headers, read only. + * @return the headers, read only + */ public Map getHeaders() { return headers; } - /** @return a copy of the body, or null when there is none */ + /** + * Returns a copy of the body, or null when there is none. + * @return a copy of the body, or null when there is none + */ public byte[] getBody() { return body == null ? null : body.clone(); } @@ -106,6 +119,7 @@ final class Response { private final String body; /** + * Create a new instance. * @param statusCode the HTTP status code * @param body the body as text, empty when there was none */ @@ -114,12 +128,18 @@ public Response(int statusCode, String body) { this.body = body == null ? "" : body; } - /** @return the HTTP status code */ + /** + * Returns the HTTP status code. + * @return the HTTP status code + */ public int getStatusCode() { return statusCode; } - /** @return the body as text, never null */ + /** + * Returns the body as text, never null. + * @return the body as text, never null + */ public String getBody() { return body; } diff --git a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/RedeemResult.java b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/RedeemResult.java index fbeeca1b0..165bcf7ee 100644 --- a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/RedeemResult.java +++ b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/RedeemResult.java @@ -106,7 +106,10 @@ public enum Context { this.value = value; } - /** @return the word the cloud uses for this verdict */ + /** + * Returns the word the cloud uses for this verdict. + * @return the word the cloud uses for this verdict + */ public String getValue() { return value; } @@ -188,7 +191,10 @@ public enum Factor { this.value = value; } - /** @return the word the cloud uses for this outcome */ + /** + * Returns the word the cloud uses for this outcome. + * @return the word the cloud uses for this outcome + */ public String getValue() { return value; } @@ -316,12 +322,18 @@ static RedeemResult parse(int statusCode, JSONObject json, String raw) { raw); } - /** @return the creator context verdict */ + /** + * Returns the creator context verdict. + * @return the creator context verdict + */ public Context getContext() { return context; } /** + * Returns the {@code context} word exactly as the cloud sent it, so an + * unrecognized word (mapped to {@link Context#UNREADABLE}) is still + * visible. * @return the {@code context} word exactly as the cloud sent it, so an * unrecognised word (mapped to {@link Context#UNREADABLE}) is * still visible; the verdict's own word when the cloud sent none @@ -330,7 +342,10 @@ public String getContextValue() { return contextValue; } - /** @return the signature outcome */ + /** + * Returns the signature outcome. + * @return the signature outcome + */ public Signature getSignature() { return signature; } @@ -365,7 +380,10 @@ public Map getFactors() { return factors; } - /** @return whether the cloud sent {@code factors} */ + /** + * Returns whether the cloud sent {@code factors}. + * @return whether the cloud sent {@code factors} + */ public boolean hasFactors() { return hasFactors; } @@ -392,12 +410,18 @@ public Integer getSecondsSinceVerified() { return secondsSinceVerified; } - /** @return the HTTP status the cloud answered with, 200 or 503 */ + /** + * Returns the HTTP status the cloud answered with, 200 or 503. + * @return the HTTP status the cloud answered with, 200 or 503 + */ public int getStatusCode() { return statusCode; } - /** @return the response body as received */ + /** + * Returns the response body as received. + * @return the response body as received + */ public String getRaw() { return raw; } diff --git a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/SigningKey.java b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/SigningKey.java index d2dfb49d3..3d731fca8 100644 --- a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/SigningKey.java +++ b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/SigningKey.java @@ -50,6 +50,7 @@ public SigningKey(Instant startsAt, String publicKeyPem) { } /** + * Create a new instance. * @param startsAt when the key comes into force, UTC * @param publicKeyPem the public key in SPKI PEM form * @param endsAt when the key stops being in force, UTC, which must @@ -66,12 +67,17 @@ public SigningKey(Instant startsAt, String publicKeyPem, Instant endsAt) { this.endsAt = endsAt; } - /** @return when the key comes into force, UTC */ + /** + * Returns when the key comes into force, UTC. + * @return when the key comes into force, UTC + */ public Instant getStartsAt() { return startsAt; } /** + * Returns when the key stops being in force, UTC, or null where the cloud + * sent no end. * @return when the key stops being in force, UTC, or null where the * cloud sent no end */ @@ -79,7 +85,10 @@ public Instant getEndsAt() { return endsAt; } - /** @return the public key in SPKI PEM form */ + /** + * Returns the public key in SPKI PEM form. + * @return the public key in SPKI PEM form + */ public String getPublicKeyPem() { return publicKeyPem; } diff --git a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/Usage.java b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/Usage.java index 42e5deede..41eda340d 100644 --- a/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/Usage.java +++ b/pipeline/pipeline.did/src/main/java/fiftyone/pipeline/did/Usage.java @@ -88,6 +88,7 @@ public static Usage fromFlags(int flags) { } /** + * Returns the cloud's {@code id.usage} value for this usage. * @return the cloud's {@code id.usage} value for this usage */ public String getIdUsage() { diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/configuration/FiftyOneDataFileConfiguration.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/configuration/FiftyOneDataFileConfiguration.java index 2fac391f1..7343744e8 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/configuration/FiftyOneDataFileConfiguration.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/configuration/FiftyOneDataFileConfiguration.java @@ -30,6 +30,10 @@ * Data file configuration class for 51Degrees data files. */ public class FiftyOneDataFileConfiguration extends DataFileConfigurationDefault { + /** Create a new instance. */ + public FiftyOneDataFileConfiguration() { + } + @Override public DataUpdateUrlFormatter getUrlFormatter() { return new FiftyOneUrlFormatter(); diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CloseableIterable.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CloseableIterable.java index b9672a658..267b466ed 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CloseableIterable.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CloseableIterable.java @@ -27,4 +27,11 @@ * @param the type being iterated */ public interface CloseableIterable extends Iterable, AutoCloseable { + + /** + * Free what the iterable holds. It throws no checked exception, so a + * try-with-resources block needs no catch for it. + */ + @Override + void close(); } diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CloseableIterableDefault.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CloseableIterableDefault.java index 1995c5d25..f05afc2c9 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CloseableIterableDefault.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CloseableIterableDefault.java @@ -33,12 +33,17 @@ public class CloseableIterableDefault implements CloseableIterable { private final Iterable iterable; + /** + * Create a new instance. + * + * @param iterable the items to iterate over + */ public CloseableIterableDefault(Iterable iterable) { this.iterable = iterable; } @Override - public void close() throws Exception { + public void close() { } @Override diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CollectionIterableBase.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CollectionIterableBase.java index 03bfaf653..c7f9676d1 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CollectionIterableBase.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CollectionIterableBase.java @@ -24,10 +24,20 @@ import java.util.Iterator; +/** + * Iterates over a collection by index, from 0 to its size. + * + * @param the type of the items + */ public abstract class CollectionIterableBase implements CloseableIterable { private final long size; + /** + * Create a new instance. + * + * @param size the number of items + */ public CollectionIterableBase(long size) { this.size = size; } @@ -37,6 +47,12 @@ public Iterator iterator() { return new CollectionIterator(); } + /** + * Get the item at an index. + * + * @param index the index of the item + * @return the item + */ protected abstract T get(long index); private class CollectionIterator implements Iterator { diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CollectionIterableCachedBase.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CollectionIterableCachedBase.java index 5c4c6d566..40d7d0d32 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CollectionIterableCachedBase.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/CollectionIterableCachedBase.java @@ -25,10 +25,22 @@ import java.util.Iterator; import java.util.List; +/** + * Iterates over a collection by index, keeping the items in a list after the + * first pass. + * + * @param the type of the items + */ public abstract class CollectionIterableCachedBase extends CollectionIterableBase { private final List list; + /** + * Create a new instance. + * + * @param list holds the items once they have been read + * @param size the number of items + */ public CollectionIterableCachedBase(List list, long size) { super(size); this.list = list; diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/FiftyOneAspectPropertyMetaDataDefault.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/FiftyOneAspectPropertyMetaDataDefault.java index a460d8443..b51dc8e72 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/FiftyOneAspectPropertyMetaDataDefault.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/FiftyOneAspectPropertyMetaDataDefault.java @@ -29,6 +29,7 @@ import java.util.Iterator; import java.util.List; +/** Default implementation of {@link FiftyOneAspectPropertyMetaData}. */ public class FiftyOneAspectPropertyMetaDataDefault extends AspectPropertyMetaDataDefault implements FiftyOneAspectPropertyMetaData { @@ -45,6 +46,27 @@ public class FiftyOneAspectPropertyMetaDataDefault private final Iterable values; private final ValueMetaDataDefault defaultValue; + /** + * Create a new instance. + * + * @param name the property name + * @param element the element that returns the property + * @param category the category of the property + * @param type the type of the values + * @param dataTiersWherePresent the data tiers that hold the property + * @param available whether the engine returns the property + * @param url a page that describes the property + * @param displayOrder the order in which the property is shown + * @param mandatory whether the property is always returned + * @param list whether the value is a list + * @param obsolete whether the property is obsolete + * @param show whether the property is shown + * @param showValues whether its values are shown + * @param description the description of the property + * @param component the component the property belongs to + * @param values the values the property can have + * @param defaultValue the default value + */ @SuppressWarnings("this-escape") public FiftyOneAspectPropertyMetaDataDefault( String name, diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/FiftyOneDataFileDefault.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/FiftyOneDataFileDefault.java index a87c5c14c..84364070e 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/FiftyOneDataFileDefault.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/FiftyOneDataFileDefault.java @@ -28,6 +28,9 @@ * Default implementation of the {@link FiftyOneDataFile} interface. */ public class FiftyOneDataFileDefault extends AspectEngineDataFileDefault implements FiftyOneDataFile { + /** Create a new instance. */ + public FiftyOneDataFileDefault() { + } /** * The start of a download type and the prefix of the product names of diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/SetHeadersData.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/SetHeadersData.java index 92dc70fed..47ccd8040 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/SetHeadersData.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/SetHeadersData.java @@ -37,13 +37,27 @@ * Data containing the result of {@link SetHeadersElement}. */ public class SetHeadersData extends ElementDataBase { + /** Name of the property holding the response headers to set. */ public static final String RESPONSE_HEADER_PROPERTY_NAME = "ResponseHeaderDictionary"; + /** + * Create a new instance. + * + * @param logger used for logging + * @param flowData the Flow Data this element data belongs to + */ public SetHeadersData(Logger logger, FlowData flowData) { super(logger, flowData); } + /** + * Create a new instance with values. + * + * @param logger used for logging + * @param flowData the Flow Data this element data belongs to + * @param data the values + */ public SetHeadersData( Logger logger, FlowData flowData, @@ -70,6 +84,11 @@ public HashMap getResponseHeaderDictionary() { return getAs(RESPONSE_HEADER_PROPERTY_NAME, HashMap.class); } + /** + * Set the response headers to be set. + * + * @param responseHeaders table of response headers + */ public void setResponseHeaderDictionary(HashMap responseHeaders) { put(RESPONSE_HEADER_PROPERTY_NAME, responseHeaders); } diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/ValueMetaDataDefault.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/ValueMetaDataDefault.java index 0862b2b39..1abc81666 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/ValueMetaDataDefault.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/data/ValueMetaDataDefault.java @@ -24,6 +24,7 @@ import java.io.IOException; +/** Default implementation of {@link ValueMetaData}. */ public class ValueMetaDataDefault implements ValueMetaData { private final String name; @@ -31,11 +32,23 @@ public class ValueMetaDataDefault implements ValueMetaData { private final String url; private FiftyOneAspectPropertyMetaData property = null; + /** + * Create a value with a name only. + * + * @param name the value + */ public ValueMetaDataDefault( String name) { this(name, "", ""); } + /** + * Create a new instance. + * + * @param name the value + * @param description the description of the value + * @param url a page that describes the value + */ public ValueMetaDataDefault( String name, String description, @@ -45,6 +58,11 @@ public ValueMetaDataDefault( this.url = url; } + /** + * Set the property the value belongs to. + * + * @param property the property + */ public void setProperty(FiftyOneAspectPropertyMetaData property) { this.property = property; } diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/exceptions/Messages.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/exceptions/Messages.java index 0bd9e3b18..cd489eed4 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/exceptions/Messages.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/exceptions/Messages.java @@ -22,7 +22,12 @@ package fiftyone.pipeline.engines.fiftyone.exceptions; +/** Exception messages used by the 51Degrees engines. */ public class Messages { + /** Create a new instance. */ + public Messages() { + } + /** * Exception message when a SetHeader property does not have name starts * with 'SetHeader' diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/Constants.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/Constants.java index 5abad8ccc..5bd55843a 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/Constants.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/Constants.java @@ -26,6 +26,9 @@ * Constants used by 51Degrees aspect engines. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } /** * The maximum length, in characters, of a piece of evidence's value which @@ -65,7 +68,11 @@ public class Constants { */ public static final boolean SHARE_USAGE_DEFAULT_ENABLED = true; + /** + * Default for how long the same evidence is not shared again, in minutes. + */ public static final int SHARE_USAGE_DEFAULT_REPEAT_EVIDENCE_MINUTES = 20; + /** Default proportion of requests shared, where 1.0 is all of them. */ public static final double SHARE_USAGE_DEFAULT_SHARE_PERCENTAGE = 1.0; /** diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/FiftyOneOnPremiseAspectEngineBuilderBase.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/FiftyOneOnPremiseAspectEngineBuilderBase.java index b6ea858ec..71eb7e290 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/FiftyOneOnPremiseAspectEngineBuilderBase.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/FiftyOneOnPremiseAspectEngineBuilderBase.java @@ -45,6 +45,7 @@ public abstract class FiftyOneOnPremiseAspectEngineBuilderBase< TEngine extends FiftyOneAspectEngine> extends SingleFileAspectEngineBuilderBase { + /** The default address new data files are downloaded from. */ public static final String DATA_UPDATE_URL = "https://distributor.51degrees.com/api/v2/download"; private String dataDownloadType; diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/SetHeadersElement.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/SetHeadersElement.java index d464152a7..2edb96033 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/SetHeadersElement.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/SetHeadersElement.java @@ -76,6 +76,12 @@ public class SetHeadersElement private final List properties; private final Hashtable pipelineConfigs; + /** + * Create a new instance. + * + * @param logger used for logging + * @param elementDataFactory creates the element data this element returns + */ @SuppressWarnings("this-escape") public SetHeadersElement( Logger logger, @@ -278,6 +284,11 @@ private String getResponseHeader(String key) { * Internal class to hold 'SetHeader' properties available per pipeline. */ protected class PipelineConfig { + /** Create a new instance. */ + protected PipelineConfig() { + } + + /** The SetHeader properties, by name. */ public Map setHeaderProperties = new HashMap(); } @@ -287,7 +298,13 @@ protected class PipelineConfig { * header to set. */ protected class PropertyDetails { + /** Create a new instance. */ + protected PropertyDetails() { + } + + /** The property that gives the header value. */ public ElementPropertyMetaData propertyMetaData; + /** The name of the response header to set. */ public String responseHeaderName; } } diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageBase.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageBase.java index e6c68ef46..5e9c40d4f 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageBase.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageBase.java @@ -1179,6 +1179,11 @@ private void submitSendData() { } } + /** + * Send the queued usage data. + * + * @throws HttpException if the data could not be sent + */ protected abstract void sendUsageData() throws HttpException; /** @@ -1247,9 +1252,17 @@ public void setEnginesVersion(String enginesVersion) { * prior to it being sent to 51Degrees. */ protected static class ShareUsageData { + /** Create a new instance. */ + protected ShareUsageData() { + } + + /** The session id, when sessions are tracked. */ public String sessionId; + /** The position of this request in the session. */ public int sequence; + /** The IP address of the client. */ public String clientIP; + /** The evidence shared, by category and then by field name. */ public final Map> evidenceData = new HashMap<>(); void tryAddToData(String key, Object value) { diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageBuilderBase.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageBuilderBase.java index 1b9822e3f..9cb33b91a 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageBuilderBase.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageBuilderBase.java @@ -42,29 +42,56 @@ @SuppressWarnings({"UnusedReturnValue", "DefaultAnnotationParam"}) public abstract class ShareUsageBuilderBase { + /** Creates the loggers the element uses. */ protected final ILoggerFactory loggerFactory; + /** Used for logging. */ protected final Logger logger; + /** How long the same evidence is not shared again, in minutes. */ protected int repeatEvidenceInterval = Constants.SHARE_USAGE_DEFAULT_REPEAT_EVIDENCE_MINUTES; + /** The proportion of requests shared, where 1.0 is all of them. */ protected double sharePercentage = Constants.SHARE_USAGE_DEFAULT_SHARE_PERCENTAGE; + /** The fewest entries sent in one message. */ protected int minimumEntriesPerMessage = Constants.SHARE_USAGE_DEFAULT_MIN_ENTRIES_PER_MESSAGE; - // This value must be accessed through the corresponding getter/setter. + /** + * The most entries the queue holds. Read and set it through its getter and + * setter. + */ protected int maximumQueueSize = Constants.SHARE_USAGE_DEFAULT_MAX_QUEUE_SIZE; + /** Milliseconds to wait when adding to a full queue. */ protected int addTimeout = Constants.SHARE_USAGE_DEFAULT_ADD_TIMEOUT; + /** Milliseconds to wait for another entry before sending. */ protected int takeTimeout = Constants.SHARE_USAGE_DEFAULT_TAKE_TIMEOUT; + /** The address usage data is sent to. */ protected String shareUsageUrl = Constants.SHARE_USAGE_DEFAULT_URL; + /** Name of the cookie that holds the session id. */ protected String sessionCookieName = fiftyone.pipeline.engines.Constants.DEFAULT_SESSION_COOKIE_NAME; + /** The HTTP headers that are never shared. */ protected List blockedHttpHeaders = new ArrayList<>(); + /** Not used, as the query string parameters setting has no effect. */ protected final List includedQueryStringParameters = new ArrayList<>(); + /** Evidence whose requests are not shared, as pairs of key and value. */ protected final List> ignoreDataEvidenceFilter = new ArrayList<>(); + /** Whether the session cookie is used to tell repeated evidence apart. */ protected boolean trackSession; + /** + * Failed sends within the window that start the wait before sending again. + */ protected int failuresToEnterRecovery = Constants.SHARE_USAGE_FAILURES_TO_ENTER_RECOVERY_DEFAULT; + /** The window in which failed sends are counted, in seconds. */ protected int failuresWindowSeconds = Constants.SHARE_USAGE_FAILURES_WINDOW_SECONDS_DEFAULT; + /** The first wait before sending again, in seconds. */ protected double initialRecoveryDelaySeconds = Constants.SHARE_USAGE_EXPONENTIAL_BACKOFF_INITIAL_DELAY_SECONDS_DEFAULT; + /** The longest wait before sending again, in seconds. */ protected double maxRecoveryDelaySeconds = Constants.SHARE_USAGE_EXPONENTIAL_BACKOFF_MAX_DELAY_SECONDS_DEFAULT; + /** How much each wait grows after another failure. */ protected double recoveryMultiplier = Constants.SHARE_USAGE_EXPONENTIAL_BACKOFF_MULTIPLIER_DEFAULT; + /** + * Whether all evidence is shared, not only the keys the Pipeline accepts. + */ protected boolean shareAllEvidence; + /** Not used, as the setting has no effect. */ protected boolean shareAllQueryStringParameters = Constants.SHARE_USAGE_DEFAULT_SHARE_ALL_QUERY_STRING_PARAMETERS; diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageElement.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageElement.java index 55aa9328b..2a919e096 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageElement.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageElement.java @@ -56,12 +56,16 @@ * @see Specification */ public class ShareUsageElement extends ShareUsageBase { - // max time to wait to send data - protected int httpSendTimeout = SHARE_USAGE_DEFAULT_HTTP_POST_TIMEOUT; // milliseconds + /** The longest wait to send data, in milliseconds. */ + protected int httpSendTimeout = SHARE_USAGE_DEFAULT_HTTP_POST_TIMEOUT; + /** HTTP headers sent with the data. */ protected Map headers = new HashMap<>(); - protected HttpClient httpClient; // old style HttpClient + /** Sends the data where it is set, in place of the uploader. */ + protected HttpClient httpClient; + /** Sends the data when no HTTP client is set. */ protected DataUploader dataUploader = new DataUploaderHttp(shareUsageUrl, headers, httpSendTimeout); + /** Creates the writers of the XML that is sent. */ protected XMLOutputFactory xmlOutputFactory; /** @@ -494,6 +498,12 @@ protected void sendUsageData() { logger.debug(threadMarker, "Stopping sending. Queue size is {}", evidenceCollection.size()); } + /** + * Write the data as XML and send it. + * + * @param allData the data to send + * @throws Exception if the data could not be written or sent + */ protected void sendAsXML(List allData) throws Exception { logger.debug(threadMarker, "send {} usage elements", allData.size()); @@ -537,6 +547,7 @@ private void streamXml(List allData, OutputStream os) throws XML * * @param writer an XMLWriter * @param data the data to write + * @throws XMLStreamException if the XML could not be written */ protected void writeXmlData(XMLStreamWriter writer, ShareUsageData data) throws XMLStreamException { writer.writeStartElement("Device"); @@ -609,6 +620,14 @@ protected void writeXmlData(XMLStreamWriter writer, ShareUsageData data) throws writer.writeEndElement(); } + /** + * Write an element with text, or nothing when the text is null. + * + * @param writer where the XML is written + * @param elementName the name of the element + * @param elementContent the text + * @throws XMLStreamException if the XML could not be written + */ protected void writeXmlElement(XMLStreamWriter writer, String elementName, String elementContent) throws XMLStreamException { @@ -690,10 +709,20 @@ public ReplacedString(String text) { } } + /** + * Whether a character was replaced. + * + * @return true if one was + */ public boolean isReplaced() { return replaced; } + /** + * Whether the text was cut short. + * + * @return true if it was + */ public boolean isTruncated() { return truncated; } @@ -706,6 +735,7 @@ public String toString() { /** * If there is an HttpClient we will use this as a legacy * @param allData data to send + * @throws Exception if the data could not be written or sent */ protected void legacySendAsXML(List allData) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); diff --git a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/interop/LibLoader.java b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/interop/LibLoader.java index 65c97e55b..6783b1df7 100644 --- a/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/interop/LibLoader.java +++ b/pipeline/pipeline.engines.fiftyone/src/main/java/fiftyone/pipeline/engines/fiftyone/flowelements/interop/LibLoader.java @@ -36,6 +36,9 @@ * {@link AspectEngine}. */ public class LibLoader { + /** Create a new instance. */ + public LibLoader() { + } /** * Get the enumeration of the group of Operating Systems to which the system diff --git a/pipeline/pipeline.engines.fiftyone/src/test/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageOptionsTests.java b/pipeline/pipeline.engines.fiftyone/src/test/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageOptionsTests.java index afa9d2bba..d75a6412a 100644 --- a/pipeline/pipeline.engines.fiftyone/src/test/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageOptionsTests.java +++ b/pipeline/pipeline.engines.fiftyone/src/test/java/fiftyone/pipeline/engines/fiftyone/flowelements/ShareUsageOptionsTests.java @@ -322,14 +322,15 @@ public void neverSharedKeys_TurkishLocale_StillRefused() { public void tracker_BuildsOneCache() { CountingCacheBuilder builder = new CountingCacheBuilder(); - try (ShareUsageTracker tracker = new ShareUsageTracker( - new CacheConfiguration(builder, 10), - 1000, - new EvidenceKeyFilterShareUsage( - new ArrayList(), - new ArrayList(), - false, - DEFAULT_SESSION_COOKIE_NAME))) { + try { + new ShareUsageTracker( + new CacheConfiguration(builder, 10), + 1000, + new EvidenceKeyFilterShareUsage( + new ArrayList(), + new ArrayList(), + false, + DEFAULT_SESSION_COOKIE_NAME)).close(); assertEquals(1, builder.built.get()); } catch (java.io.IOException e) { throw new IllegalStateException(e); diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/Constants.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/Constants.java index 0601e4b2d..f06e65f3d 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/Constants.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/Constants.java @@ -24,16 +24,37 @@ import fiftyone.pipeline.engines.configuration.CacheConfiguration; +/** Default settings and messages shared by the engines. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } + + /** Prefix of the names of 51Degrees cookies. */ public static final String FIFTYONE_COOKIE_PREFIX = "51d_"; + /** Default name of the session cookie. */ public static final String DEFAULT_SESSION_COOKIE_NAME = "JSESSIONID"; + /** Default time between checks for a new data file, in seconds. */ public static final int DATA_UPDATE_POLLING_DEFAULT = 30 * 60; + /** + * Default most seconds added at random to the time between checks, so that + * many servers do not check at once. + */ public static final int DATA_UPDATE_RANDOMISATION_DEFAULT = 10 * 60; + /** Whether automatic data file updates are on by default. */ public static final boolean DEFAULT_AUTOUPDATE_ENABLED = true; + /** Whether the data file is watched for changes by default. */ public static final boolean DEFAULT_WATCHER_ENABLED = true; + /** Whether a downloaded data file is decompressed by default. */ public static final boolean DEFAULT_DECOMPRESS = true; + /** Whether the MD5 hash of a downloaded data file is checked by default. */ public static final boolean DEFAULT_VERIFY_MD5 = true; + /** + * Whether an update request sends the data file's time by default, so the + * server can answer that nothing is new. + */ public static final boolean DEFAULT_VERIFY_IF_MODIFIED_SINCE = true; + /** Whether the data file is updated when the engine starts by default. */ public static final boolean DEFAULT_UPDATE_ON_STARTUP = false; /** @@ -61,17 +82,36 @@ public class Constants { public static final int DEFAULT_RESULTS_CACHE_SIZE = CacheConfiguration.defaultSize; + /** How an on-premise engine trades memory for speed. */ public enum PerformanceProfiles { + /** + * Reads the data file as needed with no caching, using the least + * memory. + */ LowMemory, + /** Holds the whole data file in memory for the fastest detection. */ MaxPerformance, + /** Holds the data file in memory. */ HighPerformance, + /** Holds some data in memory and caches the rest as it is read. */ Balanced, + /** + * As Balanced, reading from a temporary copy so the data file is not + * locked. + */ BalancedTemp } + /** Messages that explain why a property has no value. */ public static class MissingPropertyMessages { + /** Create a new instance. */ + public MissingPropertyMessages() { + } + + /** Start of every message, naming the property and element. */ public static final String PREFIX = "Property '%s' not found in data for element '%s'. "; + /** The property needs a higher data tier, which the message names. */ public static final String DATA_UPGRADE_REQUIRED = "This is because your license or data file does not include " + "this property. It is available with the %s license/data for " + @@ -85,14 +125,20 @@ public static class MissingPropertyMessages { "This is because your license or data file does not include " + "this property. To see which licenses include it, see " + "https://51degrees.com/pricing?utm_source=code&utm_medium=comment&utm_campaign=51degrees-java&utm_content=pipeline.engines-src-main-java-fiftyone-pipeline-engines-constants.java&utm_term=data_upgrade_required_tiers_not_known."; + /** The property was excluded when the engine was configured. */ public static final String PROPERTY_EXCLUDED = "This is because the property has been excluded when configuring " + "the engine."; + /** The resource key gives no properties of the product named. */ public static final String PRODUCT_NOT_IN_CLOUD_RESOURCE = "This is because your resource key does not include access to " + "any properties under '%s'. Check or create a resource key with " + "the properties you need in the configurator at " + "https://configure.51degrees.com?utm_source=code&utm_medium=comment&utm_campaign=51degrees-java&utm_content=pipeline.engines-src-main-java-fiftyone-pipeline-engines-constants.java&utm_term=product_not_in_cloud_resource."; + /** + * The resource key does not give the property, and the message lists + * those it does give. + */ public static final String PROPERTY_NOT_IN_CLOUD_RESOURCE = "This is because your resource key does not include access to " + "this property. The properties included for your key under " + @@ -102,6 +148,7 @@ public static class MissingPropertyMessages { * The separator of the names in a list in a message. */ public static final String LIST_SEPARATOR = ","; + /** A cloud request failed, so there was no data. */ public static final String CLOUD_REQUEST_FAILED = "This is because an upstream cloud request failed, so no data " + "was available to populate the property."; @@ -110,6 +157,7 @@ public static class MissingPropertyMessages { * populates the Element Data. */ public static final String UNKNOWN_DATA_KEY = "Unknown"; + /** No other reason fits. */ public static final String UNKNOWN = "The reason for this is unknown. Please check that the aspect " + "and property name are correct."; diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/caching/FlowCacheDefault.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/caching/FlowCacheDefault.java index be1348415..21e3757b0 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/caching/FlowCacheDefault.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/caching/FlowCacheDefault.java @@ -39,6 +39,11 @@ public class FlowCacheDefault private FlowElement flowElement; + /** + * Create a new instance. + * + * @param configuration the cache size and other settings + */ public FlowCacheDefault(CacheConfiguration configuration) { super(configuration); } diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/CacheConfiguration.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/CacheConfiguration.java index 9295403c4..b22fd2fe2 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/CacheConfiguration.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/CacheConfiguration.java @@ -32,6 +32,7 @@ */ public class CacheConfiguration { + /** Number of entries a cache holds when no size is given. */ public static final int defaultSize = 1000; private final CacheBuilder builder; diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationBuilder.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationBuilder.java index 1fa86ce88..48b23b166 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationBuilder.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationBuilder.java @@ -28,6 +28,9 @@ public class DataFileConfigurationBuilder extends DataFileConfigurationBuilderBase< DataFileConfigurationBuilder, DataFileConfiguration> { + /** Create a new instance. */ + public DataFileConfigurationBuilder() { + } @Override protected DataFileConfiguration createConfig() { diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationBuilderBase.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationBuilderBase.java index 9d7cb5818..1a930cf17 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationBuilderBase.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationBuilderBase.java @@ -62,6 +62,7 @@ protected List getDataUpdateLicenseKeys() { return licenseKeys; } + /** Create a new builder. */ public DataFileConfigurationBuilderBase() { } @@ -298,6 +299,11 @@ public TBuilder setDataUpdateLicenseKeys(String[] keys) { return (TBuilder)this; } + /** + * Create the configuration instance that the build method fills in. + * + * @return a new configuration + */ protected abstract TConfig createConfig(); /** diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationDefault.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationDefault.java index f08819232..b7495809b 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationDefault.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/DataFileConfigurationDefault.java @@ -34,6 +34,10 @@ * @see Specification */ public class DataFileConfigurationDefault implements DataFileConfiguration { + /** Create a new instance. */ + public DataFileConfigurationDefault() { + } + private String identifier = "Default"; private String dataFilePath; private boolean createTempDataCopy; diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/ExecutorServiceFactoryDefault.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/ExecutorServiceFactoryDefault.java index eff8dc31b..f247b25bc 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/ExecutorServiceFactoryDefault.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/configuration/ExecutorServiceFactoryDefault.java @@ -30,6 +30,10 @@ * {@link Executors#newCachedThreadPool()} method to create a new service. */ public class ExecutorServiceFactoryDefault implements ExecutorServiceFactory { + /** Create a new instance. */ + public ExecutorServiceFactoryDefault() { + } + @Override public ExecutorService create() { return Executors.newCachedThreadPool(); diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/data/AspectEngineDataFileDefault.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/data/AspectEngineDataFileDefault.java index 55ecaa049..ad50adf05 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/data/AspectEngineDataFileDefault.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/data/AspectEngineDataFileDefault.java @@ -36,6 +36,10 @@ * Default implementation of the {@link AspectEngineDataFile} interface. */ public class AspectEngineDataFileDefault implements AspectEngineDataFile { + /** Create a new instance. */ + public AspectEngineDataFileDefault() { + } + private String identifier; private OnPremiseAspectEngine engine; private DataFileConfiguration configuration; @@ -182,36 +186,72 @@ public void setDataUpdateService(DataUpdateService dataUpdateService) { private long lastUpdateFileCreateTime; + /** + * The modified time of the file last applied, so one change is applied + * once. + * + * @return the time in milliseconds since the epoch + */ public long getLastUpdateFileCreateTime() { return lastUpdateFileCreateTime; } + /** + * Set the modified time of the file last applied. + * + * @param createTime the time in milliseconds since the epoch + */ public void setLastUpdateFileCreateTime(long createTime) { lastUpdateFileCreateTime = createTime; } private final Object syncLock = new Object(); + /** + * The lock held while a changed file is applied. + * + * @return the lock + */ public Object getUpdateSyncLock() { return syncLock; } private ScheduledFuture future; + /** + * The scheduled check for a new data file. + * + * @return the scheduled task, or null if none + */ public ScheduledFuture getFuture() { return future; } + /** + * Set the scheduled check for a new data file. + * + * @param future the scheduled task + */ public void setFuture(ScheduledFuture future) { this.future = future; } private ScheduledFuture pollFuture; + /** + * The scheduled task that polls the file for changes. + * + * @return the scheduled task, or null if none + */ public ScheduledFuture getPollFuture() { return pollFuture; } + /** + * Set the scheduled task that polls the file for changes. + * + * @param future the scheduled task + */ public void setPollFuture(ScheduledFuture future) { this.pollFuture = future; } diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/data/JsonLoader.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/data/JsonLoader.java index c4ebdf413..529cb9056 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/data/JsonLoader.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/data/JsonLoader.java @@ -37,6 +37,9 @@ * @param type of object to load */ public class JsonLoader implements DataLoader { + /** Create a new instance. */ + public JsonLoader() { + } private T loadData(Reader reader, Class type) throws IOException, IllegalAccessException, InstantiationException, InvocationTargetException { int bufferLength = 1024; diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/exceptions/PropertyMissingException.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/exceptions/PropertyMissingException.java index ece52d77f..18f7bca37 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/exceptions/PropertyMissingException.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/exceptions/PropertyMissingException.java @@ -36,10 +36,13 @@ public class PropertyMissingException extends RuntimeException { */ private static final long serialVersionUID = -2395447752714222366L; + /** Name of the property that has no value. */ private String propertyName = null; + /** Why the property has no value. */ private MissingPropertyReason reason; + /** Create a new instance with no message. */ public PropertyMissingException() { super(); } diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/AspectEngineBase.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/AspectEngineBase.java index b828c38d5..c29772700 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/AspectEngineBase.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/AspectEngineBase.java @@ -45,6 +45,8 @@ * Base class for {@link AspectEngine}s to extend. This implements the data * update service and missing property service along with everything * already implemented by {@link FlowElementBase}. + * @param the type of element data the engine returns + * @param the type of the property metadata * @see Specification */ public abstract class AspectEngineBase< @@ -55,8 +57,10 @@ public abstract class AspectEngineBase< private LazyLoadingConfiguration lazyLoadingConfiguration = null; + /** Explains why a property has no value. */ protected MissingPropertyService missingPropertyService; + /** Caches results, or null when there is no cache. */ protected FlowCache cache = null; /** diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/AspectEngineBuilderBase.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/AspectEngineBuilderBase.java index 54ff3eeb4..854654875 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/AspectEngineBuilderBase.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/AspectEngineBuilderBase.java @@ -45,8 +45,10 @@ public abstract class AspectEngineBuilderBase< TBuilder extends AspectEngineBuilderBase, TEngine extends AspectEngine> { + /** Creates the loggers the engine uses. */ protected final ILoggerFactory loggerFactory; private final List properties = new ArrayList<>(); + /** The results cache settings, or null for no cache. */ protected CacheConfiguration cacheConfig = null; private LazyLoadingConfiguration lazyLoadingConfig = null; diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/CloudPipelineBuilderBase.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/CloudPipelineBuilderBase.java index 234f0099c..29e0cab59 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/CloudPipelineBuilderBase.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/CloudPipelineBuilderBase.java @@ -38,20 +38,33 @@ public abstract class CloudPipelineBuilderBase< TBuilder extends CloudPipelineBuilderBase> extends PrePackagedPipelineBuilderBase { + /** The cloud service endpoint, or empty for the default. */ protected String url = ""; + /** The data endpoint, or empty for the default. */ protected String dataEndpoint = ""; + /** The properties endpoint, or empty for the default. */ protected String propertiesEndpoint = ""; + /** The evidence keys endpoint, or empty for the default. */ protected String evidenceKeysEndpoint = ""; + /** The resource key sent with each request. */ protected String resourceKey = ""; + /** The license key sent with each request. */ protected String licenseKey = ""; + /** + * The properties to ask the cloud service for, or empty for all the key + * gives. + */ protected final List requestedProperties = new ArrayList<>(); + /** + * The value of the Origin header sent with each request, or empty for none. + */ protected String cloudRequestOrigin = ""; /** diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/Constants.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/Constants.java index a5bde623d..04528ff96 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/Constants.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/Constants.java @@ -22,6 +22,12 @@ package fiftyone.pipeline.engines.flowelements; +/** Constants used by the element builders. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } + + /** Separates the property names in a list. */ public static final String PROPERTIES_SEPARATOR = ","; } diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/OnPremiseAspectEngineBase.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/OnPremiseAspectEngineBase.java index 58d7caa4a..158768953 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/OnPremiseAspectEngineBase.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/OnPremiseAspectEngineBase.java @@ -82,6 +82,11 @@ public String getTempDataDirPath() { return tempDataDirPath; } + /** + * Set the folder for temporary copies of the data file. + * + * @param tempDataDirPath path of the folder + */ protected void setTempDataDirPath(String tempDataDirPath) { this.tempDataDirPath = tempDataDirPath; } diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/OnPremiseAspectEngineBuilderBase.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/OnPremiseAspectEngineBuilderBase.java index f743cd6a6..8ebe9a7d5 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/OnPremiseAspectEngineBuilderBase.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/OnPremiseAspectEngineBuilderBase.java @@ -59,11 +59,15 @@ public abstract class OnPremiseAspectEngineBuilderBase< private final DataUpdateService dataUpdateService; + /** The data files configured so far. */ protected final List dataFileConfigs = new ArrayList<>(); + /** The data files created from the configurations. */ protected final List dataFiles = new ArrayList<>(); + /** Folder for temporary copies of the data file. */ protected String tempDir = Paths.get( System.getProperty("java.io.tmpdir"),"fiftyone.tempfiles").toString(); + /** Used for logging. */ protected Logger logger = LoggerFactory.getLogger(OnPremiseAspectEngineBuilderBase.class); /** @@ -100,6 +104,14 @@ public OnPremiseAspectEngineBuilderBase( createAndVerifyTempDir(Paths.get(tempDir)); } + /** + * Create the folder if it does not exist, readable and writable by its + * owner only, and check it can be read and written. + * + * @param pathToCreate the folder + * @throws IllegalStateException if the path is not a folder or cannot be + * read and written + */ public final void createAndVerifyTempDir(Path pathToCreate) { try { File directory = pathToCreate.toFile(); diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/PrePackagedPipelineBuilderBase.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/PrePackagedPipelineBuilderBase.java index 83ac76a40..c0529b0b2 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/PrePackagedPipelineBuilderBase.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/PrePackagedPipelineBuilderBase.java @@ -36,13 +36,17 @@ public abstract class PrePackagedPipelineBuilderBase > extends PipelineBuilderBase { + /** Whether lazy loading is on, which has no effect. */ protected boolean lazyLoading = Constants.DEFAULT_LAZY_LOADING; + /** Whether the engines cache results. */ protected boolean resultsCache = Constants.DEFAULT_RESULTS_CACHE; + /** Timeout of the lazy loading option, which has no effect. */ protected long lazyLoadingTimeoutMillis = Constants.DEFAULT_LAZY_LOADING_TIMEOUT_MILLIS; + /** Number of results each engine's cache holds. */ protected int resultsCacheSize = Constants.DEFAULT_RESULTS_CACHE_SIZE; /** diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/SingleFileAspectEngineBuilderBase.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/SingleFileAspectEngineBuilderBase.java index d389e1600..d3393b810 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/SingleFileAspectEngineBuilderBase.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/flowelements/SingleFileAspectEngineBuilderBase.java @@ -236,7 +236,7 @@ public TBuilder setDataFileSystemWatcher(boolean enabled) { /** * Set the time between checks for a new data file made by the * {@link DataUpdateService} in seconds. - *

+ * * @deprecated use {@link #setUpdatePollingIntervalSeconds(int)} * @param pollingIntervalSeconds the number of seconds between checks * @return this builder diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUpdateService.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUpdateService.java index eeb93a9c2..905f80f64 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUpdateService.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUpdateService.java @@ -106,40 +106,46 @@ public interface DataUpdateService extends Closeable, PipelineService { */ enum AutoUpdateStatus { - // Update completed successfully. + /** Update completed successfully. */ AUTO_UPDATE_SUCCESS, - // HTTPS connection could not be established. + /** HTTPS connection could not be established. */ AUTO_UPDATE_HTTPS_ERR, - // No need to perform update. + /** No need to perform update. */ AUTO_UPDATE_NOT_NEEDED, - // Update currently under way. + /** Update currently under way. */ AUTO_UPDATE_IN_PROGRESS, - // Path to master file is directory not file + /** The data file could not be renamed, as when its path is a folder. */ AUTO_UPDATE_MASTER_FILE_CANT_RENAME, - // 51Degrees server responded with 429: too many attempts. + /** The server answered 429, too many requests. */ AUTO_UPDATE_ERR_429_TOO_MANY_ATTEMPTS, - // 51Degrees server responded with 403 meaning key is blacklisted. + /** The server answered 403, so the license key is refused. */ AUTO_UPDATE_ERR_403_FORBIDDEN, - // Used when IO operations with input or output stream failed. + /** Used when IO operations with input or output stream failed. */ AUTO_UPDATE_ERR_READING_STREAM, - // MD5 validation failed + /** The MD5 hash of the downloaded file did not match. */ AUTO_UPDATE_ERR_MD5_VALIDATION_FAILED, - // The new data file can't be renamed to replace the previous one. + /** The new data file can't be renamed to replace the previous one. */ AUTO_UPDATE_NEW_FILE_CANT_RENAME, - // Refreshing the engine with the new data caused an error to occur. + /** Refreshing the engine with the new data caused an error to occur. */ AUTO_UPDATE_REFRESH_FAILED, - // An operation could not be completed within the expected time. + /** An operation could not be completed within the expected time. */ AUTO_UPDATE_TIMEOUT, - // The data file checking for updates has no temporary file path. + /** The data file checking for updates has no temporary file path. */ AUTO_UPDATE_TEMP_PATH_NOT_SET, - // A check failed with an error that no other status covers. + /** A check failed with an error that no other status covers. */ AUTO_UPDATE_UNKNOWN_ERROR } + /** The result of an update, passed to those told when it completes. */ class DataUpdateCompleteArgs { private AspectEngineDataFile dataFile; private AutoUpdateStatus status; + /** + * Create a new instance. + * @param status the result of the update + * @param dataFile the data file that was updated + */ public DataUpdateCompleteArgs( AutoUpdateStatus status, AspectEngineDataFile dataFile) { @@ -147,10 +153,18 @@ public DataUpdateCompleteArgs( this.dataFile = dataFile; } + /** + * The result of the update. + * @return the status + */ public AutoUpdateStatus getStatus() { return status; } + /** + * The data file that was updated. + * @return the data file + */ public AspectEngineDataFile getDataFile() { return dataFile; } diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUpdateServiceDefault.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUpdateServiceDefault.java index 97c1dce49..8a2677699 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUpdateServiceDefault.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUpdateServiceDefault.java @@ -542,9 +542,11 @@ private AutoUpdateStatus applyWatchedFile(AspectEngineDataFile dataFile) { watchedFileOpenTimeoutMillis); while (fileLockable == false && System.nanoTime() - deadline < 0) { - try (BinaryReader reader = fileWrapperFactory.build( - aspectDataFile.getDataFilePath()).getReader()) { + try { + BinaryReader reader = fileWrapperFactory.build( + aspectDataFile.getDataFilePath()).getReader(); fileLockable = true; + reader.close(); } catch (IOException ignored) { try { Thread.sleep(WATCHED_FILE_OPEN_PAUSE_MILLIS); diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUploader.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUploader.java index b790a6415..a4cd89533 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUploader.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUploader.java @@ -35,16 +35,21 @@ public interface DataUploader { /** * returns an OutputStream through which data may be uploaded + * @return the stream to write the data to + * @throws Exception if the connection could not be opened */ OutputStream getOutputStream() throws Exception; /** - * + * The HTTP status code of the answer to the upload. * @return 200 for success + * @throws IOException if the answer could not be read */ int getResponseCode() throws IOException; /** + * Returns the content of the answer, which is logged when the code is not + * 200, or an empty string if the uploader cannot give it. * @return the content of the answer, which is logged when the code is * not 200, or an empty string if the uploader cannot give it */ diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUploaderHttp.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUploaderHttp.java index 9ad54e674..a3a94403f 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUploaderHttp.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/DataUploaderHttp.java @@ -31,6 +31,7 @@ import java.util.Map; import java.util.zip.GZIPOutputStream; +/** Uploads data in an HTTP POST, compressed with gzip. */ public class DataUploaderHttp implements DataUploader{ private final String url; diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/HttpClientDefault.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/HttpClientDefault.java index 4759da850..245a97e68 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/HttpClientDefault.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/HttpClientDefault.java @@ -42,6 +42,7 @@ public class HttpClientDefault implements HttpClient { private final HostLookup hostLookup; + /** Create a client that finds hosts with the default lookup. */ public HttpClientDefault() { this(HostLookup.DEFAULT); } diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/MissingPropertyReason.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/MissingPropertyReason.java index 60697b59e..52d735895 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/MissingPropertyReason.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/MissingPropertyReason.java @@ -29,14 +29,22 @@ * {@link AspectEngine}'s processing. */ public enum MissingPropertyReason { + /** + * The data file does not hold the property, so a higher data tier is + * needed. + */ DataFileUpgradeRequired, + /** The property was excluded when the engine was configured. */ PropertyExcludedFromEngineConfiguration, + /** The resource key does not give the property. */ PropertyNotAccessibleWithResourceKey, + /** The resource key gives no properties of the product. */ ProductNotAccessibleWithResourceKey, /** * A request to the cloud service failed, so no data was available to * populate the property. */ CloudRequestFailed, + /** No other reason fits. */ Unknown } diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/update/FutureFactory.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/update/FutureFactory.java index 4c1d2b3e0..9a121327b 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/update/FutureFactory.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/update/FutureFactory.java @@ -25,12 +25,27 @@ import java.io.Closeable; import java.util.concurrent.ScheduledFuture; +/** Schedules the tasks of the data update service. */ public interface FutureFactory extends Closeable { + /** + * Run a task repeatedly. + * + * @param runnable the task + * @param period milliseconds before the first run and between runs + * @return the scheduled task + */ ScheduledFuture scheduleRepeating( Runnable runnable, long period); + /** + * Run a task once. + * + * @param runnable the task + * @param delay milliseconds before it runs + * @return the scheduled task + */ ScheduledFuture schedule( Runnable runnable, long delay); diff --git a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/update/FutureFactoryDefault.java b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/update/FutureFactoryDefault.java index b1e27a5a5..759538260 100644 --- a/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/update/FutureFactoryDefault.java +++ b/pipeline/pipeline.engines/src/main/java/fiftyone/pipeline/engines/services/update/FutureFactoryDefault.java @@ -28,7 +28,11 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +/** Schedules tasks on a single background thread. */ public class FutureFactoryDefault implements FutureFactory { + /** Create a new instance. */ + public FutureFactoryDefault() { + } private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); diff --git a/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/flowelements/ConfigurationValueTypesTests.java b/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/flowelements/ConfigurationValueTypesTests.java index 495df35a8..fadfe6e8d 100644 --- a/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/flowelements/ConfigurationValueTypesTests.java +++ b/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/flowelements/ConfigurationValueTypesTests.java @@ -24,7 +24,6 @@ import fiftyone.pipeline.core.configuration.ElementOptions; import fiftyone.pipeline.core.configuration.PipelineOptions; -import fiftyone.pipeline.core.flowelements.Pipeline; import fiftyone.pipeline.core.flowelements.PipelineBuilder; import fiftyone.pipeline.engines.testhelpers.flowelements.ConfiguredEngineBuilder; import org.junit.Test; @@ -52,11 +51,10 @@ private static void build(String name, String value) throws Exception { element.buildParameters.put(name, value); PipelineOptions options = new PipelineOptions(); options.elements.add(element); - try (Pipeline ignored = new PipelineBuilder( - LoggerFactory.getILoggerFactory()) - .buildFromConfiguration(options)) { - // Building is enough. - } + // Building is enough. + new PipelineBuilder(LoggerFactory.getILoggerFactory()) + .buildFromConfiguration(options) + .close(); } @Test diff --git a/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/services/DataUpdateServiceWatchedFileTests.java b/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/services/DataUpdateServiceWatchedFileTests.java index b3e6d13c1..778abdb87 100644 --- a/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/services/DataUpdateServiceWatchedFileTests.java +++ b/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/services/DataUpdateServiceWatchedFileTests.java @@ -610,12 +610,18 @@ void assertLeftAsItWas() { } @Override - public void close() throws Exception { + public void close() { // Lets an update that would not give up end, so the thread stops. stop.set(true); locked.set(false); - if (runner.isAlive()) { - runner.join(WAIT_FOR_EVENT_MILLIS); + try { + if (runner.isAlive()) { + runner.join(WAIT_FOR_EVENT_MILLIS); + } + } catch (InterruptedException e) { + // The files are still removed, and the test thread keeps its + // interrupt for the test to see. + Thread.currentThread().interrupt(); } cleanUp(file, directory, dataFile); } diff --git a/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/services/DataUploaderHttpTests.java b/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/services/DataUploaderHttpTests.java index d9094b438..eb5ecf0b9 100644 --- a/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/services/DataUploaderHttpTests.java +++ b/pipeline/pipeline.engines/src/test/java/fiftyone/pipeline/engines/services/DataUploaderHttpTests.java @@ -76,8 +76,13 @@ public static void AllowRestrictedHeaders() { public void DataUploaderHttp_NoAnswer_TimesOut() throws Exception { try (ServerSocket server = new ServerSocket(0)) { Thread holder = new Thread(() -> { - try (Socket socket = server.accept()) { - Thread.sleep(HOLD_MILLIS); + try { + Socket socket = server.accept(); + try { + Thread.sleep(HOLD_MILLIS); + } finally { + socket.close(); + } } catch (Exception ignored) { // The test has ended and closed the server. } diff --git a/pipeline/pipeline.javascriptbuilder/pom.xml b/pipeline/pipeline.javascriptbuilder/pom.xml index 73a9e1f19..c56b8859a 100644 --- a/pipeline/pipeline.javascriptbuilder/pom.xml +++ b/pipeline/pipeline.javascriptbuilder/pom.xml @@ -117,6 +117,43 @@ [11,) + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-testCompile + + + **/JavaScriptBuilderTests.java + + + + + selenium-testCompile + test-compile + + testCompile + + + + **/JavaScriptBuilderTests.java + + 11 + + + + + + org.seleniumhq.selenium @@ -131,7 +168,9 @@ just from the test run: javac fails reading the Java 11 class files ("class file has wrong version 55.0, should be 52.0") long before surefire is reached, so a surefire alone would not help. - The module's other tests are unaffected. --> + CI compiles with JDK 17 and then runs the tests with Maven on + JDK 8, so the class compiled for Java 11 is also left out of the + test run there. The module's other tests are unaffected. --> jdk8-no-selenium @@ -148,6 +187,18 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + + **/*$* + **/JavaScriptBuilderTests.java + + + diff --git a/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/Constants.java b/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/Constants.java index 8fc7c43c8..dafb00ee4 100644 --- a/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/Constants.java +++ b/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/Constants.java @@ -22,15 +22,25 @@ package fiftyone.pipeline.javascriptbuilder; +/** Evidence keys and defaults used by the JavaScript Builder Element. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } + + /** Evidence key of the Host header. */ public static final String EVIDENCE_HOST_KEY = fiftyone.pipeline.core.Constants.EVIDENCE_HTTPHEADER_PREFIX + fiftyone.pipeline.core.Constants.EVIDENCE_SEPERATOR + "Host"; + /** Suffix of the evidence that names the JavaScript object. */ public static final String EVIDENCE_OBJECT_NAME_SUFFIX = "fod-js-object-name"; + /** + * Evidence key, in the query string, of the name of the JavaScript object. + */ public static final String EVIDENCE_OBJECT_NAME = fiftyone.pipeline.core.Constants.EVIDENCE_QUERY_PREFIX + fiftyone.pipeline.core.Constants.EVIDENCE_SEPERATOR + @@ -52,8 +62,11 @@ public class Constants { fiftyone.pipeline.core.Constants.EVIDENCE_SEPERATOR + EVIDENCE_ENABLE_COOKIES_SUFFIX; + /** Protocol of the callback URL when none is configured or found. */ public static final String DEFAULT_PROTOCOL = "https"; + /** Path of the template the JavaScript is made from. */ public static final String TEMPLATE = "/fiftyone/pipeline/javascriptbuilder/templates/JavaScriptResource.mustache"; + /** Name of the JavaScript object when none is configured. */ public static final String DEFAULT_OBJECT_NAME = "fod"; } diff --git a/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderDataInternal.java b/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderDataInternal.java index 0ca38907e..22297f16b 100644 --- a/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderDataInternal.java +++ b/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderDataInternal.java @@ -36,6 +36,12 @@ public class JavaScriptBuilderDataInternal extends ElementDataBase implements JavaScriptBuilderData { + /** + * Create a new instance. + * + * @param logger used for logging + * @param flowData the Flow Data this element data belongs to + */ public JavaScriptBuilderDataInternal(Logger logger, FlowData flowData) { super(logger, flowData); } diff --git a/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderElement.java b/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderElement.java index 3f3c6ee1a..78cee76a0 100644 --- a/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderElement.java +++ b/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderElement.java @@ -66,12 +66,19 @@ public class JavaScriptBuilderElement extends FlowElementBase { + /** Host of the callback URL, or empty to use the Host header. */ protected String host; + /** Path of the callback endpoint. */ protected String endpoint; + /** Protocol of the callback URL, or empty to use the request's. */ protected String protocol; + /** Context root of the callback URL, or empty to use the evidence. */ protected String contextRoot; + /** Name of the JavaScript object. */ protected final String objName; + /** Whether the JavaScript keeps the cookies it sets. */ protected final boolean enableCookies; + /** Whether the JavaScript is minified. */ protected final boolean minify; private final Mustache mustache; diff --git a/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderElementBuilder.java b/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderElementBuilder.java index 89d3bcb8a..adb60a752 100644 --- a/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderElementBuilder.java +++ b/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/flowelements/JavaScriptBuilderElementBuilder.java @@ -39,6 +39,9 @@ */ @ElementBuilder public class JavaScriptBuilderElementBuilder { + /** + * Whether the JavaScript keeps its cookies when nothing else is configured. + */ public static final boolean ENABLE_COOKIES = true; /** * Whether the script is minified when nothing else is configured. @@ -47,10 +50,15 @@ public class JavaScriptBuilderElementBuilder { private final ILoggerFactory loggerFactory; private final Logger logger; + /** Host of the callback URL, or empty to use the Host header. */ protected String host = ""; + /** Path of the callback endpoint. */ protected String endpoint = ""; + /** Protocol of the callback URL, or empty to use the request's. */ protected String protocol = ""; + /** Context root of the callback URL, or empty to use the evidence. */ protected String contextRoot = ""; + /** Name of the JavaScript object. */ protected String objName = Constants.DEFAULT_OBJECT_NAME; private boolean enableCookies = ENABLE_COOKIES; private boolean minify = MINIFY; @@ -95,7 +103,7 @@ public JavaScriptBuilderElementBuilder setEndpoint(String endpoint) { * Set the evidence value for the context root *

* Default is value from evidence "server.contextroot" - * @param contextRoot + * @param contextRoot the context root of the callback URL * @return this builder */ @DefaultValue("Value from evidence " + fiftyone.pipeline.core.Constants.EVIDENCE_WEB_CONTEXT_ROOT) @@ -163,7 +171,7 @@ public JavaScriptBuilderElementBuilder setObjectName(String objName) { *

* This can also be set per request, using the "query.fod-js-enable-cookies" * evidence key. For more details on personal data policy, see - * https://51degrees.com/terms/client-services-privacy-policy/?utm_source=code&utm_medium=comment&utm_campaign=51degrees-java&utm_content=pipeline.javascriptbuilder-src-main-java-fiftyone-pipeline-javascriptbuilder-flowelements-javascriptbuilderelementbuilder.java&utm_term=setenablecookies + * 51degrees.com/terms/client-services-privacy-policy/ *

* Default is true * @param enableCookies should enable cookies? diff --git a/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/templates/JavaScriptResource.java b/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/templates/JavaScriptResource.java index fb84f427a..4dc4967c6 100644 --- a/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/templates/JavaScriptResource.java +++ b/pipeline/pipeline.javascriptbuilder/src/main/java/fiftyone/pipeline/javascriptbuilder/templates/JavaScriptResource.java @@ -25,6 +25,7 @@ import java.util.HashMap; //! [class] +/** The values the JavaScript template is filled in with. */ public class JavaScriptResource { private final String _objName; private final String _jsonObject; @@ -47,11 +48,14 @@ public class JavaScriptResource { * be created on the client-side by the JavaScript produced * by the template. * @param jsonObject the JSON data payload to be inserted into the template. + * @param sessionId the session id sent with each callback. + * @param sequence the sequence number of this request in the session. * @param supportsPromises if true, the template will produce JavaScript * that makes use of promises. If false, promises * will not be used. * @param url the complete URL to use for the callback mechanism described * in remarks for this constructor. + * @param parameters the parameters sent with each callback, as JSON. * @param enableCookies if false, any cookies created by JavaScript * properties that execute on the client-side and that * start with '51D_' will be deleted automatically. @@ -90,6 +94,11 @@ public JavaScriptResource( _hasDelayedProperties = hasDelayedProperties; } + /** + * The values by the names the template uses. + * + * @return the values + */ public HashMap asMap() { HashMap hash = new HashMap<>(); diff --git a/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/Constants.java b/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/Constants.java index f72d41ee8..bfed2c536 100644 --- a/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/Constants.java +++ b/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/Constants.java @@ -22,8 +22,16 @@ package fiftyone.pipeline.jsonbuilder; +/** Constants used by the JSON Builder Element. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } + /** + * The request sequence number from which JavaScript properties are no + * longer added, so the client stops calling back. + */ public static final Integer MAX_JAVASCRIPT_ITERATIONS = 10; /** diff --git a/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/flowelements/JsonBuilderDataInternal.java b/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/flowelements/JsonBuilderDataInternal.java index 3033bb28d..52c3ca539 100644 --- a/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/flowelements/JsonBuilderDataInternal.java +++ b/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/flowelements/JsonBuilderDataInternal.java @@ -28,8 +28,15 @@ import org.slf4j.Logger; //! [class] +/** Default implementation of {@link JsonBuilderData}. */ public class JsonBuilderDataInternal extends ElementDataBase implements JsonBuilderData { + /** + * Create a new instance. + * + * @param logger used for logging + * @param flowData the Flow Data this element data belongs to + */ public JsonBuilderDataInternal(Logger logger, FlowData flowData) { super(logger, flowData); } diff --git a/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/flowelements/JsonBuilderElement.java b/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/flowelements/JsonBuilderElement.java index c1eeab5af..6debb683f 100644 --- a/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/flowelements/JsonBuilderElement.java +++ b/pipeline/pipeline.jsonbuilder/src/main/java/fiftyone/pipeline/jsonbuilder/flowelements/JsonBuilderElement.java @@ -115,6 +115,10 @@ public JsonBuilderElement( * simultaneously. */ protected class PipelineConfig { + /** Create a new instance. */ + protected PipelineConfig() { + } + /** * A collection of the complete string names of any properties * with the 'delay execution' flag set to true. diff --git a/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/data/Languages.java b/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/data/Languages.java index d47cdbc12..5add697c6 100644 --- a/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/data/Languages.java +++ b/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/data/Languages.java @@ -35,6 +35,9 @@ * against the available locales. */ public class Languages { + /** Create a new instance. */ + public Languages() { + } /** * The result of matching a language tag against the available locales: the @@ -51,6 +54,7 @@ public static class Match { } /** + * Returns the translator for the matched locale. * @return the translator for the matched locale */ public Translator getTranslator() { @@ -58,6 +62,7 @@ public Translator getTranslator() { } /** + * Returns the locale key that was matched (e.g. "fr_FR"). * @return the locale key that was matched (e.g. "fr_FR") */ public String getLocale() { diff --git a/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/flowelements/TranslationEngine.java b/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/flowelements/TranslationEngine.java index cf9f0371f..c5f19fd70 100644 --- a/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/flowelements/TranslationEngine.java +++ b/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/flowelements/TranslationEngine.java @@ -42,7 +42,7 @@ public class TranslationEngine /** * Create a new translation engine. * @param sourceElementDataKey element data key of the source flow element - * @param translations the source -> destination property name pairs + * @param translations pairs of source and destination property names * @param sources the YAML translation sources, keyed on file name * @param fixedLanguage fixed language to translate to, or null to resolve * from the evidence diff --git a/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/flowelements/TranslationEngineBase.java b/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/flowelements/TranslationEngineBase.java index 5ec346535..29dbc61da 100644 --- a/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/flowelements/TranslationEngineBase.java +++ b/pipeline/pipeline.translation/src/main/java/fiftyone/pipeline/translation/flowelements/TranslationEngineBase.java @@ -122,8 +122,8 @@ public class TranslationEngineBase /** * Create a new translation engine. * @param sourceElementDataKey element data key of the source flow element - * @param translations the translations to execute (source -> destination - * property name pairs) + * @param translations the translations to execute, as pairs of source + * and destination property names * @param sources the YAML translation sources, keyed on file name * @param fixedLanguage fixed language to translate to. If set, the engine * always translates to this language; otherwise the diff --git a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/components/FiftyOneInterceptor.java b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/components/FiftyOneInterceptor.java index 1e19a9427..c0c76384a 100644 --- a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/components/FiftyOneInterceptor.java +++ b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/components/FiftyOneInterceptor.java @@ -66,6 +66,7 @@ */ @Component public class FiftyOneInterceptor extends HandlerInterceptorAdapter { + /** The Pipeline built from the options file. */ public Pipeline pipeline; private final PipelineResultService resultService; @@ -78,6 +79,20 @@ public class FiftyOneInterceptor extends HandlerInterceptorAdapter { private final UACHService uachService; + /** + * Create the interceptor and build the Pipeline from the options file the + * configuration names. + * + * @param config the interceptor configuration + * @param resultService processes each request + * @param flowDataProvider gives the Flow Data for each request + * @param clientsidePropertyService serves the client-side JavaScript and + * JSON + * @param fiftyOneJsService decides which requests get the JavaScript and + * JSON + * @param uachService sets the User-Agent Client Hints response headers + * @throws RuntimeException if the Pipeline could not be built + */ @Autowired public FiftyOneInterceptor( FiftyOneInterceptorConfig config, @@ -133,6 +148,11 @@ public FiftyOneInterceptor( fiftyOneJsService.setPaths(config.getJavaScriptPath(), jsonPath); } + /** + * Register the paths the client-side JavaScript and JSON are served from. + * + * @param viewControllerRegistry the registry to add the paths to + */ public static void enableClientsideProperties(ViewControllerRegistry viewControllerRegistry) { viewControllerRegistry.addViewController("/" + CORE_JS_NAME); viewControllerRegistry.addViewController(DEFAULT_JSON_PATH); @@ -211,6 +231,11 @@ public void afterCompletion( } } + /** + * The service that serves the client-side JavaScript and JSON. + * + * @return the service + */ public ClientsidePropertyService getClientsidePropertyService() { return clientsidePropertyService; } diff --git a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/components/FlowDataProvider.java b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/components/FlowDataProvider.java index 1c0d23d61..750f8af01 100644 --- a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/components/FlowDataProvider.java +++ b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/components/FlowDataProvider.java @@ -36,7 +36,11 @@ @Component public interface FlowDataProvider extends FlowDataProviderCore { + /** Default implementation of {@link FlowDataProvider}. */ @Component class Default extends FlowDataProviderCore.Default implements FlowDataProvider { + /** Create a new instance. */ + public Default() { + } } } diff --git a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/configuration/FiftyOneInterceptorConfigDefault.java b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/configuration/FiftyOneInterceptorConfigDefault.java index 3bd000b66..6e884616b 100644 --- a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/configuration/FiftyOneInterceptorConfigDefault.java +++ b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/configuration/FiftyOneInterceptorConfigDefault.java @@ -31,6 +31,9 @@ * Default implementation of the {@link FiftyOneInterceptorConfig} interface. */ public class FiftyOneInterceptorConfigDefault implements FiftyOneInterceptorConfig { + /** Create a new instance. */ + public FiftyOneInterceptorConfigDefault() { + } private String dataFilePath; @@ -47,13 +50,24 @@ public class FiftyOneInterceptorConfigDefault implements FiftyOneInterceptorConf private boolean setHeadersElementEnabled = true; + /** The servlet context of the application. */ @Autowired public ServletContext servletContext; + /** + * Set the path of the Pipeline options file. + * + * @param dataFilePath the path, or empty for the default file + */ public void setDataFilePath(String dataFilePath) { this.dataFilePath = dataFilePath; } + /** + * Set whether the client-side JavaScript and JSON are served. + * + * @param clientsidePropertiesEnabled true to serve them + */ public void setClientsidePropertiesEnabled(boolean clientsidePropertiesEnabled) { this.clientsidePropertiesEnabled = clientsidePropertiesEnabled; } @@ -73,18 +87,39 @@ public void setClientsideCacheMaxAge(int seconds) { this.clientsideCacheMaxAge = seconds; } + /** + * Set the path the JavaScript is served from. + * + * @param javaScriptPath the end of the request path, or empty for the + * default + */ public void setJavaScriptPath(String javaScriptPath) { this.javaScriptPath = javaScriptPath; } + /** + * Set the path the JSON is served from. + * + * @param jsonPath the end of the request path, or empty for the default + */ public void setJsonPath(String jsonPath) { this.jsonPath = jsonPath; } + /** + * Set whether the Pipeline gets a Sequence Element. + * + * @param sequenceElementEnabled true to add one + */ public void setSequenceElementEnabled(boolean sequenceElementEnabled) { this.sequenceElementEnabled = sequenceElementEnabled; } + /** + * Set whether the Pipeline gets a Set Headers Element. + * + * @param setHeadersElementEnabled true to add one + */ public void setSetHeadersElementEnabled(boolean setHeadersElementEnabled) { this.setHeadersElementEnabled = setHeadersElementEnabled; } diff --git a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/ClientsidePropertyService.java b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/ClientsidePropertyService.java index 83de0f8f5..1d67c46f1 100644 --- a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/ClientsidePropertyService.java +++ b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/ClientsidePropertyService.java @@ -37,6 +37,11 @@ */ @Service public interface ClientsidePropertyService extends ClientsidePropertyServiceCore { + /** + * Set the Pipeline whose results are served. + * + * @param pipeline the Pipeline + */ void setPipeline(Pipeline pipeline); /** @@ -54,8 +59,14 @@ void serveJson( HttpServletRequest request, HttpServletResponse response) throws IOException; + /** Default implementation of {@link ClientsidePropertyService}. */ @Service class Default extends ClientsidePropertyServiceCore.Default implements ClientsidePropertyService { + /** + * Create a new instance. + * + * @param flowDataProvider gives the Flow Data for each request + */ @Autowired public Default(FlowDataProvider flowDataProvider) { super(flowDataProvider, null); diff --git a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/FiftyOneJSService.java b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/FiftyOneJSService.java index 974b1be61..f15123450 100644 --- a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/FiftyOneJSService.java +++ b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/FiftyOneJSService.java @@ -32,6 +32,11 @@ @Service public interface FiftyOneJSService extends FiftyOneJSServiceCore { + /** + * Set whether the JavaScript and JSON are served. + * + * @param enabled true to serve them + */ void enable(boolean enabled); /** @@ -44,9 +49,15 @@ public interface FiftyOneJSService extends FiftyOneJSServiceCore { default void setPaths(String javaScriptPath, String jsonPath) { } + /** Default implementation of {@link FiftyOneJSService}. */ @Service class Default extends FiftyOneJSServiceCore.Default implements FiftyOneJSService { + /** + * Create a new instance. + * + * @param clientsidePropertyService serves the JavaScript and JSON + */ @Autowired public Default(ClientsidePropertyService clientsidePropertyService) { super(clientsidePropertyService, true); diff --git a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/PipelineResultService.java b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/PipelineResultService.java index d1e18ed85..0fd7d168f 100644 --- a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/PipelineResultService.java +++ b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/PipelineResultService.java @@ -33,11 +33,22 @@ @Service public interface PipelineResultService extends PipelineResultServiceCore { + /** + * Set the Pipeline each request is processed with. + * + * @param pipeline the Pipeline + */ void setPipeline(Pipeline pipeline); + /** Default implementation of {@link PipelineResultService}. */ @Service class Default extends PipelineResultServiceCore.Default implements PipelineResultService { + /** + * Create a new instance. + * + * @param evidenceService adds the evidence from each request + */ @Autowired public Default(WebRequestEvidenceService evidenceService) { super(evidenceService, null); diff --git a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/UACHService.java b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/UACHService.java index d6a0cb4b4..a2055d2d2 100644 --- a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/UACHService.java +++ b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/UACHService.java @@ -38,14 +38,27 @@ @Service public interface UACHService extends UACHServiceCore { + /** + * Set the User-Agent Client Hints response headers from the results for the + * request. + * + * @param request the request + * @param response the response to set the headers on + */ public void setResponseHeaders( HttpServletRequest request, HttpServletResponse response); + /** Default implementation of {@link UACHService}. */ @Service class Default extends UACHServiceCore.Default implements UACHService { // Internal FlowData provider private final FlowDataProvider flowDataProvider; + /** + * Create a new instance. + * + * @param flowDataProvider gives the Flow Data for each request + */ @Autowired public Default(FlowDataProvider flowDataProvider) { this.flowDataProvider = flowDataProvider; diff --git a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/WebRequestEvidenceService.java b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/WebRequestEvidenceService.java index 0b63bb171..433fd611d 100644 --- a/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/WebRequestEvidenceService.java +++ b/pipeline/pipeline.web.packages/pipeline.web.mvc/src/main/java/fiftyone/pipeline/web/mvc/services/WebRequestEvidenceService.java @@ -35,8 +35,13 @@ @Service public interface WebRequestEvidenceService extends WebRequestEvidenceServiceCore { + /** Default implementation of {@link WebRequestEvidenceService}. */ @Service class Default extends WebRequestEvidenceServiceCore.Default implements WebRequestEvidenceService { + /** Create a new instance. */ + public Default() { + } + @Override public void addEvidenceFromRequest( FlowData flowData, diff --git a/pipeline/pipeline.web.packages/pipeline.web.shared/src/main/java/fiftyone/pipeline/web/shared/Constants.java b/pipeline/pipeline.web.packages/pipeline.web.shared/src/main/java/fiftyone/pipeline/web/shared/Constants.java index 7687feed1..dc3f4ce7c 100644 --- a/pipeline/pipeline.web.packages/pipeline.web.shared/src/main/java/fiftyone/pipeline/web/shared/Constants.java +++ b/pipeline/pipeline.web.packages/pipeline.web.shared/src/main/java/fiftyone/pipeline/web/shared/Constants.java @@ -22,7 +22,14 @@ package fiftyone.pipeline.web.shared; +/** Constants shared by the web integrations. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } + + /** Key of the element data that holds the client-side JavaScript. */ public static final String CLIENTSIDE_JAVASCRIPT_DATA_KEY = "clientside-javascript"; + /** Name of the property that holds the client-side JavaScript. */ public static final String CLIENTSIDE_JAVASCRIPT_PROPERTY_NAME = "javascript"; } diff --git a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/Constants.java b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/Constants.java index 70efca179..764f40c7e 100644 --- a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/Constants.java +++ b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/Constants.java @@ -22,7 +22,11 @@ package fiftyone.pipeline.web; +/** Names, paths and defaults used by the web integration. */ public class Constants { + /** Create a new instance. */ + public Constants() { + } /** * The name of the core JavaScript served to the client. diff --git a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/PipelineFilter.java b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/PipelineFilter.java index f1ef653d4..cc3f16a51 100644 --- a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/PipelineFilter.java +++ b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/PipelineFilter.java @@ -63,6 +63,10 @@ * @see Specification */ public class PipelineFilter implements Filter { + /** Create a new instance. */ + public PipelineFilter() { + } + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(PipelineFilter.class); diff --git a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/StartupHelpers.java b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/StartupHelpers.java index fb6582b59..b6285ca52 100644 --- a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/StartupHelpers.java +++ b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/StartupHelpers.java @@ -39,6 +39,9 @@ * services needed. */ public class StartupHelpers { + /** Create a new instance. */ + public StartupHelpers() { + } /** * Get the index in the {@link PipelineOptions#elements} of the element with diff --git a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/ClientsidePropertyServiceCore.java b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/ClientsidePropertyServiceCore.java index 596c1c690..2652ec51f 100644 --- a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/ClientsidePropertyServiceCore.java +++ b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/ClientsidePropertyServiceCore.java @@ -302,6 +302,14 @@ public void serveJson( serveContent(request, response, ContentTypes.Json); } + /** + * Serve the JavaScript or JSON for the request. + * + * @param request the request + * @param response the response to write to + * @param contentType whether to serve JavaScript or JSON + * @throws IOException if the response could not be written + */ public void serveContent( HttpServletRequest request, HttpServletResponse response, diff --git a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/FiftyOneJSServiceCore.java b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/FiftyOneJSServiceCore.java index 7ec017007..b32b0b6b5 100644 --- a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/FiftyOneJSServiceCore.java +++ b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/FiftyOneJSServiceCore.java @@ -93,9 +93,13 @@ default boolean serveNotModified( * Default implementation of the {@link FiftyOneJSServiceCore} service. */ class Default implements FiftyOneJSServiceCore { + /** Serves the JavaScript and JSON. */ protected final ClientsidePropertyServiceCore clientsidePropertyServiceCore; + /** Whether the JavaScript and JSON are served. */ protected boolean enabled; + /** The end of the request path the JavaScript is served for. */ protected String javaScriptPath; + /** The end of the request path the JSON is served for. */ protected String jsonPath; /** @@ -240,10 +244,6 @@ public boolean serveNotModified( flowData, request, response) : clientsidePropertyServiceCore.serveJsonNotModified( flowData, request, response); - } catch (IOException | RuntimeException e) { - throw e; - } catch (Exception e) { - throw new IOException("FlowData could not be disposed of.", e); } } diff --git a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/FlowDataProviderCore.java b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/FlowDataProviderCore.java index 11b42b490..28d49818d 100644 --- a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/FlowDataProviderCore.java +++ b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/FlowDataProviderCore.java @@ -52,6 +52,9 @@ public interface FlowDataProviderCore { * Default implementation of the {@link FlowDataProviderCore} service. */ class Default implements FlowDataProviderCore { + /** Create a new instance. */ + public Default() { + } @Override public FlowData getFlowData(HttpServletRequest request) { diff --git a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/UACHServiceCore.java b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/UACHServiceCore.java index dfe601b10..3b4653917 100644 --- a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/UACHServiceCore.java +++ b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/UACHServiceCore.java @@ -50,6 +50,9 @@ void setResponseHeaders( * Default implementation of the {@link UACHServiceCore} service. */ class Default implements UACHServiceCore { + /** Create a new instance. */ + public Default() { + } @SuppressWarnings("unchecked") @Override diff --git a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/WebRequestEvidenceServiceCore.java b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/WebRequestEvidenceServiceCore.java index c9f69c96e..5edd7256e 100644 --- a/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/WebRequestEvidenceServiceCore.java +++ b/pipeline/pipeline.web.packages/pipeline.web/src/main/java/fiftyone/pipeline/web/services/WebRequestEvidenceServiceCore.java @@ -58,6 +58,9 @@ public interface WebRequestEvidenceServiceCore { * service. */ class Default implements WebRequestEvidenceServiceCore { + /** Create a new instance. */ + public Default() { + } private static final String EVIDENCE_REQUEST_METHOD = EVIDENCE_SERVER_PREFIX + EVIDENCE_SEPERATOR + "request-method"; diff --git a/pipeline/pom.xml b/pipeline/pom.xml index 43d5fa5f6..cbcc52286 100644 --- a/pipeline/pom.xml +++ b/pipeline/pom.xml @@ -180,7 +180,7 @@ ${maven.compiler.target} true - -Xlint:all,-try,-options + -Xlint:all -Werror @@ -280,24 +280,11 @@ maven-javadoc-plugin ${maven-javadoc-plugin.version} - none - true - + + all + true @@ -421,4 +408,21 @@ scm:git:https://github.com/51Degrees/51degrees-java.git scm:git:https://github.com/51Degrees/51degrees-java.git + + + + + release-8 + + [9,) + + + 8 + + +