text,length,is_long_context,metric_val,label_metric "// Copyright 2018 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. :kotlin-reference: https://kotlinlang.org/docs/reference/ :kotlin-tutorials: https://kotlinlang.org/tutorials/ :kotlin-dsl-samples: https://github.com/gradle/kotlin-dsl-samples/tree/master/samples :gradle-issues: https://github.com/gradle/gradle/issues/ :plugin-portal: https://plugins.gradle.org/ [[kotlin_dsl]] = Gradle Kotlin DSL Primer Gradle's Kotlin DSL provides an alternative syntax to the traditional Groovy DSL with an enhanced editing experience in supported IDEs, with superior content assist, refactoring, documentation, and more. This chapter provides details of the main Kotlin DSL constructs and how to use it to interact with the Gradle API. [TIP] ==== If you are interested in migrating an existing Gradle build to the Kotlin DSL, please also check out the dedicated <>. ==== [[kotdsl:prerequisites]] == Prerequisites * The embedded Kotlin compiler is known to work on Linux, macOS, Windows, Cygwin, FreeBSD and Solaris on x86-64 architectures. * Knowledge of Kotlin syntax and basic language features is very helpful. The link:{kotlin-reference}[Kotlin reference documentation] and link:https://kotlinlang.org/docs/tutorials/koans.html[Kotlin Koans] will help you to learn the basics. * Use of the <> block to declare Gradle plugins significantly improves the editing experience and is highly recommended. [[sec:ide_support]] == IDE support The Kotlin DSL is fully supported by IntelliJ IDEA and Android Studio. Other IDEs do not yet provide helpful tools for editing Kotlin DSL files, but you can still import Kotlin-DSL-based builds and work with them as usual. .IDE support matrix [cols="">.^,^.^,^.^,^.^"",frame=none,grid=rows,options=""header""] |=== ||Build import|Syntax highlighting ^1^|Semantic editor ^2^ |IntelliJ IDEA |[.green]#*✓*# |[.green]#*✓*# |[.green]#*✓*# |Android Studio |[.green]#*✓*# |[.green]#*✓*# |[.green]#*✓*# |Eclipse IDE |[.green]#*✓*# |[.green]#*✓*# |[.red]#✖# |CLion |[.green]#*✓*# |[.green]#*✓*# |[.red]#✖# |Apache NetBeans |[.green]#*✓*# |[.green]#*✓*# |[.red]#✖# |Visual Studio Code ^(LSP)^ |[.green]#*✓*# |[.green]#*✓*# |[.red]#✖# |Visual Studio |[.green]#*✓*# |[.red]#✖# |[.red]#✖# |=== [%hardbreaks] ^1^ ^Kotlin^ ^syntax^ ^highlighting^ ^in^ ^Gradle^ ^Kotlin^ ^DSL^ ^scripts^ ^2^ ^code^ ^completion,^ ^navigation^ ^to^ ^sources,^ ^documentation,^ ^refactorings^ ^etc...^ ^in^ ^Gradle^ ^Kotlin^ ^DSL^ ^scripts^ As mentioned in the limitations, you must link:https://www.jetbrains.com/help/idea/gradle.html#gradle_import[import your project from the Gradle model] to get content-assist and refactoring tools for Kotlin DSL scripts in IntelliJ IDEA. In addition, IntelliJ IDEA and Android Studio might spawn up to 3 Gradle daemons when editing Gradle scripts — one for each type of script: build scripts, settings files and initialization scripts. Builds with slow configuration time might affect the IDE responsiveness, so please check out the <> to help resolve such issues. === Automatic build import vs. automatic reloading of script dependencies Both IntelliJ IDEA and Android Studio — which is derived from IntelliJ IDEA — will detect when you make changes to your build logic and offer two suggestions: 1. Import the whole build again + image::intellij-build-import-popup.png[IntelliJ IDEA, width=300] + image::android-studio-build-sync-popup.png[IntelliJ IDEA] 2. Reload script dependencies when editing a build script + image::intellij-script-dependencies-reload.png[Reload script dependencies] We recommend that you _disable automatic build import_, but _enable automatic reloading of script dependencies_. That way you get early feedback while editing Gradle scripts and control over when the whole build setup gets synchronized with your IDE. === Troubleshooting The IDE support is provided by two components: * The Kotlin Plugin used by IntelliJ IDEA/Android Studio * Gradle The level of support varies based on the versions of each. If you run into trouble, the first thing you should try is running `./gradlew tasks` from the command line to see whether your issue is limited to the IDE. If you encounter the same problem from the command line, then the issue is with the build rather than the IDE integration. If you can run the build successfully from the command line but your script editor is complaining, then you should try restarting your IDE and invalidating its caches. If the above doesn't work and you suspect an issue with the Kotlin DSL script editor, you can: * Run `./gradle tasks` to get more details * Check the logs in one of these locations: ** `$HOME/Library/Logs/gradle-kotlin-dsl` on Mac OS X ** `$HOME/.gradle-kotlin-dsl/log` on Linux ** `$HOME/AppData/Local/gradle-kotlin-dsl/log` on Windows * Open an issue on the link:{gradle-issues}[Gradle issue tracker], including as much detail as you can. From version 5.1 onwards, the log directory is cleaned up automatically. It is checked periodically (at most every 24 hours) and log files are deleted if they haven’t been used for 7 days. If the above isn't enough to pinpoint the problem, you can enable the `org.gradle.kotlin.dsl.logging.tapi` system property in your IDE. This will cause the Gradle Daemon to log extra information in its log file located in `$HOME/.gradle/daemon`. In IntelliJ IDEA this can be done by opening `Help > Edit Custom VM Options...` and adding `-Dorg.gradle.kotlin.dsl.logging.tapi=true`. For IDE problems outside of the Kotlin DSL script editor, please open issues in the corresponding IDE's issue tracker: * link:[JetBrains's IDEA issue tracker], * link:[Google's Android Studio issue tracker]. Lastly, if you face problems with Gradle itself or with the Kotlin DSL, please open issues on the link:{gradle-issues}[Gradle issue tracker]. [[sec:scripts]] == Kotlin DSL scripts Just like the Groovy-based equivalent, the Kotlin DSL is implemented on top of Gradle's Java API. Everything you can read in a Kotlin DSL script is Kotlin code compiled and executed by Gradle. Many of the objects, functions and properties you use in your build scripts come from the Gradle API and the APIs of the applied plugins. === Script file names [NOTE] ==== Groovy DSL script files use the `.gradle` file name extension. Kotlin DSL script files use the `.gradle.kts` file name extension. ==== To activate the Kotlin DSL, simply use the `.gradle.kts` extension for your build scripts in place of `.gradle`. That also applies to the <> — for example `settings.gradle.kts` — and <>. Note that you can mix Groovy DSL build scripts with Kotlin DSL ones, i.e. a Kotlin DSL build script can apply a Groovy DSL one and each project in a multi-project build can use either one. We recommend that you apply the following conventions to get better IDE support: * Name settings scripts (or any script that is backed by a Gradle `Settings` object) according to the pattern `*.settings.gradle.kts` — this includes script plugins that are applied from settings scripts * Name <> according to the pattern `*.init.gradle.kts` or simply `init.gradle.kts`. This is so that the IDE knows what type of object ""backs"" the script, be it link:{groovyDslPath}/org.gradle.api.Project.html[Project], link:{groovyDslPath}/org.gradle.api.initialization.Settings.html[Settings] or link:{groovyDslPath}/org.gradle.api.invocation.Gradle.html[Gradle]. [[sec:implicit_imports]] === Implicit imports All Kotlin DSL build scripts have implicit imports consisting of: * The <> * The Kotlin DSL API, which is all types within the `org.gradle.kotlin.dsl` and `org.gradle.kotlin.dsl.plugins.dsl` packages currently [CAUTION] .Avoid using internal Kotlin DSL APIs ==== Use of internal Kotlin DSL APIs in plugins and build scripts has the potential to break builds when either Gradle or plugins change. The link:{kotlinDslPath}/[Kotlin DSL API] extends the <> with the types listed in the https://gradle.github.io/kotlin-dsl-docs/api/[corresponding API docs] that are in the `org.gradle.kotlin.dsl` or `org.gradle.kotlin.dsl.plugins.dsl` packages (but not subpackages of those). ==== [[sec:configuring_plugins]] [[type-safe-accessors]] == Type-safe model accessors The Groovy DSL allows you to reference many elements of the build model by name, even when they are defined at runtime. Think named configurations, named source sets, and so on. For example, you can get hold of the `implementation` configuration via `configurations.implementation`. The Kotlin DSL replaces such dynamic resolution with type-safe model accessors that work with model elements contributed by plugins. [[kotdsl:accessor_applicability]] === Understanding when type-safe model accessors are available The Kotlin DSL currently supports type-safe model accessors for any of the following that are contributed by plugins: * Dependency and artifact configurations (such as `implementation` and `runtimeOnly` contributed by the Java Plugin) * Project extensions and conventions (such as `sourceSets`) * Elements in the `tasks` and `configurations` containers * Elements in <> (for example the source sets contributed by the Java Plugin that are added to the `sourceSets` container) * Extensions on each of the above [IMPORTANT] ==== Only the main project build scripts and precompiled project script plugins have type-safe model accessors. Initialization scripts, settings scripts, script plugins do not. These limitations will be removed in a future Gradle release. ==== The set of type-safe model accessors available is calculated right before evaluating the script body, immediately after the `plugins {}` block. Any model elements contributed after that point do not work with type-safe model accessors. For example, this includes any configurations you might define in your own build script. However, this approach does mean that you can use type-safe accessors for any model elements that are contributed by plugins that are _applied by parent projects_. The following project build script demonstrates how you can access various configurations, extensions and other elements using type-safe accessors: .Using type-safe model accessors ==== include::sample[dir=""snippets/kotlinDsl/accessors/kotlin"",files=""build.gradle.kts[tags=accessors]""] ==== <1> Uses type-safe accessors for the `api`, `implementation` and `testImplementation` dependency configurations contributed by the <> <2> Uses an accessor to configure the `sourceSets` project extension <3> Uses an accessor to configure the `main` source set <4> Uses an accessor to configure the `java` source for the `main` source set <5> Uses an accessor to configure the `test` task [TIP] ==== Your IDE knows about the type-safe accessors, so it will include them in its suggestions. This will happen both at the top level of your build scripts — most plugin extensions are added to the `Project` object — and within the blocks that configure an extension. ==== Note that accessors for elements of containers such as `configurations`, `tasks` and `sourceSets` leverage Gradle's <>. For example, on `tasks` they are of type `TaskProvider` and provide a lazy reference and lazy configuration of the underlying task. Here are some examples that illustrate the situations in which configuration avoidance applies: [source,kotlin] ---- tasks.test { // lazy configuration } // Lazy reference val testProvider: TaskProvider = tasks.test testProvider { // lazy configuration } // Eagerly realized Test task, defeat configuration avoidance if done out of a lazy context val test: Test = tasks.test.get() ---- For all other containers than `tasks`, accessors for elements are of type `NamedDomainObjectProvider` and provide the same behavior. [[sec:kotlin_using_standard_api]] === Understanding what to do when type-safe model accessors are not available Consider the sample build script shown above that demonstrates the use of type-safe accessors. The following sample is exactly the same except that is uses the `apply()` method to apply the plugin. The build script can not use type-safe accessors in this case because the `apply()` call happens in the body of the build script. You have to use other techniques instead, as demonstrated here: .Configuring plugins without type-safe accessors ==== include::sample[dir=""snippets/kotlinDsl/noAccessors/kotlin"",files=""build.gradle.kts[tags=no-accessors]""] ==== Type-safe accessors are unavailable for model elements contributed by the following: * Plugins applied via the `apply(plugin = ""id"")` method * The project build script * Script plugins, via `apply(from = ""script-plugin.gradle.kts"")` * Plugins applied via <> You also can not use type-safe accessors in Binary Gradle plugins implemented in Kotlin. If you can't find a type-safe accessor, _fall back to using the normal API_ for the corresponding types. To do that, you need to know the names and/or types of the configured model elements. We'll now show you how those can be discovered by looking at the above script in detail. ==== Artifact configurations The following sample demonstrates how to reference and configure artifact configurations without type accessors: .Artifact configurations ==== include::sample[dir=""snippets/kotlinDsl/noAccessors/kotlin"",files=""build.gradle.kts[tags=dependencies]""] ==== The code looks similar to that for the type-safe accessors, except that the configuration names are string literals in this case. You can use string literals for configuration names in dependency declarations and within the `configurations {}` block. The IDE won't be able to help you discover the available configurations in this situation, but you can look them up either in the corresponding plugin's documentation or by running `gradle dependencies`. ==== Project extensions and conventions Project extensions and <<#sec:kotlin_dsl_about_conventions,conventions>> have both a name and a unique type, but the Kotlin DSL only needs to know the type in order to configure them. As the following sample shows for the `sourceSets {}` and `java {}` blocks from the original example build script, you can use the link:{kotlinDslPath}/org.gradle.kotlin.dsl/org.gradle.api.-project/configure.html[`configure()`] function with the corresponding type to do that: .Project extensions and conventions ==== include::sample[dir=""snippets/kotlinDsl/noAccessors/kotlin"",files=""build.gradle.kts[tags=project-extension]""] ==== Note that `sourceSets` is a Gradle extension on `Project` of type `SourceSetContainer` and `java` is an extension on `Project` of type `JavaPluginExtension`. You can discover what extensions and conventions are available either by looking at the documentation for the applied plugins or by running `gradle kotlinDslAccessorsReport`, which prints the Kotlin code necessary to access the model elements contributed by all the applied plugins. The report provides both names and types. As a last resort, you can also check a plugin's source code, but that shouldn't be necessary in the majority of cases. Note that you can also use the link:{kotlinDslPath}/org.gradle.kotlin.dsl/org.gradle.api.-project/the.html[`the()`] function if you only need a reference to the extension or convention without configuring it, or if you want to perform a one-line configuration, like so: [source,kotlin] ---- the()[""main""].srcDir(""src/core/java"") ---- The snippet above also demonstrates one way of configuring the elements of a project extension that is a container. ==== Elements in project-extension containers Container-based project extensions, such as `SourceSetContainer`, also allow you to configure the elements held by them. In our sample build script, we want to configure a source set named `main` within the source set container, which we can do by using the link:{javadocPath}/org/gradle/api/NamedDomainObjectCollection.html#named-java.lang.String-[named()] method in place of an accessor, like so: .Elements of project extensions that are containers ==== include::sample[dir=""snippets/kotlinDsl/noAccessors/kotlin"",files=""build.gradle.kts[tags=project-container-extension]""] ==== All elements within a container-based project extension have a name, so you can use this technique in all such cases. As for project extensions and conventions themselves, you can discover what elements are present in any container by either looking at the documentation of the applied plugins or by running `gradle kotlinDslAccessorsReport`. And as a last resort, you may be able to view the plugin's source code to find out what it does, but that shouldn't be necessary in the majority of cases. ==== Tasks Tasks are not managed through a container-based project extension, but they are part of a container that behaves in a similar way. This means that you can configure tasks in the same way as you do for source sets, as you can see in this example: .Tasks ==== include::sample[dir=""snippets/kotlinDsl/noAccessors/kotlin"",files=""build.gradle.kts[tags=tasks]""] ==== We are using the Gradle API to refer to the tasks by name and type, rather than using accessors. Note that it's necessary to specify the type of the task explicitly, otherwise the script won't compile because the inferred type will be `Task`, not `Test`, and the `testLogging` property is specific to the `Test` task type. You can, however, omit the type if you only need to configure properties or to call methods that are common to all tasks, i.e. they are declared on the `Task` interface. One can discover what tasks are available by running `gradle tasks`. You can then find out the type of a given task by running `gradle help --task `, as demonstrated here: [source] ---- ❯ ./gradlew help --task test ... Type Test (org.gradle.api.tasks.testing.Test) ---- Note that the IDE can assist you with the required imports, so you only need the simple names of the types, i.e. without the package name part. In this case, there's no need to import the `Test` task type as it is part of the Gradle API and is therefore <>. [[sec:kotlin_dsl_about_conventions]] === About conventions Some of the Gradle core plugins expose configurability with the help of a so-called _convention_ object. These serve a similar purpose to — and have now been superseded by — _extensions_. Please avoid using convention objects when writing new plugins. The long term plan is to migrate all Gradle core plugins to use extensions and remove the convention objects altogether. As seen above, the Kotlin DSL provides accessors only for convention objects on `Project`. There are situations that require you to interact with a Gradle plugin that uses convention objects on other types. The Kotlin DSL provides the `withConvention(T::class) {}` extension function to do this: .Configuring source set conventions ==== include::sample[dir=""snippets/kotlinDsl/sourceSetConvention/kotlin"",files=""build.gradle.kts[tags=source-set-convention]""] ==== This technique is most commonly required for source sets that are added by language plugins other than the Java Plugin, e.g. the Groovy Plugin and the Scala Plugin. You can see which plugins add which properties to source sets in the link:{groovyDslPath}/org.gradle.api.tasks.SourceSet.html[SourceSet] reference documentation. [[kotdsl:multi_project_builds]] [[sec:multi_project_builds]] == Multi-project builds As with single-project builds, you should try to use the `plugins {}` block in your multi-project builds so that you can use the type-safe accessors. Another consideration with multi-project builds is that you won't be able to use type-safe accessors when configuring subprojects within the root build script or with other forms of cross configuration between projects. We discuss both topics in more detail in the following sections. [[sec:multi_project_builds_applying_plugins]] === Applying plugins You can declare your plugins within the subprojects to which they apply, but we recommend that you also declare them within the root project build script. This makes it easier to keep plugin versions consistent across projects within a build. The approach also improves the performance of the build. The <> chapter explains how you can declare plugins in the root project build script with a version and then apply them to the appropriate subprojects' build scripts. What follows is an example of this approach using three subprojects and three plugins. Note how the root build script only declares the community plugins as the Java Library Plugin is tied to the version of Gradle you are using: [[ex:multi_project_ratpack]] .Declare plugin dependencies in the root build script using the `plugins {}` block ==== include::sample[dir=""snippets/kotlinDsl/multiProjectBuild/kotlin"",files=""settings.gradle.kts[tags=base];build.gradle.kts[tags=root];domain/build.gradle.kts[];infra/build.gradle.kts[];http/build.gradle.kts[]""] ==== If your build requires additional plugin repositories on top of the Gradle Plugin Portal, you should declare them in the `pluginManagement {}` block in your `settings.gradle.kts` file, like so: .Declare additional plugin repositories ==== include::sample[dir=""snippets/kotlinDsl/multiProjectBuild/kotlin"",files=""settings.gradle.kts[tags=repositories]""] ==== Plugins fetched from a source other than the link:https://plugins.gradle.org/[Gradle Plugin Portal] can only be declared via the `plugins {}` block if they are published with their <>. NOTE: At the time of writing, all versions of the Android Plugin for Gradle up to 3.2.0 present in the `google()` repository lack plugin marker artifacts. If those artifacts are missing, then you can't use the `plugins {}` block. You must instead fall back to declaring your plugin dependencies using the `buildscript {}` block in the root project build script. Here's an example of doing that for the Android Plugin: .Declare plugin dependencies in the root build script using the `buildscript {}` block ==== include::sample[dir=""snippets/kotlinDsl/androidBuild/kotlin"",files=""settings.gradle.kts[tags=android];build.gradle.kts[tags=android-buildscript];lib/build.gradle.kts[tags=android];app/build.gradle.kts[tags=android]""] ==== This technique is not that different from what Android Studio produces when creating a new build. The main difference is that the subprojects' build scripts in the above sample declare their plugins using the `plugins {}` block. This means that you can use type-safe accessors for the model elements that they contribute. Note that you can't use this technique if you want to apply such a plugin either to the root project build script of a multi-project build (rather than solely to its subprojects) or to a single-project build. You'll need to use a different approach in those cases that we detail in <>. [[sec:kotlin_cross_project_configuration]] === Cross-configuring projects <> is a mechanism by which you can configure a project from another project's build script. A common example is when you configure subprojects in the root project build script. Taking this approach means that you won't be able to use type-safe accessors for model elements contributed by the plugins. You will instead have to rely on string literals and the standard Gradle APIs. As an example, let's modify the <> to fully configure its subprojects from the root project build script: .Cross-configuring projects ==== include::sample[dir=""snippets/kotlinDsl/multiProjectBuild/kotlin"",files=""settings.gradle.kts[tags=base];build.gradle.kts[tags=cross]""] ==== Note how we're using the `apply()` method to apply the plugins since the `plugins {}` block doesn't work in this context. We are also using standard APIs instead of type-safe accessors to configure tasks, extensions and conventions — an approach that we discussed in <>. [[sec:plugins_resolution_strategy]] == When you can't use the `plugins {}` block Plugins fetched from a source other than the link:https://plugins.gradle.org/[Gradle Plugin Portal] may or may not be usable with the `plugins {}` block. It depends on how they have been published and, specifically, whether they have been published with the necessary <>. For example, the Android Plugin for Gradle is not published to the Gradle Plugin Portal and — at least up to version 3.2.0 of the plugin — the metadata required to resolve the artifacts for a given plugin identifier is not published to the Google repository. If your build is a multi-project build and you don't need to apply such a plugin to your _root_ project, then you can get round this issue using the technique <>. For any other situation, keep reading. [TIP] ==== When publishing plugins, please use Gradle's built-in <>. It automates the publication of the metadata necessary to make your plugins usable with the `plugins {}` block. ==== We will show you in this section how to apply the Android Plugin to a single-project build or the root project of a multi-project build. The goal is to instruct your build on how to map the `com.android.application` plugin identifier to a resolvable artifact. This is done in two steps: * Add a plugin repository to the build's settings script * Map the plugin ID to the corresponding artifact coordinates You accomplish both steps by configuring a `pluginManagement {}` block in the build's settings script. To demonstrate, the following sample adds the `google()` repository — where the Android plugin is published — to the repository search list, and uses a `resolutionStrategy {}` block to map the `com.android.application` plugin ID to the `com.android.tools.build:gradle:` artifact available in the `google()` repository: .Mapping plugin IDs to dependency coordinates ==== include::sample[dir=""snippets/kotlinDsl/androidSingleBuild/kotlin"",files=""settings.gradle.kts[tags=android];build.gradle.kts[tags=android]""] ==== In fact, the above sample will work for all `com.android.*` plugins that are provided by the specified module. That's because the packaged module contains the details of which plugin ID maps to which plugin implementation class, using the properties-file mechanism described in the <> chapter. See the <> section of the Gradle user manual for more information on the `pluginManagement {}` block and what it can be used for. // [PL] It seems to me that this block of content should really be in a more generic part // of the user manual as it discusses techniques that apply outside of the Kotlin DSL. // In fact, it indicates missing content that this chapter should be able to link to. // // In the case of multi-project builds, this approach is similar to using a `buildscript {}` block in the root project build script to depend on third party plugins and then using `plugins {}` in your sub project build scripts to apply them. // The main difference is that this approach means that the root project can also benefit from the `plugins {}` block and it is more aligned with Gradle best practices. // // [PL] We should also aim to avoid temporary information in the user manual that could // be out of date at any time. // The same approach can be used to resolve plugins from composite builds, which link:https://github.com/gradle/gradle/issues/2528[do not expose plugin markers] yet. // Simply map the plugin ID to the corresponding artifact coordinates as shown in the Android samples above. // TODO ? // [[sec:buildSrc]] // == Using `buildSrc` // // 1. what is buildSrc -> link // 2. apply the `kotlin-dsl` plugin, see below for the details // 3. all dependencies added to `buildSrc/build.gradle.kts` will be available to all build scripts // 3. all members from `buildSrc/src/main/kotlin` will be available to all build scripts // 4. handy for constants, objects, functions, extension functions // 5. perfect for Gradle Tasks, Gradle Plugins and DSL Extensions [[kotdsl:containers]] == Working with container objects The Gradle build model makes heavy use of container objects (or just ""containers""). For example, both `configurations` and `tasks` are container objects that contain `Configuration` and `Task` objects respectively. Community plugins also contribute containers, like the `android.buildTypes` container contributed by the Android Plugin. The Kotlin DSL provides several ways for build authors to interact with containers. We look at each of those ways next, using the `tasks` container as an example. [TIP] ==== Note that you can leverage the type-safe accessors described in <> if you are configuring existing elements on supported containers. That section also describes which containers support type-safe accessors. ==== === Using the container API All containers in Gradle implement link:{groovyDslPath}/org.gradle.api.NamedDomainObjectContainer.html#org.gradle.api.NamedDomainObjectContainer[NamedDomainObjectContainer]. Some of them can contain objects of different types and implement link:{groovyDslPath}/org.gradle.api.PolymorphicDomainObjectContainer.html#org.gradle.api.PolymorphicDomainObjectContainer[PolymorphicDomainObjectContainer]. The simplest way to interact with containers is through these interfaces. The following sample demonstrates how you can use the link:{groovyDslPath}/org.gradle.api.NamedDomainObjectContainer.html#org.gradle.api.NamedDomainObjectContainer:named(java.lang.String)[named()] method to configure existing tasks and the link:{groovyDslPath}/org.gradle.api.NamedDomainObjectContainer.html#org.gradle.api.NamedDomainObjectContainer:register(java.lang.String)[register()] method to create new ones. .Using the container API ==== include::sample[dir=""snippets/kotlinDsl/containers-api/kotlin"",files=""build.gradle.kts[tags=api]""] ==== <1> Gets a reference of type `Task` to the existing task named `check` <2> Registers a new untyped task named `myTask1` <3> Gets a reference to the existing task named `compileJava` of type `JavaCompile` <4> Registers a new task named `myCopy1` of type `Copy` <5> Gets a reference to the existing (untyped) task named `assemble` and configures it — you can only configure properties and methods that are available on `Task` with this syntax <6> Registers a new untyped task named `myTask2` and configures it — you can only configure properties and methods that are available on `Task` in this case <7> Gets a reference to the existing task named `test` of type `Test` and configures it — in this case you have access to the properties and methods of the specified type <8> Registers a new task named `myCopy2` of type `Copy` and configures it [NOTE] ==== The above sample relies on the configuration avoidance APIs. If you need or want to eagerly configure or register container elements, simply replace `named()` with `getByName()` and `register()` with `create()`. ==== === Using Kotlin delegated properties Another way to interact with containers is via Kotlin delegated properties. These are particularly useful if you need a reference to a container element that you can use elsewhere in the build. In addition, Kotlin delegated properties can easily be renamed via IDE refactoring. The following sample does the exact same things as the one in the previous section, but it uses delegated properties and reuses those references in place of string-literal task paths: .Using Kotlin delegated properties ==== include::sample[dir=""snippets/kotlinDsl/containers-delegated-properties/kotlin"",files=""build.gradle.kts[tags=delegated-properties]""] ==== <1> Uses the reference to the `myTask1` task rather than a task path [NOTE] ==== The above rely on configuration avoidance APIs. If you need to eagerly configure or register container elements simply replace link:{kotlinDslPath}/org.gradle.kotlin.dsl/org.gradle.api.-named-domain-object-container/existing.html[`existing()`] with link:{kotlinDslPath}/org.gradle.kotlin.dsl/org.gradle.api.-named-domain-object-container/getting.html[`getting()`] and link:{kotlinDslPath}/org.gradle.kotlin.dsl/org.gradle.api.-named-domain-object-container/registering.html[`registering()`] with link:{kotlinDslPath}/org.gradle.kotlin.dsl/org.gradle.api.-named-domain-object-container/creating.html[`creating()`]. ==== === Configuring multiple container elements together When configuring several elements of a container one can group interactions in a block in order to avoid repeating the container's name on each interaction. The following example uses a combination of type-safe accessors, the container API and Kotlin delegated properties: .Container scope ==== include::sample[dir=""snippets/kotlinDsl/containers-scope/kotlin"",files=""build.gradle.kts[tags=scope]""] ==== // TODO decide if we should document this given the current limitation // === The container scope string invoke extension // // .The container scope string invoke extension // ==== // include::sample[dir=""snippets/kotlinDsl/containers-string-invoke/kotlin"",files=""build.gradle.kts[tags=string-invoke]""] // ==== [[kotdsl:properties]] == Working with runtime properties Gradle has two main sources of properties that are defined at runtime: <> and <>. The Kotlin DSL provides specific syntax for working with these types of properties, which we look at in the following sections. === Project properties The Kotlin DSL allows you to access project properties by binding them via Kotlin delegated properties. Here's a sample snippet that demonstrates the technique for a couple of project properties, one of which _must_ be defined: .build.gradle.kts [source,kotlin] ---- val myProperty: String by project // <1> val myNullableProperty: String? by project // <2> ---- <1> Makes the `myProperty` project property available via a `myProperty` delegated property — the project property must exist in this case, otherwise the build will fail when the build script attempts to use the `myProperty` value <2> Does the same for the `myNullableProperty` project property, but the build won't fail on using the `myNullableProperty` value as long as you check for null (standard https://kotlinlang.org/docs/reference/null-safety.html[Kotlin rules for null safety] apply) The same approach works in both settings and initialization scripts, except you use `by settings` and `by gradle` respectively in place of `by project`. === Extra properties Extra properties are available on any object that implements the link:{groovyDslPath}/org.gradle.api.plugins.ExtensionAware.html#org.gradle.api.plugins.ExtensionAware[ExtensionAware] interface. Kotlin DSL allows you to access extra properties and create new ones via delegated properties, using any of the `by extra` forms demonstrated in the following sample: .build.gradle.kts [source,kotlin] ---- val myNewProperty by extra(""initial value"") // <1> val myOtherNewProperty by extra { ""calculated initial value"" } // <2> val myProperty: String by extra // <3> val myNullableProperty: String? by extra // <4> ---- <1> Creates a new extra property called `myNewProperty` in the current context (the project in this case) and initializes it with the value `""initial value""`, which also determines the property's _type_ <2> Create a new extra property whose initial value is calculated by the provided lambda <3> Binds an existing extra property from the current context (the project in this case) to a `myProperty` reference <4> Does the same as the previous line but allows the property to have a null value This approach works for all Gradle scripts: project build scripts, script plugins, settings scripts and initialization scripts. You can also access extra properties on a root project from a subproject using the following syntax: .my-sub-project/build.gradle.kts [source,kotlin] ---- val myNewProperty: String by rootProject.extra // <1> ---- <1> Binds the root project's `myNewProperty` extra property to a reference of the same name Extra properties aren't just limited to projects. For example, `Task` extends `ExtensionAware`, so you can attach extra properties to tasks as well. Here's an example that defines a new `myNewTaskProperty` on the `test` task and then uses that property to initialize another task: .build.gradle.kts [source,kotlin] ---- tasks { test { val reportType by extra(""dev"") // <1> doLast { // Use 'suffix' for post processing of reports } } register(""archiveTestReports"") { val reportType: String by test.get().extra // <2> archiveAppendix.set(reportType) from(test.get().reports.html.destination) } } ---- <1> Creates a new `reportType` extra property on the `test` task <2> Makes the `test` task's `reportType` extra property available to configure the `archiveTestReports` task If you're happy to use eager configuration rather than the configuration avoidance APIs, you could use a single, ""global"" property for the report type, like this: .build.gradle.kts [source,kotlin] ---- tasks.test.doLast { ... } val testReportType by tasks.test.get().extra(""dev"") // <1> tasks.create(""archiveTestReports"") { archiveAppendix.set(testReportType) // <2> from(test.get().reports.html.destination) } ---- <1> Creates and initializes an extra property on the `test` task, binding it to a ""global"" property <2> Uses the ""global"" property to initialize the `archiveTestReports` task There is one last syntax for extra properties that we should cover, one that treats `extra` as a map. We recommend against using this in general as you lose the benefits of Kotlin's type checking and it prevents IDEs from providing as much support as they could. However, it is more succinct than the delegated properties syntax and can reasonably be used if you only need to set the value of an extra property without referencing it later. Here's a simple example demonstrating how to set and read extra properties using the map syntax: .build.gradle.kts [source,kotlin] ---- extra[""myNewProperty""] = ""initial value"" // <1> tasks.create(""myTask"") { doLast { println(""Property: ${project.extra[""myNewProperty""]}"") // <2> } } ---- <1> Creates a new project extra property called `myNewProperty` and sets its value <2> Reads the value from the project extra property we created — note the `project.` qualifier on `extra[...]`, otherwise Gradle will assume we want to read an extra property from the _task_ // === `Property`, `Provider` and `NamedDomainObjectProvider` [[sec:kotlin-dsl_plugin]] == The Kotlin DSL Plugin The Kotlin DSL Plugin provides a convenient way to develop Kotlin-based projects that contribute build logic. That includes <>, <> and <>. The plugin achieves this by doing the following: * Applies the link:https://kotlinlang.org/docs/reference/using-gradle.html#targeting-the-jvm[Kotlin Plugin], which adds support for compiling Kotlin source files. * Adds the `kotlin-stdlib-jdk8`, `kotlin-reflect` and `gradleKotlinDsl()` dependencies to the `compileOnly` and `testImplementation` configurations, which allows you to make use of those Kotlin libraries and the Gradle API in your Kotlin code. * Configures the Kotlin compiler with the same settings that are used for Kotlin DSL scripts, ensuring consistency between your build logic and those scripts. * Enables support for <>. [CAUTION] .Avoid specifying a version for the `kotlin-dsl` plugin ==== Each Gradle release is meant to be used with a specific version of the `kotlin-dsl` plugin and compatibility between arbitrary Gradle releases and `kotlin-dsl` plugin versions is not guaranteed. Using an unexpected version of the `kotlin-dsl` plugin in a build will emit a warning and can cause hard to diagnose problems. ==== This is the basic configuration you need to use the plugin: .Applying the Kotlin DSL Plugin to a `buildSrc` project ==== include::sample[dir=""snippets/kotlinDsl/kotlinDslPlugin/kotlin"",files=""buildSrc/build.gradle.kts[tags=apply]""] ==== [[sec:kotlin]] == The embedded Kotlin Gradle embeds Kotlin in order to provide support for Kotlin-based scripts. === Kotlin versions Gradle ships with `kotlin-compiler-embeddable` plus matching versions of `kotlin-stdlib` and `kotlin-reflect` libraries. For example, Gradle 4.3 ships with the Kotlin DSL v0.12.1 that includes Kotlin 1.1.51 versions of these modules. The `kotlin` package from those modules is visible through the Gradle classpath. The link:https://kotlinlang.org/docs/reference/compatibility.html[compatibility guarantees] provided by Kotlin apply for both backward and forward compatibility. ==== Backward compatibility Our approach is to only do backwards-breaking Kotlin upgrades on a major Gradle release. We will always clearly document which Kotlin version we ship and announce upgrade plans before a major release. Plugin authors who want to stay compatible with older Gradle versions need to limit their API usage to a subset that is compatible with these old versions. It’s not really different from any other new API in Gradle. E.g. if we introduce a new API for dependency resolution and a plugin wants to use that API, then they either need to drop support for older Gradle versions or they need to do some clever organization of their code to only execute the new code path on newer versions. ==== Forward compatibility The biggest issue is the compatibility between the external `kotlin-gradle-plugin` version and the `kotlin-stdlib` version shipped with Gradle. More generally, between any plugin that transitively depends on `kotlin-stdlib` and its version shipped with Gradle. As long as the combination is compatible everything should work. This will become less of an issue as the language matures. [[sec:kotlin_compiler_arguments]] === Kotlin compiler arguments These are the Kotlin compiler arguments used for compiling Kotlin DSL scripts and Kotlin sources and scripts in a project that has the `kotlin-dsl` plugin applied: `-jvm-target=1.8`:: Sets the target version of the generated JVM bytecode to `1.8`. `-Xjsr305=strict`:: Sets up Kotlin's Java interoperability to strictly follow JSR-305 annotations for increased null safety. See link:https://kotlinlang.org/docs/reference/java-interop.html#compiler-configuration[Calling Java code from Kotlin] in the Kotlin documentation for more information. [[sec:interoperability]] == Interoperability When mixing languages in your build logic, you may have to cross language boundaries. An extreme example would be a build that uses tasks and plugins that are implemented in Java, Groovy and Kotlin, while also using both Kotlin DSL and Groovy DSL build scripts. Quoting the Kotlin reference documentation: > Kotlin is designed with Java Interoperability in mind. Existing Java code can be called from Kotlin in a natural way, and Kotlin code can be used from Java rather smoothly as well. Both link:{kotlin-reference}java-interop.html[calling Java from Kotlin] and link:{kotlin-reference}java-to-kotlin-interop.html[calling Kotlin from Java] are very well covered in the Kotlin reference documentation. The same mostly applies to interoperability with Groovy code. In addition, the Kotlin DSL provides several ways to opt into Groovy semantics, which we look at next. === Static extensions Both the Groovy and Kotlin languages support extending existing classes via link:https://groovy-lang.org/metaprogramming.html#_extension_modules[Groovy Extension modules] and link:{kotlin-reference}extensions.html[Kotlin extensions]. To call a Kotlin extension function from Groovy, call it as a static function, passing the receiver as the first parameter: .Calling a Kotlin extension from Groovy ==== include::sample[dir=""snippets/kotlinDsl/interoperability-static-extensions/kotlin"",files=""build.gradle[tags=kotlin-from-groovy]""] ==== Kotlin extension functions are package-level functions and you can learn how to locate the name of the type declaring a given Kotlin extension in the link:{kotlin-reference}java-to-kotlin-interop.html#package-level-functions[Package-Level Functions] section of the Kotlin reference documentation. To call a Groovy extension method from Kotlin, the same approach applies: call it as a static function passing the receiver as the first parameter. Here's an example: .Calling a Groovy extension from Kotlin ==== include::sample[dir=""snippets/kotlinDsl/interoperability-static-extensions/kotlin"",files=""build.gradle.kts[tags=groovy-from-kotlin]""] ==== === Named parameters and default arguments Both the Groovy and Kotlin languages support named function parameters and default arguments, although they are implemented very differently. Kotlin has fully-fledged support for both, as described in the Kotlin language reference under link:{kotlin-reference}functions.html#named-arguments[named arguments] and link:{kotlin-reference}functions.html#default-arguments[default arguments]. Groovy implements link:https://groovy-lang.org/objectorientation.html#_named_arguments[named arguments] in a non-type-safe way based on a `Map` parameter, which means they cannot be combined with link:https://groovy-lang.org/objectorientation.html#_default_arguments[default arguments]. In other words, you can only use one or the other in Groovy for any given method. ==== Calling Kotlin from Groovy To call a Kotlin function that has named arguments from Groovy, just use a normal method call with positional parameters. There is no way to provide values by argument name. To call a Kotlin function that has default arguments from Groovy, always pass values for all the function parameters. ==== Calling Groovy from Kotlin To call a Groovy function with named arguments from Kotlin, you need to pass a `Map`, as shown in this example: .Call Groovy function with named arguments from Kotlin [.multi-language-sample] ==== .build.gradle.kts [source, kotlin] ---- groovyNamedArgumentTakingMethod(mapOf( ""parameterName"" to ""value"", ""other"" to 42, ""and"" to aReference)) ---- ==== To call a Groovy function with default arguments from Kotlin, always pass values for all the parameters. === Groovy closures from Kotlin You may sometimes have to call Groovy methods that take link:https://groovy-lang.org/closures.html[Closure] arguments from Kotlin code. For example, some third-party plugins written in Groovy expect closure arguments. [NOTE] ==== Gradle plugins written in any language should prefer the type `Action` type in place of closures. Groovy closures and Kotlin lambdas are automatically mapped to arguments of that type. ==== In order to provide a way to construct closures while preserving Kotlin's strong typing, two helper methods exist: * `closureOf {}` * `delegateClosureOf {}` Both methods are useful in different circumstances and depend upon the method you are passing the `Closure` instance into. Some plugins expect simple closures, as with the link:{plugin-portal}plugin/com.jfrog.bintray[Bintray] plugin: .Use `closureOf {}` ==== include::sample[dir=""snippets/kotlinDsl/interoperability-closure-of/kotlin"",files=""build.gradle.kts[tags=closureOf]""] ==== In other cases, like with the link:{plugin-portal}plugin/org.gretty[Gretty Plugin] when configuring farms, the plugin expects a delegate closure: .Use `delegateClosureOf {}` ==== include::sample[dir=""snippets/kotlinDsl/interoperability-delegate-closure-of/kotlin"",files=""build.gradle.kts[tags=delegateClosureOf]""] ==== There sometimes isn't a good way to tell, from looking at the source code, which version to use. Usually, if you get a `NullPointerException` with `closureOf {}`, using `delegateClosureOf {}` will resolve the problem. These two utility functions are useful for _configuration closures_, but some plugins might expect Groovy closures for other purposes. The `KotlinClosure0` to `KotlinClosure2` types allows adapting Kotlin functions to Groovy closures with more flexibility. .Use `KotlinClosureX` types ==== include::sample[dir=""snippets/kotlinDsl/interoperability-kotlinClosure/kotlin"",files=""build.gradle.kts[tags=kotlinClosure]""] ==== Also see the link:{kotlin-dsl-samples}groovy-interop[groovy-interop] sample. === The Kotlin DSL Groovy Builder If some plugin makes heavy use of link:https://groovy-lang.org/metaprogramming.html[Groovy metaprogramming], then using it from Kotlin or Java or any statically-compiled language can be very cumbersome. The Kotlin DSL provides a `withGroovyBuilder {}` utility extension that attaches the Groovy metaprogramming semantics to objects of type `Any`. The following example demonstrates several features of the method on the object `target`: .Use `withGroovyBuilder {}` ==== include::sample[dir=""snippets/kotlinDsl/interoperability-groovy-builder/kotlin"",files=""build.gradle.kts[tags=withGroovyBuilder]""] ==== <1> The receiver is a link:https://docs.groovy-lang.org/latest/html/api/groovy/lang/GroovyObject.html[GroovyObject] and provides Kotlin helpers <2> The `GroovyObject` API is available <3> Invoke the `methodName` method, passing some parameters <4> Configure the `blockName` property, maps to a `Closure` taking method invocation <5> Invoke `another` method taking named arguments, maps to a Groovy named arguments `Map` taking method invocation The link:{kotlin-dsl-samples}maven-plugin[maven-plugin] sample demonstrates the use of the `withGroovyBuilder()` utility extensions for configuring the `uploadArchives` task to <> with a custom POM using Gradle's core <>. Note that the recommended <> provides a type-safe and Kotlin-friendly DSL that allows you to easily do <> without resorting to `withGroovyBuilder()`. [[using_a_groovy_script]] === Using a Groovy script Another option when dealing with problematic plugins that assume a Groovy DSL build script is to configure them in a Groovy DSL build script that is applied from the main Kotlin DSL build script: .Using a Groovy script ==== [.multi-language-sample] ===== .build.gradle.kts [source, kotlin] ---- plugins { id(""dynamic-groovy-plugin"") version ""1.0"" <1> } apply(from = ""dynamic-groovy-plugin-configuration.gradle"") <2> ---- ===== ==== ==== [.multi-language-sample] ===== .dynamic-groovy-plugin-configuration.gradle [source, groovy] ---- native { <3> dynamic { groovy as Usual } } ---- ===== ==== <1> The Kotlin build script requests and applies the plugin <2> The Kotlin build script applies the Groovy script <3> The Groovy script uses dynamic Groovy to configure plugin [[kotdsl:limitations]] == Limitations * The Kotlin DSL is link:https://github.com/gradle/kotlin-dsl/issues/902[known to be slower than the Groovy DSL] on first use, for example with clean checkouts or on ephemeral continuous integration agents. Changing something in the _buildSrc_ directory also has an impact as it invalidates build-script caching. The main reason for this is the slower script compilation for Kotlin DSL. * In IntelliJ IDEA, you must link:https://www.jetbrains.com/help/idea/gradle.html#gradle_import[import your project from the Gradle model] in order to get content assist and refactoring support for your Kotlin DSL build scripts. * The Kotlin DSL will not support the `model {}` block, which is part of the link:https://blog.gradle.org/state-and-future-of-the-gradle-software-model[discontinued Gradle Software Model]. However, you _can_ apply model rules from scripts — see the link:{kotlin-dsl-samples}model-rules[model rules] sample for more information. * We recommend against enabling the incubating <> feature as it can lead to very hard-to-diagnose problems. If you run into trouble or discover a suspected bug, please report the issue in the link:{gradle-issues}[Gradle issue tracker]. ",12104,False,2091.6735705982196,median "[[netty-component]] = Netty Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-netty/src/main/docs/netty-component.adoc :docTitle: Netty :artifactId: camel-netty :description: Socket level networking using TCP or UDP with the Netty 4.x. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported *Since Camel {since}* *{component-header}* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 72 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *executorService* (consumer) | To use the given EventExecutorGroup. | | EventExecutorGroup | *maximumPoolSize* (consumer) | Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17. This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be affected. | | int | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. The value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *useGlobalSslContextParameters* (security) | Enable usage of global SSL context parameters. | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol:host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. The value can be one of: tcp, udp | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (71 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. The value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. The value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== [NOTE] ==== Read below about using non shareable encoders/decoders. ==== === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload Note that Object serialization is not allowed by default, and so a decoder must be configured. [source,java] ---- @BindToRegistry(""decoder"") public ChannelHandler getDecoder() throws Exception { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true&decoders=#decoder"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); // Process poetry in some way exchange.getOut().setBody(""Message received); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSL/TLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. [TIP] ==== The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. ==== === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. [NOTE] ==== Read further above about using non shareable encoders/decoders. ==== The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- [TIP] ==== For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. ==== Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. [NOTE] ==== We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. ==== You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. include::camel-spring-boot::page$netty-starter.adoc[] ",12368,False,2297.7197663836423,median "#include ""sif/bicyclecost.h"" #include ""sif/costconstants.h"" #include ""baldr/directededge.h"" #include ""baldr/nodeinfo.h"" #include ""midgard/constants.h"" #include ""baldr/accessrestriction.h"" #include ""midgard/util.h"" #ifdef INLINE_TEST #include ""test/test.h"" #include #include #endif using namespace valhalla::baldr; namespace valhalla { namespace sif { // Default options/values namespace { constexpr float kDefaultManeuverPenalty = 5.0f; // Seconds constexpr float kDefaultDrivewayPenalty = 300.0f; // Seconds constexpr float kDefaultAlleyPenalty = 60.0f; // Seconds constexpr float kDefaultGateCost = 30.0f; // Seconds constexpr float kDefaultGatePenalty = 300.0f; // Seconds constexpr float kDefaultFerryCost = 300.0f; // Seconds constexpr float kDefaultCountryCrossingCost = 600.0f; // Seconds constexpr float kDefaultCountryCrossingPenalty = 0.0f; // Seconds constexpr float kDefaultUseRoad = 0.5f; // Factor between 0 and 1 constexpr float kDefaultUseFerry = 0.5f; // Factor between 0 and 1 constexpr float kDefaultLowStressUseRoad = 0.0f; // Factor between 0 and 1 // Maximum ferry penalty (when use_ferry == 0). Can't make this too large // since a ferry is sometimes required to complete a route. constexpr float kMaxFerryPenalty = 8.0f * 3600.0f; // 8 hours // Default turn costs - modified by the stop impact. constexpr float kTCStraight = 0.15f; constexpr float kTCFavorableSlight = 0.2f; constexpr float kTCFavorable = 0.3f; constexpr float kTCFavorableSharp = 0.5f; constexpr float kTCCrossing = 0.75f; constexpr float kTCUnfavorableSlight = 0.4f; constexpr float kTCUnfavorable = 1.0f; constexpr float kTCUnfavorableSharp = 1.5f; constexpr float kTCReverse = 5.0f; // Turn costs based on side of street driving constexpr float kRightSideTurnCosts[] = { kTCStraight, kTCFavorableSlight, kTCFavorable, kTCFavorableSharp, kTCReverse, kTCUnfavorableSharp, kTCUnfavorable, kTCUnfavorableSlight }; constexpr float kLeftSideTurnCosts[] = { kTCStraight, kTCUnfavorableSlight, kTCUnfavorable, kTCUnfavorableSharp, kTCReverse, kTCFavorableSharp, kTCFavorable, kTCFavorableSlight }; // Turn stress penalties for low-stress bike. constexpr float kTPStraight = 0.0f; constexpr float kTPFavorableSlight = 0.25f; constexpr float kTPFavorable = 0.75f; constexpr float kTPFavorableSharp = 1.0f; constexpr float kTPUnfavorableSlight = 0.75f; constexpr float kTPUnfavorable = 1.75f; constexpr float kTPUnfavorableSharp = 2.25f; constexpr float kTPReverse = 4.0f; constexpr float kRightSideTurnPenalties[] = { kTPStraight, kTPFavorableSlight, kTPFavorable, kTPFavorableSharp, kTPReverse, kTPUnfavorableSharp, kTPUnfavorable, kTPUnfavorableSlight }; constexpr float kLeftSideTurnPenalties[] = { kTPStraight, kTPUnfavorableSlight, kTPUnfavorable, kTPUnfavorableSharp, kTPReverse, kTPFavorableSharp, kTPFavorable, kTPFavorableSlight }; // Cost of traversing an edge with steps. Make this high but not impassible. // Equal to about 5 minutes (penalty) const float kBicycleStepsFactor = 8.0f; // Default cycling speed on smooth, flat roads - based on bicycle type (KPH) constexpr float kDefaultCyclingSpeed[] = { 25.0f, // Road bicycle: ~15.5 MPH 20.0f, // Cross bicycle: ~13 MPH 18.0f, // Hybrid or ""city"" bicycle: ~11.5 MPH 16.0f // Mountain bicycle: ~10 MPH }; constexpr float kDismountSpeed = 5.1f; // Minimum and maximum average bicycling speed (to validate input). // Maximum is just above the fastest average speed in Tour de France time trial constexpr float kMinCyclingSpeed = 5.0f; // KPH constexpr float kMaxCyclingSpeed = 60.0f; // KPH // Speed factors based on surface types (defined for each bicycle type). // These values determine the percentage by which speed us reduced for // each surface type. (0 values indicate unusable surface types). constexpr float kRoadSurfaceSpeedFactors[] = { 1.0f, 1.0f, 0.9f, 0.6f, 0.0f, 0.0f, 0.0f, 0.0f }; constexpr float kHybridSurfaceSpeedFactors[] = { 1.0f, 1.0f, 1.0f, 0.8f, 0.5f, 0.0f, 0.0f, 0.0f }; constexpr float kCrossSurfaceSpeedFactors[] = { 1.0f, 1.0f, 1.0f, 0.8f, 0.7f, 0.5f, 0.0f, 0.0f }; constexpr float kMountainSurfaceSpeedFactors[] = { 1.0f, 1.0f, 1.0f, 1.0f, 0.9f, 0.8f, 0.7f, 0.0f }; // Worst allowed surface based on bicycle type constexpr Surface kWorstAllowedSurface[] = { Surface::kCompacted, // Road bicycle Surface::kGravel, // Cross Surface::kDirt, // Hybrid Surface::kPath }; // Mountain // Avoid driveways constexpr float kDrivewayFactor = 20.0f; // Additional penalty to avoid destination only constexpr float kDestinationOnlyFactor = 0.1f; // Weighting factor based on road class. These apply penalties to higher class // roads. These penalties are modulated by the useroads factor - further // avoiding higher class roads for those with low propensity for using roads. constexpr float kRoadClassFactor[] = { 1.0f, // Motorway 0.4f, // Trunk 0.2f, // Primary 0.1f, // Secondary 0.05f, // Tertiary 0.05f, // Unclassified 0.0f, // Residential 0.5f // Service, other }; // Speed adjustment factors based on weighted grade. Comments here show an // example of speed changes based on ""grade"", using a base speed of 18 MPH // on flat roads constexpr float kGradeBasedSpeedFactor[] = { 2.5f, // -10% - 45 2.25f, // -8% - 40.5 2.0f, // -6.5% - 36 1.7f, // -5% - 30.6 1.4f, // -3% - 25 1.2f, // -1.5% - 21.6 1.0f, // 0% - 18 0.95f, // 1.5% - 17 0.85f, // 3% - 15 0.75f, // 5% - 13.5 0.65f, // 6.5% - 12 0.55f, // 8% - 10 0.5f, // 10% - 9 0.45f, // 11.5% - 8 0.4f, // 13% - 7 0.3f // 15% - 5.5 }; // User propensity to use ""hilly"" roads. Ranges from a value of 0 (avoid // hills) to 1 (take hills when they offer a more direct, less time, path). constexpr float kDefaultUseHills = 0.5f; // Avoid hills ""strength"". How much do we want to avoid a hill. Combines // with the usehills factor (1.0 - usehills = avoidhills factor) to create // a weighting penalty per weighted grade factor. This indicates how strongly // edges with the specified grade are weighted. Note that speed also is // influenced by grade, so these weights help further avoid hills. constexpr float kAvoidHillsStrength[] = { 1.0f, // -10% - Treacherous descent possible 0.5f, // -8% - Steep downhill 0.1f, // -6.5% - Good downhill - where is the bottom? 0.05f, // -5% - Picking up speed! 0.025f, // -3% - Modest downhill 0.0f, // -1.5% - Smooth slight downhill, ride this all day! 0.05f, // 0% - Flat, no avoidance 0.1f, // 1.5% - These are called ""false flat"" 0.15f, // 3% - Slight rise 0.3f, // 5% - Small hill 0.6f, // 6.5% - Starting to feel this... 1.2f, // 8% - Moderately steep 2.5f, // 10% - Getting tough 5.0f, // 11.5% - Tiring! 7.5f, // 13% - Ooof - this hurts 10.0f // 15% - Only for the strongest! }; // Avoid hills ""strength"" specifically for low stress bicycle costing. constexpr float kLowStressAvoidHillsStrength[] = { 2.0f, // -10% - Treacherous descent possible 1.0f, // -8% - Steep downhill 0.5f, // -6.5% - Good downhill - where is the bottom? 0.2f, // -5% - Picking up speed! 0.1f, // -3% - Modest downhill 0.0f, // -1.5% - Smooth slight downhill, ride this all day! 0.05f, // 0% - Flat, no avoidance 0.1f, // 1.5% - These are called ""false flat"" 0.3f, // 3% - Slight rise 1.0f, // 5% - Small hill 2.5f, // 6.5% - Starting to feel this... 3.5f, // 8% - Moderately steep 5.0f, // 10% - Getting tough 6.5f, // 11.5% - Tiring! 10.0f, // 13% - Ooof - this hurts 12.0f // 15% - Only for the strongest! }; // Edge speed above which extra penalties apply (to avoid roads with higher // speed traffic). This threshold is adjusted upwards with higher useroads // factors. constexpr uint32_t kSpeedPenaltyThreshold = 40; // 40 KPH ~ 25 MPH // How much to favor bicycle networks. constexpr float kBicycleNetworkFactor = 1.0f; // Maximum amount of seconds that will be allowed to be passed in to influence paths // This can't be too high because sometimes a certain kind of path is required to be taken constexpr float kMaxSeconds = 12.0f * kSecPerHour; // 12 hours // Valid ranges and defaults constexpr ranged_default_t kManeuverPenaltyRange{0.0f, kDefaultManeuverPenalty, kMaxSeconds}; constexpr ranged_default_t kDrivewayPenaltyRange{0.0f, kDefaultDrivewayPenalty, kMaxSeconds}; constexpr ranged_default_t kAlleyPenaltyRange{0.0f, kDefaultAlleyPenalty, kMaxSeconds}; constexpr ranged_default_t kGateCostRange{0.0f, kDefaultGateCost, kMaxSeconds}; constexpr ranged_default_t kGatePenaltyRange{0.0f, kDefaultGatePenalty, kMaxSeconds}; constexpr ranged_default_t kFerryCostRange{0.0f, kDefaultFerryCost, kMaxSeconds}; constexpr ranged_default_t kCountryCrossingCostRange{0.0f, kDefaultCountryCrossingCost, kMaxSeconds}; constexpr ranged_default_t kCountryCrossingPenaltyRange{0.0f, kDefaultCountryCrossingPenalty, kMaxSeconds}; constexpr ranged_default_t kUseRoadRange{0.0f, kDefaultUseRoad, 1.0f}; constexpr ranged_default_t kUseFerryRange{0.0f, kDefaultUseFerry, 1.0f}; constexpr ranged_default_t kUseHillsRange{0.0f, kDefaultUseHills, 1.0f}; constexpr ranged_default_t kLowStressUseRoadRange{0.0f, kDefaultLowStressUseRoad, 1.0f}; } /** * Derived class providing dynamic edge costing for bicycle routes. */ class BicycleCost : public DynamicCost { public: /** * Constructor. Configuration / options for bicycle costing are provided * via a property tree. * @param config Property tree with configuration/options. */ BicycleCost(const boost::property_tree::ptree& config); virtual ~BicycleCost(); /** * Get the access mode used by this costing method. * @return Returns access mode. */ uint32_t access_mode() const; /** * Checks if access is allowed for the provided directed edge. * This is generally based on mode of travel and the access modes * allowed on the edge. However, it can be extended to exclude access * based on other parameters. * @param edge Pointer to a directed edge. * @param pred Predecessor edge information. * @param tile current tile * @param edgeid edgeid that we care about * @return Returns true if access is allowed, false if not. */ virtual bool Allowed(const baldr::DirectedEdge* edge, const EdgeLabel& pred, const baldr::GraphTile*& tile, const baldr::GraphId& edgeid) const; /** * Checks if access is allowed for an edge on the reverse path * (from destination towards origin). Both opposing edges are * provided. * @param edge Pointer to a directed edge. * @param pred Predecessor edge information. * @param opp_edge Pointer to the opposing directed edge. * @param tile Tile for the opposing edge (for looking * up restrictions). * @param opp_edgeid Opposing edge Id * @return Returns true if access is allowed, false if not. */ virtual bool AllowedReverse(const baldr::DirectedEdge* edge, const EdgeLabel& pred, const baldr::DirectedEdge* opp_edge, const baldr::GraphTile*& tile, const baldr::GraphId& opp_edgeid) const; /** * Checks if access is allowed for the provided node. Node access can * be restricted if bollards or gates are present. (TODO - others?) * @param edge Pointer to node information. * @return Returns true if access is allowed, false if not. */ virtual bool Allowed(const baldr::NodeInfo* node) const; /** * Get the cost to traverse the specified directed edge. Cost includes * the time (seconds) to traverse the edge. * @param edge Pointer to a directed edge. * @return Returns the cost and time (seconds) */ virtual Cost EdgeCost(const baldr::DirectedEdge* edge) const; /** * Returns the cost to make the transition from the predecessor edge. * Defaults to 0. Costing models that wish to include edge transition * costs (i.e., intersection/turn costs) must override this method. * @param edge Directed edge (the to edge) * @param node Node (intersection) where transition occurs. * @param pred Predecessor edge information. * @return Returns the cost and time (seconds) */ virtual Cost TransitionCost(const baldr::DirectedEdge* edge, const baldr::NodeInfo* node, const EdgeLabel& pred) const; /** * Returns the cost to make the transition from the predecessor edge * when using a reverse search (from destination towards the origin). * @param idx Directed edge local index * @param node Node (intersection) where transition occurs. * @param pred the opposing current edge in the reverse tree. * @param edge the opposing predecessor in the reverse tree * @return Returns the cost and time (seconds) */ virtual Cost TransitionCostReverse(const uint32_t idx, const baldr::NodeInfo* node, const baldr::DirectedEdge* pred, const baldr::DirectedEdge* edge) const; /** * Get the cost factor for A* heuristics. This factor is multiplied * with the distance to the destination to produce an estimate of the * minimum cost to the destination. The A* heuristic must underestimate the * cost to the destination. So a time based estimate based on speed should * assume the maximum speed is used to the destination such that the time * estimate is less than the least possible time along roads. */ virtual float AStarCostFactor() const; /** * Get the current travel type. * @return Returns the current travel type. */ virtual uint8_t travel_type() const; // Hidden in source file so we don't need it to be protected // We expose it within the source file for testing purposes public: float speedfactor_[kMaxSpeedKph + 1]; // Cost factors based on speed in kph float density_factor_[16]; // Density factor float maneuver_penalty_; // Penalty (seconds) when inconsistent names float driveway_penalty_; // Penalty (seconds) using a driveway float gate_cost_; // Cost (seconds) to go through gate float gate_penalty_; // Penalty (seconds) to go through gate float alley_penalty_; // Penalty (seconds) to use a alley float ferry_cost_; // Cost (seconds) to exit a ferry float ferry_penalty_; // Penalty (seconds) to enter a ferry float ferry_factor_; // Weighting to apply to ferry edges float country_crossing_cost_; // Cost (seconds) to go through toll booth float country_crossing_penalty_; // Penalty (seconds) to go across a country border float use_roads_; // Preference of using roads between 0 and 1 float road_factor_; // Road factor based on use_roads_ float use_ferry_; // Preference of using ferries between 0 and 1 float use_hills_; // Preference of using hills between 0 and 1 // Density factor used in edge transition costing std::vector trans_density_factor_; // Average speed (kph) on smooth, flat roads. float speed_; // Bicycle type BicycleType type_; // Minimal surface type usable by the bicycle type Surface minimal_allowed_surface_; // Surface speed factors (based on road surface type). const float* surface_speed_factor_; // Speed penalty factor. Penalties apply above a threshold // (based on the use_roads factor) float speedpenalty_[kMaxSpeedKph + 1]; uint32_t speed_penalty_threshold_; // Elevation/grade penalty (weighting applied based on the edge's weighted // grade (relative value from 0-15) float grade_penalty[16]; /** * Returns a function/functor to be used in location searching which will * exclude and allow ranking results from the search by looking at each * edges attribution and suitability for use as a location by the travel * mode used by the costing method. Function/functor is also used to filter * edges not usable / inaccessible by bicycle. */ virtual const EdgeFilter GetEdgeFilter() const { // Throw back a lambda that checks the access for this type of costing uint32_t b = static_cast(type_); return [b](const baldr::DirectedEdge* edge) { if ( edge->IsTransition() || edge->is_shortcut() || !(edge->forwardaccess() & kBicycleAccess) || edge->use() == Use::kSteps || edge->surface() > kWorstAllowedSurface[b]) { return 0.0f; } else { // TODO - use classification/use to alter the factor return 1.0f; } }; } /** * Returns a function/functor to be used in location searching which will * exclude results from the search by looking at each node's attribution * @return Function to be used in filtering out nodes */ virtual const NodeFilter GetNodeFilter() const { //throw back a lambda that checks the access for this type of costing return [](const baldr::NodeInfo* node) { return !(node->access() & kBicycleAccess); }; } }; // Bicycle route costs are distance based with some favor/avoid based on // attribution. // Constructor BicycleCost::BicycleCost(const boost::property_tree::ptree& pt) : DynamicCost(pt, TravelMode::kBicycle), trans_density_factor_{ 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.05f, 1.1f, 1.15f, 1.2f, 1.25f, 1.3f, 1.4f, 1.5f } { // Set hierarchy to allow unlimited transitions for (auto& h : hierarchy_limits_) { h.max_up_transitions = kUnlimitedTransitions; } // Transition penalties (similar to auto) maneuver_penalty_ = kManeuverPenaltyRange( pt.get(""maneuver_penalty"", kDefaultManeuverPenalty) ); driveway_penalty_ = kDrivewayPenaltyRange( pt.get(""driveway"", kDefaultDrivewayPenalty) ); gate_cost_ = kGateCostRange( pt.get(""gate_cost"", kDefaultGateCost) ); gate_penalty_ = kGatePenaltyRange( pt.get(""gate_penalty"", kDefaultGatePenalty) ); alley_penalty_ = kAlleyPenaltyRange( pt.get(""alley_penalty"", kDefaultAlleyPenalty) ); country_crossing_cost_ = kCountryCrossingCostRange( pt.get(""country_crossing_cost"", kDefaultCountryCrossingCost) ); country_crossing_penalty_ = kCountryCrossingPenaltyRange( pt.get(""country_crossing_penalty"", kDefaultCountryCrossingPenalty) ); // Get the bicycle type - enter as string and convert to enum std::string bicycle_type = pt.get(""bicycle_type"", ""Road""); if (bicycle_type == ""Cross"") { type_ = BicycleType::kCross; } else if (bicycle_type == ""Hybrid"" || bicycle_type == ""City"") { type_ = BicycleType::kHybrid; } else if (bicycle_type == ""Mountain"") { type_ = BicycleType::kMountain; } else { type_ = BicycleType::kRoad; } // Get default speed from the config. This is the average speed on smooth, // flat roads. If not present or outside the valid range use a default speed // based on the bicycle type. uint32_t t = static_cast(type_); ranged_default_t kCycleSpeedRange { kMinCyclingSpeed, kDefaultCyclingSpeed[t], kMaxCyclingSpeed }; speed_ = kCycleSpeedRange( pt.get(""cycling_speed"", kDefaultCyclingSpeed[t]) ); // Set the minimal surface type usable by the bicycle type and the // surface speed factors. if (type_ == BicycleType::kRoad) { // Heavily penalize driveways minimal_allowed_surface_ = Surface::kCompacted; surface_speed_factor_ = kRoadSurfaceSpeedFactors; } else if (type_ == BicycleType::kHybrid) { minimal_allowed_surface_ = Surface::kDirt; surface_speed_factor_ = kHybridSurfaceSpeedFactors; } else if (type_ == BicycleType::kCross) { minimal_allowed_surface_ = Surface::kGravel; surface_speed_factor_ = kCrossSurfaceSpeedFactors; } else { // Mountain - allow all but impassable minimal_allowed_surface_ = Surface::kPath; surface_speed_factor_ = kMountainSurfaceSpeedFactors; } // Willingness to use roads. Make sure this is within range [0, 1]. use_roads_ = kUseRoadRange( pt.get(""use_roads"", kDefaultUseRoad) ); // Set the road classification factor. use_roads factors above 0.5 start to // reduce the weight difference between road classes while factors below 0.5 // start to increase the differences. road_factor_ = (use_roads_ >= 0.5f) ? 1.5f - use_roads_ : 5.0f - use_roads_ * 8.0f; // Set the cost (seconds) to enter a ferry (only apply entering since // a route must exit a ferry (except artificial test routes ending on // a ferry!) ferry_cost_ = kFerryCostRange( pt.get(""ferry_cost"", kDefaultFerryCost) ); // Modify ferry penalty and edge weighting based on use_ferry_ factor use_ferry_ = kUseFerryRange( pt.get(""use_ferry"", 0.5f) ); if (use_ferry_ < 0.5f) { // Penalty goes from max at use_ferry_ = 0 to 0 at use_ferry_ = 0.5 ferry_penalty_ = static_cast(kMaxFerryPenalty * (1.0f - use_ferry_ * 2.0f)); // Cost X10 at use_ferry_ == 0, slopes downwards towards 1.0 at use_ferry_ = 0.5 ferry_factor_ = 10.0f - use_ferry_ * 18.0f; } else { // Add a ferry weighting factor to influence cost along ferries to make // them more favorable if desired rather than driving. No ferry penalty. // Half the cost at use_ferry_ == 1, progress to 1.0 at use_ferry_ = 0.5 ferry_penalty_ = 0.0f; ferry_factor_ = 1.5f - use_ferry_; } // Set the speed penalty threshold and factor. With useroads = 1 the // threshold is 70 kph (near 50 MPH). speed_penalty_threshold_ = kSpeedPenaltyThreshold + static_cast(use_roads_ * 30.0f); // Create speed cost table and penalty table (to avoid division in costing) speedfactor_[0] = kSecPerHour; for (uint32_t s = 1; s <= kMaxSpeedKph; s++) { speedfactor_[s] = (kSecPerHour * 0.001f) / static_cast(s); speedpenalty_[s] = (s <= speed_penalty_threshold_) ? 1.0f : powf(static_cast(s) / static_cast(speed_penalty_threshold_), 0.25); } // Populate the grade penalties (based on use_hills factor). use_hills_ = kUseHillsRange( pt.get(""use_hills"", kDefaultUseHills) ); float avoidhills = (1.0f - use_hills_); for (uint32_t i = 0; i <= kMaxGradeFactor; i++) { grade_penalty[i] = 1.0f + avoidhills * kAvoidHillsStrength[i]; } } // Destructor BicycleCost::~BicycleCost() { } // Get the access mode used by this costing method. uint32_t BicycleCost::access_mode() const { return kBicycleAccess; } // Check if access is allowed on the specified edge. bool BicycleCost::Allowed(const baldr::DirectedEdge* edge, const EdgeLabel& pred, const baldr::GraphTile*& tile, const baldr::GraphId& edgeid) const { // TODO - obtain and check the access restrictions. // Check bicycle access and turn restrictions. Bicycles should obey // vehicular turn restrictions. Allow Uturns at dead ends only. // Skip impassable edges and shortcut edges. if (!(edge->forwardaccess() & kBicycleAccess) || edge->is_shortcut() || (!pred.deadend() && pred.opp_local_idx() == edge->localedgeidx()) || (pred.restrictions() & (1 << edge->localedgeidx())) || IsUserAvoidEdge(edgeid)) { return false; } // Disallow transit connections // (except when set for multi-modal routes (FUTURE) if (edge->use() == Use::kTransitConnection || edge->use() == Use::kEgressConnection || edge->use() == Use::kPlatformConnection /* && !allow_transit_connections_*/) { return false; } // Prohibit certain roads based on surface type and bicycle type return edge->surface() <= minimal_allowed_surface_; } // Checks if access is allowed for an edge on the reverse path (from // destination towards origin). Both opposing edges are provided. bool BicycleCost::AllowedReverse(const baldr::DirectedEdge* edge, const EdgeLabel& pred, const baldr::DirectedEdge* opp_edge, const baldr::GraphTile*& tile, const baldr::GraphId& opp_edgeid) const { // TODO - obtain and check the access restrictions. // Check access, U-turn (allow at dead-ends), and simple turn restriction. // Do not allow transit connection edges. if (!(opp_edge->forwardaccess() & kBicycleAccess) || opp_edge->is_shortcut() || opp_edge->use() == Use::kTransitConnection || opp_edge->use() == Use::kEgressConnection || opp_edge->use() == Use::kPlatformConnection || (!pred.deadend() && pred.opp_local_idx() == edge->localedgeidx()) || (opp_edge->restrictions() & (1 << pred.opp_local_idx())) || IsUserAvoidEdge(opp_edgeid)) { return false; } // Prohibit certain roads based on surface type and bicycle type return opp_edge->surface() <= minimal_allowed_surface_; } // Check if access is allowed at the specified node. bool BicycleCost::Allowed(const baldr::NodeInfo* node) const { return (node->access() & kBicycleAccess); } // Returns the cost to traverse the edge and an estimate of the actual time // (in seconds) to traverse the edge. // TODO: Make this (and TransitionCost) more similar to low-stress bicycle cost Cost BicycleCost::EdgeCost(const baldr::DirectedEdge* edge) const { // Stairs/steps - use a high fixed cost so they are generally avoided. if (edge->use() == Use::kSteps) { float sec = (edge->length() * speedfactor_[1]); return {sec * kBicycleStepsFactor, sec }; } // Ferries are a special case - they use the ferry speed (stored on the edge) if (edge->use() == Use::kFerry) { // Compute elapsed time based on speed. Modulate cost with weighting factors. float sec = (edge->length() * speedfactor_[edge->speed()]); return { sec * ferry_factor_, sec }; } // If you have to dismount on the edge then we set speed to an average walking speed // Otherwise, Update speed based on surface factor. Lower speed for rougher surfaces // depending on the bicycle type. Modulate speed based on weighted grade // (relative measure of elevation change along the edge) uint32_t bike_speed = edge->dismount () ? kDismountSpeed : static_cast((speed_ * surface_speed_factor_[static_cast(edge->surface())] * kGradeBasedSpeedFactor[edge->weighted_grade()]) + 0.5f); // Apply a weighting factor to the cost based on desirability of cycling // on this edge. Based on several factors: rider propensity to ride on roads, // road classification and use type of road, presence of bike lanes, // does the road belong to a bike network, and the hilliness/elevation change // (based on an avoid hills factor). float factor = 1.0f; // Special use cases: cycleway, footway, and path uint32_t road_speed = static_cast(edge->speed() + 0.5f); if (edge->use() == Use::kCycleway || edge->use() == Use::kFootway || edge->use() == Use::kPath) { // Differentiate how segregated the way is from pedestrians if (edge->cyclelane() == CycleLane::kSeparated) { // No pedestrians allowed on path factor = 0.5f; } else if (edge->cyclelane() == CycleLane::kDedicated) { // Segregated lane from pedestrians factor = 0.6f; } else { // Share path with pedestrians factor = 0.75f; } factor += use_roads_ * 0.5f; } else if (edge->use() == Use::kMountainBike && type_ == BicycleType::kMountain) { factor = 0.5f; } else if (edge->use() == Use::kLivingStreet) { factor = 0.6f; } else if (edge->use() == Use::kTrack) { factor = 0.8f; } else if (edge->use() == Use::kDriveway) { // Heavily penalize driveways factor = kDrivewayFactor; } else { // Favor roads where a cycle lane exists - if the lane is not separated // apply the speed penalty if (edge->cyclelane() == CycleLane::kShared) { factor = 0.9f * speedpenalty_[road_speed]; } else if (edge->cyclelane() == CycleLane::kDedicated) { factor = 0.8f * speedpenalty_[road_speed]; } else if (edge->cyclelane() == CycleLane::kSeparated) { factor *= 0.7f; } else if (edge->shoulder()) { factor = 0.85f * speedpenalty_[road_speed]; } else { // On a road without a bicycle lane. Set factor to include any speed // penalty and road class factor factor = speedpenalty_[road_speed] + (road_factor_ * kRoadClassFactor[static_cast(edge->classification())]); // Slight penalty going though destination only areas if no bike lanes if (edge->destonly()) { factor += kDestinationOnlyFactor; } } // We want to try and avoid roads that specify to use a cycling path to the side if (edge->use_sidepath()) { factor += 1.0f; } // Favor bicycle networks. // TODO - do we need to differentiate between types of network? if (edge->bike_network() > 0) { factor *= kBicycleNetworkFactor; } } // Update factor based on penalties applied for weighted_grade factor *= grade_penalty[edge->weighted_grade()]; // Compute elapsed time based on speed. Modulate cost with weighting factors. float sec = (edge->length() * speedfactor_[bike_speed]); return { sec * factor, sec }; } // Returns the time (in seconds) to make the transition from the predecessor Cost BicycleCost::TransitionCost(const baldr::DirectedEdge* edge, const baldr::NodeInfo* node, const EdgeLabel& pred) const { // Accumulate cost and penalty float seconds = 0.0f; float penalty = 0.0f; // Special cases with both time and penalty: country crossing, // gate, toll booth if (node->type() == NodeType::kBorderControl) { seconds += country_crossing_cost_; penalty += country_crossing_penalty_; } else if (node->type() == NodeType::kGate) { seconds += gate_cost_; penalty += gate_penalty_; } // Additional penalties without any time cost uint32_t idx = pred.opp_local_idx(); if (pred.use() != Use::kAlley && edge->use() == Use::kAlley) { penalty += alley_penalty_; } if (pred.use() != Use::kDriveway && edge->use() == Use::kDriveway) { penalty += driveway_penalty_; } if ((pred.use() != Use::kFerry && edge->use() == Use::kFerry)) { seconds += ferry_cost_; penalty += ferry_penalty_; } // Ignore name inconsistency when entering a link to avoid double penalizing. if (!edge->link() && !node->name_consistency(idx, edge->localedgeidx())) { // Slight maneuver penalty penalty += maneuver_penalty_; } // Penalize transition to higher class road. // TODO - modulate based on useroads factor? if (edge->classification() < pred.classification()) { penalty += 10.0f * (static_cast(pred.classification()) - static_cast(edge->classification())); } // Transition time = densityfactor * stopimpact * turncost if (edge->stopimpact(idx) > 0) { // Take the higher of the turn degree cost and the crossing cost float turn_cost = (edge->drive_on_right()) ? kRightSideTurnCosts[static_cast(edge->turntype(idx))] : kLeftSideTurnCosts[static_cast(edge->turntype(idx))]; if (turn_cost < kTCCrossing && edge->edge_to_right(idx) && edge->edge_to_left(idx)) { turn_cost = kTCCrossing; } seconds += trans_density_factor_[node->density()] * edge->stopimpact(idx) * turn_cost; } // Return cost (time and penalty) return { seconds + penalty, seconds }; } // Returns the cost to make the transition from the predecessor edge // when using a reverse search (from destination towards the origin). // pred is the opposing current edge in the reverse tree // edge is the opposing predecessor in the reverse tree Cost BicycleCost::TransitionCostReverse(const uint32_t idx, const baldr::NodeInfo* node, const baldr::DirectedEdge* pred, const baldr::DirectedEdge* edge) const { // Accumulate cost and penalty float seconds = 0.0f; float penalty = 0.0f; // Special cases with both time and penalty: country crossing, // gate, toll booth if (node->type() == NodeType::kBorderControl) { seconds += country_crossing_cost_; penalty += country_crossing_penalty_; } else if (node->type() == NodeType::kGate) { seconds += gate_cost_; penalty += gate_penalty_; } // Additional penalties without any time cost if (pred->use() != Use::kAlley && edge->use() == Use::kAlley) { penalty += alley_penalty_; } if (pred->use() != Use::kDriveway && edge->use() == Use::kDriveway) { penalty += driveway_penalty_; } if (pred->use() != Use::kFerry && edge->use() == Use::kFerry) { seconds += ferry_cost_; penalty += ferry_penalty_; } // Ignore name inconsistency when entering a link to avoid double penalizing. if (!edge->link() && !node->name_consistency(idx, edge->localedgeidx())) { // Slight maneuver penalty penalty += maneuver_penalty_; } // Penalize transition to higher class road. // TODO - modulate based on useroads factor? if (edge->classification() < pred->classification()) { penalty += 10.0f * (static_cast(pred->classification()) - static_cast(edge->classification())); } // Transition time = densityfactor * stopimpact * turncost if (edge->stopimpact(idx) > 0) { // Take the higher of the turn degree cost and the crossing cost float turn_cost = (edge->drive_on_right()) ? kRightSideTurnCosts[static_cast(edge->turntype(idx))] : kLeftSideTurnCosts[static_cast(edge->turntype(idx))]; if (turn_cost < kTCCrossing && edge->edge_to_right(idx) && edge->edge_to_left(idx)) { turn_cost = kTCCrossing; } seconds += trans_density_factor_[node->density()] * edge->stopimpact(idx) * turn_cost; } // Return cost (time and penalty) return { seconds + penalty, seconds }; } /** * Get the cost factor for A* heuristics. This factor is multiplied * with the distance to the destination to produce an estimate of the * minimum cost to the destination. The A* heuristic must underestimate the * cost to the destination. So a time based estimate based on speed should * assume the maximum speed is used to the destination such that the time * estimate is less than the least possible time along roads. */ float BicycleCost::AStarCostFactor() const { // Assume max speed of 80 kph (50 MPH) return speedfactor_[80]; } // Returns the current travel type. uint8_t BicycleCost::travel_type() const { return static_cast(type_); } cost_ptr_t CreateBicycleCost(const boost::property_tree::ptree& config) { return std::make_shared(config); } //////////////////////////////////////////////////////////////////////////// class LowStressBicycleCost : public BicycleCost { public: /** * Construct low stress costing. * Pass in configuration using property tree * @param config property tree with configuration/options */ LowStressBicycleCost(const boost::property_tree::ptree& config); virtual ~LowStressBicycleCost(); /** * Get the cost to traverse the specified directed edge. Cost includes * the time (seconds) to traverse the edge. * @param edge Pointer to a directed edge. * @return Returns the cost and time (seconds) */ virtual Cost EdgeCost(const baldr::DirectedEdge* edge) const; /** * Returns the cost to make the transition from the predecessor edge. * Defaults to 0. Costing models that wish to include edge transition * costs (i.e., intersection/turn costs) must override this method. * @param edge Directed edge (the to edge) * @param node Node (intersection) where transition occurs. * @param pred Predecessor edge information. * @return Returns the cost and time (seconds) */ virtual Cost TransitionCost(const baldr::DirectedEdge* edge, const baldr::NodeInfo* node, const EdgeLabel& pred) const; /** * Returns the cost to make the transition from the predecessor edge * when using a reverse search (from destination towards the origin). * @param idx Directed edge local index * @param node Node (intersection) where transition occurs. * @param pred the opposing current edge in the reverse tree. * @param edge the opposing predecessor in the reverse tree * @return Returns the cost and time (seconds) */ virtual Cost TransitionCostReverse(const uint32_t idx, const baldr::NodeInfo* node, const baldr::DirectedEdge* pred, const baldr::DirectedEdge* edge) const; }; LowStressBicycleCost::LowStressBicycleCost(const boost::property_tree::ptree& config) : BicycleCost(config) { // Overwrite use_roads_ to default to 0 use_roads_ = kLowStressUseRoadRange( config.get(""use_roads"", kDefaultLowStressUseRoad) ); uint32_t s = 1; // Low speed roads should be more favored than standard bike for ( ; s <= 40; s++) { // Linearly increases to a factor of 1.0 at 40 kmh (~25 mph) speedpenalty_[s] = static_cast(s) / 40.0f; } // Mid speed roads should be slightly more penalized than standard bike. for ( ; s <= 65; s++) { // Linearly increases to a factor of 2.0 at 65 kmh (~40 mph) speedpenalty_[s] = (static_cast(s) / 25.0f) - 0.6f; } // High speed roads should be much more penalized than standard bike. for ( ; s <= kMaxSpeedKph; s++) { // Linearly increases to a factor of 2.5 at 90 kmh (~56 mph) and continues until max. speedpenalty_[s] = (static_cast(s) / 50.0) + 0.7f; } // Populate the grade penalties (based on use_hills factor). float avoidhills = (1.0f - use_hills_); for (uint32_t i = 0; i <= kMaxGradeFactor; i++) { // Use the specialized low stress AvoidHillsStrength array. grade_penalty[i] = kLowStressAvoidHillsStrength[i]; // avoid hills 0.0 - 0.5 linearly increases from 0.25 to 1.0 // avoid hills 0.5 - 1.0 linearly increases from 1.0 to 1.5 // That way we will always somewhat avoid hills even if there seems to be preference for them. grade_penalty[i] *= (avoidhills > 0.5) ? avoidhills + 0.5f : avoidhills * 1.5f + 0.25; } } LowStressBicycleCost::~LowStressBicycleCost() { } // Returns the cost to traverse the edge and an estimate of the actual time // (in seconds) to traverse the edge. Cost LowStressBicycleCost::EdgeCost(const baldr::DirectedEdge* edge) const { // Stairs/steps - use a high fixed cost so they are generally avoided. if (edge->use() == Use::kSteps) { float sec = (edge->length() * speedfactor_[1]); return {sec * kBicycleStepsFactor, sec }; } // Ferries are a special case - they use the ferry speed (stored on the edge) if (edge->use() == Use::kFerry) { // Compute elapsed time based on speed. Modulate cost with weighting factors. float sec = (edge->length() * speedfactor_[edge->speed()]); return { sec * ferry_factor_, sec }; } // If you have to dismount on the edge then we set speed to an average walking speed // Otherwise, Update speed based on surface factor. Lower speed for rougher surfaces // depending on the bicycle type. Modulate speed based on weighted grade // (relative measure of elevation change along the edge) uint32_t bike_speed = edge->dismount () ? kDismountSpeed : static_cast((speed_ * surface_speed_factor_[static_cast(edge->surface())] * kGradeBasedSpeedFactor[edge->weighted_grade()]) + 0.5f); // Represents how stressful a roadway is without looking at grade or cycle accomodations float roadway_stress = 1.0f; // Represents the amount of accomodation is being made. Should be between 0.0 and 1.0 at // all times because it is a stress REDUCTION float accommodation_factor = 1.0f; // Special use cases: cycleway, footway, and path uint32_t road_speed = static_cast(edge->speed() + 0.5f); if (edge->use() == Use::kCycleway || edge->use() == Use::kFootway || edge->use() == Use::kPath) { // Differentiate how segregated the way is from pedestrians if (edge->cyclelane() == CycleLane::kSeparated) { // No pedestrians allowed on path accommodation_factor = use_roads_ * 0.125f; } else if (edge->cyclelane() == CycleLane::kDedicated) { // Segregated lane from pedestrians accommodation_factor = use_roads_ * 0.15f + 0.05f; } else { // Share path with pedestrians accommodation_factor = use_roads_ * 0.25f + 0.05f; } } else if (edge->use() == Use::kMountainBike && type_ == BicycleType::kMountain) { // Slightly less reduction than a footway or path because even with a mountain bike // these paths can be a little stressful to ride. No traffic though so still favorable accommodation_factor = use_roads_ * 0.25f + 0.1f; } else if(edge->use() == Use::kLivingStreet) { roadway_stress = 0.25f; } else if (edge->use() == Use::kTrack) { roadway_stress = 0.5f; } else if (edge->use() == Use::kDriveway) { // Heavily penalize driveways roadway_stress = kDrivewayFactor; } else { if (edge->cyclelane() == CycleLane::kShared) { accommodation_factor = 0.9f; } else if (edge->cyclelane() == CycleLane::kDedicated) { accommodation_factor = 0.5f; } else if (edge->cyclelane() == CycleLane::kSeparated) { accommodation_factor = 0.25f; } else if (edge->shoulder()) { accommodation_factor = 0.7f; } else if (edge->destonly()) { // Slight penalty going though destination only areas if no bike lanes roadway_stress += kDestinationOnlyFactor; } // Penalize roads that have more than one lane (in the direction of travel) // TODO: Maybe consider not penalizing lane count if in a separated (or even dedicated) lane if (edge->lanecount() > 1) { roadway_stress += (static_cast(edge->lanecount()) - 1) * 0.1f; } // Add in penalization for road classification roadway_stress += road_factor_ * kRoadClassFactor[static_cast(edge->classification())]; // Then multiply by speed so that higher classified roads are more severely punished for being fast. roadway_stress *= speedpenalty_[road_speed]; } // We want to try and avoid roads that specify to use a cycling path to the side if (edge->use_sidepath()) { accommodation_factor += 1.0f; } // Favor bicycle networks very slightly. // TODO - do we need to differentiate between types of network? if (edge->bike_network() > 0) { accommodation_factor *= 0.95f; } // The stress of this road after accommodation but before grade float total_stress = accommodation_factor * roadway_stress; // Create a final edge factor based on total stress and the weighted grade penalty for the edge. float factor = 1.0f + grade_penalty[edge->weighted_grade()] + total_stress; // Compute elapsed time based on speed. Modulate cost with weighting factors. float sec = (edge->length() * speedfactor_[bike_speed]); return { sec * factor, sec }; } // Returns the time (in seconds) to make the transition from the predecessor Cost LowStressBicycleCost::TransitionCost(const baldr::DirectedEdge* edge, const baldr::NodeInfo* node, const EdgeLabel& pred) const { // Accumulate cost and penalty float seconds = 0.0f; float penalty = 0.0f; // Special cases with both time and penalty: country crossing, // gate, toll booth if (node->type() == NodeType::kBorderControl) { seconds += country_crossing_cost_; penalty += country_crossing_penalty_; } else if (node->type() == NodeType::kGate) { seconds += gate_cost_; penalty += gate_penalty_; } // Additional penalties without any time cost uint32_t idx = pred.opp_local_idx(); if (pred.use() != Use::kAlley && edge->use() == Use::kAlley) { penalty += alley_penalty_; } if (pred.use() != Use::kDriveway && edge->use() == Use::kDriveway) { penalty += driveway_penalty_; } if ((pred.use() != Use::kFerry && edge->use() == Use::kFerry)) { seconds += ferry_cost_; penalty += ferry_penalty_; } // Ignore name inconsistency when entering a link to avoid double penalizing. if (!edge->link() && !node->name_consistency(idx, edge->localedgeidx())) { // Slight maneuver penalty penalty += maneuver_penalty_; } // Reduce the turn stress if there is a traffic signal // TODO - Put this and other complex considerations like lane count into the stop impact code float turn_stress = (node->traffic_signal()) ? 0.4 : 1.0; // Reduce the cost to make this turn if the road we are turning on to has some kind // of bicycle accommodation // TODO - Determine if this is needed or tweak/add to it float class_factor = 1.0f; if (edge->use() == Use::kCycleway) { class_factor = 0.05f; } else if (edge->use() == Use::kPedestrian || edge->use() == Use::kPath) { class_factor = 0.1f; } else { if (edge->cyclelane() == CycleLane::kShared) { class_factor = 0.9f; } else if (edge->cyclelane() == CycleLane::kDedicated) { class_factor = 0.5f; } else if (edge->cyclelane() == CycleLane::kSeparated) { class_factor = 0.25f; } } // Penalize transition to higher class road. // TODO - modulate based on useroads factor? if (edge->classification() < pred.classification()) { penalty += 10.0f * (static_cast(pred.classification()) - static_cast(edge->classification())); turn_stress *= kRoadClassFactor[static_cast(edge->classification())] + 1.0f; } if (edge->stopimpact(idx) > 0) { // Increase turn stress depending on the kind of turn that has to be made. float turn_penalty = (edge->drive_on_right()) ? kRightSideTurnPenalties[static_cast(edge->turntype(idx))] : kLeftSideTurnPenalties[static_cast(edge->turntype(idx))]; turn_stress += turn_penalty; // Take the higher of the turn degree cost and the crossing cost float turn_cost = (edge->drive_on_right()) ? kRightSideTurnCosts[static_cast(edge->turntype(idx))] : kLeftSideTurnCosts[static_cast(edge->turntype(idx))]; if (turn_cost < kTCCrossing && edge->edge_to_right(idx) && edge->edge_to_left(idx)) { turn_cost = kTCCrossing; } // Transition time = densityfactor * stopimpact * turncost seconds += trans_density_factor_[node->density()] * edge->stopimpact(idx) * turn_cost; } // Final turn factor based on the stress to make the turn and if the road being turned to is bike friendly. float factor = 1.0f + turn_stress * class_factor; // Return cost (time and penalty) return { (seconds * factor) + penalty, seconds }; } // Returns the cost to make the transition from the predecessor edge // when using a reverse search (from destination towards the origin). // pred is the opposing current edge in the reverse tree // edge is the opposing predecessor in the reverse tree Cost LowStressBicycleCost::TransitionCostReverse(const uint32_t idx, const baldr::NodeInfo* node, const baldr::DirectedEdge* pred, const baldr::DirectedEdge* edge) const { // Accumulate cost and penalty float seconds = 0.0f; float penalty = 0.0f; // Special cases with both time and penalty: country crossing, // gate, toll booth if (node->type() == NodeType::kBorderControl) { seconds += country_crossing_cost_; penalty += country_crossing_penalty_; } else if (node->type() == NodeType::kGate) { seconds += gate_cost_; penalty += gate_penalty_; } // Additional penalties without any time cost if (pred->use() != Use::kAlley && edge->use() == Use::kAlley) { penalty += alley_penalty_; } if (pred->use() != Use::kDriveway && edge->use() == Use::kDriveway) { penalty += driveway_penalty_; } if ((pred->use() != Use::kFerry && edge->use() == Use::kFerry)) { seconds += ferry_cost_; penalty += ferry_penalty_; } // Ignore name inconsistency when entering a link to avoid double penalizing. if (!edge->link() && !node->name_consistency(idx, edge->localedgeidx())) { // Slight maneuver penalty penalty += maneuver_penalty_; } // Reduce the turn stress if there is a traffic signal // TODO - Put this and other complex considerations like lane count into the stop impact code float turn_stress = (node->traffic_signal()) ? 0.4 : 1.0; // Reduce the cost to make this turn if the road we are turning on to has some kind // of bicycle accommodation // TODO - Determine if this is needed or tweak/add to it float class_factor = 1.0f; if (edge->use() == Use::kCycleway) { class_factor = 0.05f; } else if (edge->use() == Use::kPedestrian || edge->use() == Use::kPath) { class_factor = 0.1f; } else { if (edge->cyclelane() == CycleLane::kShared) { class_factor = 0.9f; } else if (edge->cyclelane() == CycleLane::kDedicated) { class_factor = 0.5f; } else if (edge->cyclelane() == CycleLane::kSeparated) { class_factor = 0.25f; } } // Penalize transition to higher class road. // TODO - modulate based on useroads factor? if (edge->classification() < pred->classification()) { penalty += 10.0f * (static_cast(pred->classification()) - static_cast(edge->classification())); turn_stress *= kRoadClassFactor[static_cast(edge->classification())] + 1.0f; } if (edge->stopimpact(idx) > 0) { // Increase turn stress depending on the kind of turn that has to be made. float turn_penalty = (edge->drive_on_right()) ? kRightSideTurnPenalties[static_cast(edge->turntype(idx))] : kLeftSideTurnPenalties[static_cast(edge->turntype(idx))]; turn_stress += turn_penalty; // Take the higher of the turn degree cost and the crossing cost float turn_cost = (edge->drive_on_right()) ? kRightSideTurnCosts[static_cast(edge->turntype(idx))] : kLeftSideTurnCosts[static_cast(edge->turntype(idx))]; if (turn_cost < kTCCrossing && edge->edge_to_right(idx) && edge->edge_to_left(idx)) { turn_cost = kTCCrossing; } // Transition time = densityfactor * stopimpact * turncost seconds += trans_density_factor_[node->density()] * edge->stopimpact(idx) * turn_cost; } // Final turn factor based on the stress to make the turn and if the road being turned to is bike friendly. float factor = 1.0f + turn_stress * class_factor; // Return cost (time and penalty) return { (seconds * factor) + penalty, seconds }; } cost_ptr_t CreateLowStressBicycleCost(const boost::property_tree::ptree& config) { return std::make_shared(config); } } } /**********************************************************************************************/ #ifdef INLINE_TEST using namespace valhalla; using namespace sif; namespace { BicycleCost* make_bicyclecost_from_json(const std::string& property, float testVal) { std::stringstream ss; ss << R""({"")"" << property << R""("":)"" << testVal << ""}""; boost::property_tree::ptree costing_ptree; boost::property_tree::read_json(ss, costing_ptree); return new BicycleCost(costing_ptree); } std::uniform_real_distribution* make_distributor_from_range (const ranged_default_t& range) { float rangeLength = range.max - range.min; return new std::uniform_real_distribution(range.min - rangeLength, range.max + rangeLength); } void testBicycleCostParams() { constexpr unsigned testIterations = 250; constexpr unsigned seed = 0; std::default_random_engine generator(seed); std::shared_ptr> distributor; std::shared_ptr ctorTester; // maneuver_penalty_ distributor.reset(make_distributor_from_range(kManeuverPenaltyRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""maneuver_penalty"", (*distributor)(generator))); if (ctorTester->maneuver_penalty_ < kManeuverPenaltyRange.min || ctorTester->maneuver_penalty_ > kManeuverPenaltyRange.max) { throw std::runtime_error (""maneuver_penalty_ is not within it's range""); } } // driveway_penalty_ distributor.reset(make_distributor_from_range(kDrivewayPenaltyRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""driveway"", (*distributor)(generator))); if (ctorTester->driveway_penalty_ < kDrivewayPenaltyRange.min || ctorTester->driveway_penalty_ > kDrivewayPenaltyRange.max) { throw std::runtime_error (""driveway_penalty_ is not within it's range""); } } // alley_penalty_ distributor.reset(make_distributor_from_range(kAlleyPenaltyRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""alley_penalty"", (*distributor)(generator))); if (ctorTester->alley_penalty_ < kAlleyPenaltyRange.min || ctorTester->alley_penalty_ > kAlleyPenaltyRange.max) { throw std::runtime_error (""alley_penalty_ is not within it's range""); } } // gate_cost_ distributor.reset(make_distributor_from_range(kGateCostRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""gate_cost"", (*distributor)(generator))); if (ctorTester->gate_cost_ < kGateCostRange.min || ctorTester->gate_cost_ > kGateCostRange.max) { throw std::runtime_error (""gate_cost_ is not within it's range""); } } // gate_penalty_ distributor.reset(make_distributor_from_range(kGatePenaltyRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""gate_penalty"", (*distributor)(generator))); if (ctorTester->gate_penalty_ < kGatePenaltyRange.min || ctorTester->gate_penalty_ > kGatePenaltyRange.max) { throw std::runtime_error (""gate_penalty_ is not within it's range""); } } // ferry_cost_ distributor.reset(make_distributor_from_range(kFerryCostRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""ferry_cost"", (*distributor)(generator))); if (ctorTester->ferry_cost_ < kFerryCostRange.min || ctorTester->ferry_cost_ > kFerryCostRange.max) { throw std::runtime_error (""ferry_cost_ is not within it's range""); } } // country_crossing_cost_ distributor.reset(make_distributor_from_range(kCountryCrossingCostRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""country_crossing_cost"", (*distributor)(generator))); if (ctorTester->country_crossing_cost_ < kCountryCrossingCostRange.min || ctorTester->country_crossing_cost_ > kCountryCrossingCostRange.max) { throw std::runtime_error (""country_crossing_cost_ is not within it's range""); } } // country_crossing_penalty_ distributor.reset(make_distributor_from_range(kCountryCrossingPenaltyRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""country_crossing_penalty"", (*distributor)(generator))); if (ctorTester->country_crossing_penalty_ < kCountryCrossingPenaltyRange.min || ctorTester->country_crossing_penalty_ > kCountryCrossingPenaltyRange.max) { throw std::runtime_error (""country_crossing_penalty_ is not within it's range""); } } // use_roads_ distributor.reset(make_distributor_from_range(kUseRoadRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""use_roads"", (*distributor)(generator))); if (ctorTester->use_roads_ < kUseRoadRange.min || ctorTester->use_roads_ > kUseRoadRange.max) { throw std::runtime_error (""use_roads_ is not within it's range""); } } // speed_ constexpr ranged_default_t kRoadCyclingSpeedRange {kMinCyclingSpeed, kDefaultCyclingSpeed[0], kMaxCyclingSpeed}; distributor.reset(make_distributor_from_range(kRoadCyclingSpeedRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""cycling_speed"", (*distributor)(generator))); if (ctorTester->speed_ < kRoadCyclingSpeedRange.min || ctorTester->speed_ > kRoadCyclingSpeedRange.max) { throw std::runtime_error (""speed_ is not within it's range""); } } // use_ferry_ distributor.reset(make_distributor_from_range(kUseFerryRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""use_ferry"", (*distributor)(generator))); if (ctorTester->use_ferry_ < kUseFerryRange.min || ctorTester->use_ferry_ > kUseFerryRange.max) { throw std::runtime_error (""use_ferry_ is not within it's range""); } } // use_hills_ distributor.reset(make_distributor_from_range(kUseHillsRange)); for (unsigned i = 0; i < testIterations; ++i) { ctorTester.reset(make_bicyclecost_from_json(""use_hills"", (*distributor)(generator))); if (ctorTester->use_hills_ < kUseHillsRange.min || ctorTester->use_hills_ > kUseHillsRange.max) { throw std::runtime_error (""use_hills_ is not within it's range""); } } } } int main() { test::suite suite(""costing""); suite.test(TEST_CASE(testBicycleCostParams)); return suite.tear_down(); } #endif ",16261,True,2835.326281679032,median "*----------------------------------------------------------------------* * CLASS ZCL_LOGGER DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* class zcl_logger definition public create private global friends zcl_logger_factory . public section. *""* public components of class ZCL_LOGGER *""* do not include other source files here!!! type-pools abap . interfaces zif_logger. aliases: add for zif_logger~add, a for zif_logger~a, e for zif_logger~e, w for zif_logger~w, i for zif_logger~i, s for zif_logger~s, has_errors for zif_logger~has_errors, has_warnings for zif_logger~has_warnings, is_empty for zif_logger~is_empty, length for zif_logger~length, save for zif_logger~save, export_to_table for zif_logger~export_to_table, fullscreen for zif_logger~fullscreen, popup for zif_logger~popup, handle for zif_logger~handle, db_number for zif_logger~db_number, header for zif_logger~header. ""! Starts a new log. ""! For backwards compatibility only! Use ZCL_LOGGER_FACTORY instead. class-methods new importing !object type csequence optional !subobject type csequence optional !desc type csequence optional !context type simple optional !auto_save type abap_bool optional !second_db_conn type abap_bool default abap_true returning value(r_log) type ref to zcl_logger . ""! Reopens an already existing log. ""! For backwards compatibility only! Use ZCL_LOGGER_FACTORY instead. class-methods open importing !object type csequence !subobject type csequence !desc type csequence optional !create_if_does_not_exist type abap_bool default abap_false !auto_save type abap_bool optional returning value(r_log) type ref to zcl_logger . protected section. *""* protected components of class ZCL_LOGGER *""* do not include other source files here!!! private section. * Local type for hrpad_message as it is not available in an ABAP Development System types: begin of hrpad_message_field_list_alike, scrrprfd type scrrprfd. types: end of hrpad_message_field_list_alike. types: begin of hrpad_message_alike, cause(32) type c, ""original: hrpad_message_cause detail_level type ballevel. include type symsg . types: field_list type standard table of hrpad_message_field_list_alike with non-unique key scrrprfd. types: end of hrpad_message_alike. *""* private components of class ZCL_LOGGER *""* do not include other source files here!!! data sec_connection type abap_bool . data sec_connect_commit type abap_bool . data settings type ref to zif_logger_settings. methods: ""! Safety limit for previous exception drill down drill_down_into_exception importing exception type ref to cx_root type type symsgty optional importance type balprobcl optional returning value(rt_exception_data_table) type tty_exception_data, get_message_handles importing msgtype type symsgty optional returning value(rt_message_handles) type bal_t_msgh , add_structure importing obj_to_log type any optional context type simple optional callback_form type csequence optional callback_prog type csequence optional callback_fm type csequence optional type type symsgty optional importance type balprobcl optional preferred parameter obj_to_log returning value(self) type ref to zif_logger . methods save_log. ENDCLASS. CLASS ZCL_LOGGER IMPLEMENTATION. method a. self = add( obj_to_log = obj_to_log context = context callback_form = callback_form callback_prog = callback_prog callback_fm = callback_fm type = 'A' importance = importance ). endmethod. method add. data: detailed_msg type bal_s_msg, exception_data_table type tty_exception_data, free_text_msg type char200, ctx_type type ref to cl_abap_typedescr, ctx_ddic_header type x030l, msg_type type ref to cl_abap_typedescr, msg_table_type type ref to cl_abap_tabledescr, log_numbers type bal_t_lgnm, log_handles type bal_t_logh, log_number type bal_s_lgnm, formatted_context type bal_s_cont, formatted_params type bal_s_parm. field-symbols: type any table, type any, type bapiret1, type bapiret2, type bapi_coru_return, type bapi_order_return, type bdcmsgcoll, type hrpad_message_alike, type rcomp, type any. if context is not initial. assign context to . formatted_context-value = . ctx_type = cl_abap_typedescr=>describe_by_data( context ). call method ctx_type->get_ddic_header receiving p_header = ctx_ddic_header exceptions not_found = 1 no_ddic_type = 2 others = 3. if sy-subrc = 0. formatted_context-tabname = ctx_ddic_header-tabname. endif. endif. if callback_fm is not initial. formatted_params-callback-userexitf = callback_fm. formatted_params-callback-userexitp = callback_prog. formatted_params-callback-userexitt = 'F'. elseif callback_form is not initial. formatted_params-callback-userexitf = callback_form. formatted_params-callback-userexitp = callback_prog. formatted_params-callback-userexitt = ' '. endif. msg_type = cl_abap_typedescr=>describe_by_data( obj_to_log ). if obj_to_log is not supplied. detailed_msg-msgty = sy-msgty. detailed_msg-msgid = sy-msgid. detailed_msg-msgno = sy-msgno. detailed_msg-msgv1 = sy-msgv1. detailed_msg-msgv2 = sy-msgv2. detailed_msg-msgv3 = sy-msgv3. detailed_msg-msgv4 = sy-msgv4. elseif msg_type->absolute_name = '\\TYPE=BAPIRET1'. assign obj_to_log to . detailed_msg-msgty = -type. detailed_msg-msgid = -id. detailed_msg-msgno = -number. detailed_msg-msgv1 = -message_v1. detailed_msg-msgv2 = -message_v2. detailed_msg-msgv3 = -message_v3. detailed_msg-msgv4 = -message_v4. elseif msg_type->absolute_name = '\\TYPE=BAPIRET2'. assign obj_to_log to . detailed_msg-msgty = -type. detailed_msg-msgid = -id. detailed_msg-msgno = -number. detailed_msg-msgv1 = -message_v1. detailed_msg-msgv2 = -message_v2. detailed_msg-msgv3 = -message_v3. detailed_msg-msgv4 = -message_v4. elseif msg_type->absolute_name = '\\TYPE=BAPI_CORU_RETURN'. assign obj_to_log to . detailed_msg-msgty = -type. detailed_msg-msgid = -id. detailed_msg-msgno = -number. detailed_msg-msgv1 = -message_v1. detailed_msg-msgv2 = -message_v2. detailed_msg-msgv3 = -message_v3. detailed_msg-msgv4 = -message_v4. elseif msg_type->absolute_name = '\\TYPE=BAPI_ORDER_RETURN'. assign obj_to_log to . detailed_msg-msgty = -type. detailed_msg-msgid = -id. detailed_msg-msgno = -number. detailed_msg-msgv1 = -message_v1. detailed_msg-msgv2 = -message_v2. detailed_msg-msgv3 = -message_v3. detailed_msg-msgv4 = -message_v4. elseif msg_type->absolute_name = '\\TYPE=BDCMSGCOLL'. assign obj_to_log to . detailed_msg-msgty = -msgtyp. detailed_msg-msgid = -msgid. detailed_msg-msgno = -msgnr. detailed_msg-msgv1 = -msgv1. detailed_msg-msgv2 = -msgv2. detailed_msg-msgv3 = -msgv3. detailed_msg-msgv4 = -msgv4. elseif msg_type->absolute_name = '\\TYPE=HRPAD_MESSAGE'. assign obj_to_log to . detailed_msg-msgty = -msgty. detailed_msg-msgid = -msgid. detailed_msg-msgno = -msgno. detailed_msg-msgv1 = -msgv1. detailed_msg-msgv2 = -msgv2. detailed_msg-msgv3 = -msgv3. detailed_msg-msgv4 = -msgv4. elseif msg_type->absolute_name = '\\TYPE=RCOMP'. assign obj_to_log to . detailed_msg-msgty = -msgty. detailed_msg-msgid = -msgid. detailed_msg-msgno = -msgno. detailed_msg-msgv1 = -msgv1. detailed_msg-msgv2 = -msgv2. detailed_msg-msgv3 = -msgv3. detailed_msg-msgv4 = -msgv4. elseif msg_type->type_kind = cl_abap_typedescr=>typekind_oref. exception_data_table = me->drill_down_into_exception( exception = obj_to_log type = type importance = importance ). elseif msg_type->type_kind = cl_abap_typedescr=>typekind_table. assign obj_to_log to . loop at assigning . add( ). endloop. elseif msg_type->type_kind = cl_abap_typedescr=>typekind_struct1 ""flat structure or msg_type->type_kind = cl_abap_typedescr=>typekind_struct2. ""deep structure (already when string is used) add_structure( exporting obj_to_log = obj_to_log context = context callback_form = callback_form callback_prog = callback_prog callback_fm = callback_fm type = type importance = importance receiving self = self ). else. free_text_msg = obj_to_log. endif. if free_text_msg is not initial. call function 'BAL_LOG_MSG_ADD_FREE_TEXT' exporting i_log_handle = me->handle i_msgty = type i_probclass = importance i_text = free_text_msg i_s_context = formatted_context i_s_params = formatted_params. elseif exception_data_table is not initial. field-symbols like line of exception_data_table. loop at exception_data_table assigning . call function 'BAL_LOG_EXCEPTION_ADD' exporting i_log_handle = me->handle i_s_exc = . endloop. elseif detailed_msg is not initial. detailed_msg-context = formatted_context. detailed_msg-params = formatted_params. detailed_msg-probclass = importance. call function 'BAL_LOG_MSG_ADD' exporting i_log_handle = me->handle i_s_msg = detailed_msg. endif. if me->settings->get_autosave( ) = abap_true. save_log( ). endif. self = me. endmethod. method add_structure. data: msg_type type ref to cl_abap_typedescr, msg_struct_type type ref to cl_abap_structdescr, components type cl_abap_structdescr=>component_table, component like line of components, string_to_log type string. field-symbols: type any, TYPE ANY TABLE. msg_struct_type ?= cl_abap_typedescr=>describe_by_data( obj_to_log ). components = msg_struct_type->get_components( ). add( '--- Begin of structure ---' ). loop at components into component. assign component component-name of structure obj_to_log to . if sy-subrc = 0. msg_type = cl_abap_typedescr=>describe_by_data( ). if msg_type->kind = cl_abap_typedescr=>kind_elem. string_to_log = |{ to_lower( component-name ) } = { }|. add( string_to_log ). elseif msg_type->kind = cl_abap_typedescr=>kind_struct. add_structure( exporting obj_to_log = context = context callback_form = callback_form callback_prog = callback_prog callback_fm = callback_fm type = type importance = importance receiving self = self ). ELSEIF msg_type->kind = cl_abap_typedescr=>kind_table. ASSIGN TO
. LOOP AT
ASSIGNING FIELD-SYMBOL(). add( ). ENDLOOP. endif. endif. endloop. add( '--- End of structure ---' ). endmethod. method drill_down_into_exception. data: i type i value 2, previous_exception type ref to cx_root, exceptions type tty_exception. field-symbols like line of exceptions. append initial line to exceptions assigning . -level = 1. -exception = exception. previous_exception = exception. while i <= settings->get_max_exception_drill_down( ). if previous_exception->previous is not bound. exit. endif. previous_exception ?= previous_exception->previous. append initial line to exceptions assigning . -level = i. -exception = previous_exception. i = i + 1. endwhile. field-symbols like line of rt_exception_data_table. sort exceptions by level descending. ""Display the deepest exception first loop at exceptions assigning . append initial line to rt_exception_data_table assigning . -exception = -exception. -msgty = type. -probclass = importance. endloop. endmethod. method e. self = add( obj_to_log = obj_to_log context = context callback_form = callback_form callback_prog = callback_prog callback_fm = callback_fm type = 'E' importance = importance ). endmethod. method export_to_table. data: message_handles type bal_t_msgh, message type bal_s_msg, bapiret2 type bapiret2. field-symbols type balmsghndl. message_handles = get_message_handles( ). loop at message_handles assigning . call function 'BAL_LOG_MSG_READ' exporting i_s_msg_handle = importing e_s_msg = message exceptions others = 3. if sy-subrc is initial. message id message-msgid type message-msgty number message-msgno into bapiret2-message with message-msgv1 message-msgv2 message-msgv3 message-msgv4. bapiret2-type = message-msgty. bapiret2-id = message-msgid. bapiret2-number = message-msgno. bapiret2-log_no = -log_handle. ""last 2 chars missing!! bapiret2-log_msg_no = -msgnumber. bapiret2-message_v1 = message-msgv1. bapiret2-message_v2 = message-msgv2. bapiret2-message_v3 = message-msgv3. bapiret2-message_v4 = message-msgv4. bapiret2-system = sy-sysid. append bapiret2 to rt_bapiret. endif. endloop. endmethod. method fullscreen. data: profile type bal_s_prof, lt_log_handles type bal_t_logh. append me->handle to lt_log_handles. call function 'BAL_DSP_PROFILE_SINGLE_LOG_GET' importing e_s_display_profile = profile. call function 'BAL_DSP_LOG_DISPLAY' exporting i_s_display_profile = profile i_t_log_handle = lt_log_handles. endmethod. method get_message_handles. data: log_handle type bal_t_logh, filter type bal_s_mfil. field-symbols like line of filter-msgty. insert handle into table log_handle. if msgtype is not initial. append initial line to filter-msgty assigning . -sign = 'I'. -option = 'EQ'. -low = msgtype. endif. call function 'BAL_GLB_SEARCH_MSG' exporting i_t_log_handle = log_handle i_s_msg_filter = filter importing e_t_msg_handle = rt_message_handles exceptions msg_not_found = 0. endmethod. method has_errors. rv_yes = boolc( lines( get_message_handles( msgtype = 'E' ) ) > 0 ). endmethod. method has_warnings. rv_yes = boolc( lines( get_message_handles( msgtype = 'W' ) ) > 0 ). endmethod. method i. self = add( obj_to_log = obj_to_log context = context callback_form = callback_form callback_prog = callback_prog callback_fm = callback_fm type = 'I' importance = importance ). endmethod. method is_empty. rv_yes = boolc( length( ) = 0 ). endmethod. method length. rv_length = lines( get_message_handles( ) ). endmethod. method new. if auto_save is supplied. r_log ?= zcl_logger_factory=>create_log( object = object subobject = subobject desc = desc context = context settings = zcl_logger_factory=>create_settings( )->set_usage_of_secondary_db_conn( second_db_conn )->set_autosave( auto_save ) ). else. r_log ?= zcl_logger_factory=>create_log( object = object subobject = subobject desc = desc context = context settings = zcl_logger_factory=>create_settings( )->set_usage_of_secondary_db_conn( second_db_conn ) ). endif. endmethod. method open. if auto_save is supplied. r_log ?= zcl_logger_factory=>open_log( object = object subobject = subobject desc = desc create_if_does_not_exist = create_if_does_not_exist settings = zcl_logger_factory=>create_settings( )->set_autosave( auto_save ) ). else. r_log ?= zcl_logger_factory=>open_log( object = object subobject = subobject desc = desc create_if_does_not_exist = create_if_does_not_exist ). endif. endmethod. method popup. * See SBAL_DEMO_04_POPUP for ideas data: profile type bal_s_prof, lt_log_handles type bal_t_logh. append me->handle to lt_log_handles. call function 'BAL_DSP_PROFILE_POPUP_GET' importing e_s_display_profile = profile. call function 'BAL_DSP_LOG_DISPLAY' exporting i_s_display_profile = profile i_t_log_handle = lt_log_handles. endmethod. method s. self = add( obj_to_log = obj_to_log context = context callback_form = callback_form callback_prog = callback_prog callback_fm = callback_fm type = 'S' importance = importance ). endmethod. method save. check me->settings->get_autosave( ) = abap_false. save_log( ). endmethod. method save_log. data log_handles type bal_t_logh. data log_numbers type bal_t_lgnm. data log_number type bal_s_lgnm. insert me->handle into table log_handles. call function 'BAL_DB_SAVE' exporting i_t_log_handle = log_handles i_2th_connection = me->sec_connection i_2th_connect_commit = me->sec_connect_commit importing e_new_lognumbers = log_numbers. if me->db_number is initial. read table log_numbers index 1 into log_number. me->db_number = log_number-lognumber. endif. endmethod. method w. self = add( obj_to_log = obj_to_log context = context callback_form = callback_form callback_prog = callback_prog callback_fm = callback_fm type = 'W' importance = importance ). endmethod. ENDCLASS. ",5170,False,1026.4422621513315,median "// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include ""ash/display/display_prefs.h"" #include #include #include #include #include #include ""ash/constants/ash_switches.h"" #include ""ash/display/display_configuration_observer.h"" #include ""ash/display/display_util.h"" #include ""ash/display/resolution_notification_controller.h"" #include ""ash/display/screen_orientation_controller.h"" #include ""ash/display/window_tree_host_manager.h"" #include ""ash/public/cpp/ash_pref_names.h"" #include ""ash/session/test_session_controller_client.h"" #include ""ash/shell.h"" #include ""ash/test/ash_test_base.h"" #include ""ash/test/ash_test_helper.h"" #include ""ash/wm/tablet_mode/tablet_mode_controller.h"" #include ""base/command_line.h"" #include ""base/macros.h"" #include ""base/memory/ptr_util.h"" #include ""base/numerics/math_constants.h"" #include ""base/strings/string_number_conversions.h"" #include ""base/test/scoped_feature_list.h"" #include ""base/values.h"" #include ""components/prefs/scoped_user_pref_update.h"" #include ""components/prefs/testing_pref_service.h"" #include ""components/user_manager/user_type.h"" #include ""testing/gtest/include/gtest/gtest.h"" #include ""ui/display/display_layout_builder.h"" #include ""ui/display/display_switches.h"" #include ""ui/display/manager/display_configurator.h"" #include ""ui/display/manager/display_layout_store.h"" #include ""ui/display/manager/display_manager.h"" #include ""ui/display/manager/display_manager_utilities.h"" #include ""ui/display/manager/json_converter.h"" #include ""ui/display/manager/managed_display_info.h"" #include ""ui/display/manager/test/touch_device_manager_test_api.h"" #include ""ui/display/screen.h"" #include ""ui/display/test/display_manager_test_api.h"" #include ""ui/events/devices/touchscreen_device.h"" #include ""ui/gfx/geometry/vector3d_f.h"" namespace ash { namespace { const char kPrimaryIdKey[] = ""primary-id""; bool IsRotationLocked() { return ash::Shell::Get()->screen_orientation_controller()->rotation_locked(); } bool CompareTouchAssociations( const display::TouchDeviceManager::TouchAssociationMap& map_1, const display::TouchDeviceManager::TouchAssociationMap& map_2) { if (map_1.size() != map_2.size()) return false; // Each iterator instance |entry| is a pair of type // std::pair for (const auto& entry : map_1) { if (!map_2.count(entry.first)) return false; const auto& association_info_map_1 = entry.second; const auto& association_info_map_2 = map_2.at(entry.first); if (association_info_map_1.size() != association_info_map_2.size()) return false; // Each iterator instance is a pair of type: // std::pair for (const auto& info_1 : association_info_map_1) { if (!association_info_map_2.count(info_1.first)) return false; const auto& info_2 = association_info_map_2.at(info_1.first); if (!(info_1.second.timestamp == info_2.timestamp && info_1.second.calibration_data == info_2.calibration_data)) { return false; } } } return true; } bool ComparePortAssociations( const display::TouchDeviceManager::PortAssociationMap& map_1, const display::TouchDeviceManager::PortAssociationMap& map_2) { if (map_1.size() != map_2.size()) return false; auto it_1 = map_1.begin(); auto it_2 = map_2.begin(); while (it_1 != map_1.end()) { if (it_1->first != it_2->first) return false; if (it_1->second != it_2->second) return false; it_1++; it_2++; } return true; } } // namespace class DisplayPrefsTest : public AshTestBase { protected: DisplayPrefsTest() = default; ~DisplayPrefsTest() override = default; void SetUp() override { AshTestBase::SetUp(); observer_ = std::make_unique(); observer_->OnDisplaysInitialized(); } void TearDown() override { observer_.reset(); AshTestBase::TearDown(); } void LoggedInAsUser() { SimulateUserLogin(""user1@test.com""); } void LoggedInAsGuest() { SimulateGuestLogin(); } void LoggedInAsPublicAccount() { SimulateUserLogin(""pa@test.com"", user_manager::USER_TYPE_PUBLIC_ACCOUNT); } void LoadDisplayPreferences() { display_prefs()->LoadDisplayPreferences(); } // Do not use the implementation of display_prefs.cc directly to avoid // notifying the update to the system. void StoreDisplayLayoutPrefForList( const display::DisplayIdList& list, display::DisplayPlacement::Position position, int offset, int64_t primary_id) { std::string name = display::DisplayIdListToString(list); DictionaryPrefUpdate update(local_state(), prefs::kSecondaryDisplays); display::DisplayLayout display_layout; display_layout.placement_list.emplace_back(position, offset); display_layout.primary_id = primary_id; DCHECK(!name.empty()); base::DictionaryValue* pref_data = update.Get(); std::unique_ptr layout_value(new base::DictionaryValue()); base::Value* value = nullptr; if (pref_data->Get(name, &value) && value != nullptr) layout_value.reset(value->DeepCopy()); if (display::DisplayLayoutToJson(display_layout, layout_value.get())) pref_data->Set(name, std::move(layout_value)); } void StoreDisplayPropertyForList(const display::DisplayIdList& list, const std::string& key, std::unique_ptr value) { std::string name = display::DisplayIdListToString(list); DictionaryPrefUpdate update(local_state(), prefs::kSecondaryDisplays); base::DictionaryValue* pref_data = update.Get(); base::Value* layout_value = pref_data->FindKey(name); if (layout_value) { static_cast(layout_value) ->Set(key, std::move(value)); } else { std::unique_ptr layout_value( new base::DictionaryValue()); layout_value->SetBoolean(key, value != nullptr); pref_data->Set(name, std::move(layout_value)); } } void StoreDisplayBoolPropertyForList(const display::DisplayIdList& list, const std::string& key, bool value) { StoreDisplayPropertyForList(list, key, std::make_unique(value)); } void StoreDisplayLayoutPrefForList(const display::DisplayIdList& list, display::DisplayPlacement::Position layout, int offset) { StoreDisplayLayoutPrefForList(list, layout, offset, list[0]); } void StoreDisplayOverscan(int64_t id, const gfx::Insets& insets) { DictionaryPrefUpdate update(local_state(), prefs::kDisplayProperties); const std::string name = base::NumberToString(id); base::DictionaryValue* pref_data = update.Get(); auto insets_value = std::make_unique(); insets_value->SetInteger(""insets_top"", insets.top()); insets_value->SetInteger(""insets_left"", insets.left()); insets_value->SetInteger(""insets_bottom"", insets.bottom()); insets_value->SetInteger(""insets_right"", insets.right()); pref_data->Set(name, std::move(insets_value)); } display::Display::Rotation GetRotation() { return Shell::Get() ->display_manager() ->GetDisplayInfo(display::Display::InternalDisplayId()) .GetRotation(display::Display::RotationSource::ACCELEROMETER); } void StoreExternalDisplayMirrorInfo( const std::set& external_display_mirror_info) { ListPrefUpdate update(local_state(), prefs::kExternalDisplayMirrorInfo); base::ListValue* pref_data = update.Get(); pref_data->Clear(); for (const auto& id : external_display_mirror_info) pref_data->Append(base::Value(base::NumberToString(id))); } std::string GetRegisteredDisplayPlacementStr( const display::DisplayIdList& list) { return Shell::Get() ->display_manager() ->layout_store() ->GetRegisteredDisplayLayout(list) .placement_list[0] .ToString(); } display::DisplayConfigurator* display_configurator() { return Shell::Get()->display_configurator(); } DisplayPrefs* display_prefs() { return Shell::Get()->display_prefs(); } private: std::unique_ptr observer_; base::test::ScopedFeatureList scoped_feature_list_; DISALLOW_COPY_AND_ASSIGN(DisplayPrefsTest); }; class DisplayPrefsTestGuest : public DisplayPrefsTest { public: DisplayPrefsTestGuest() { set_start_session(false); } private: DISALLOW_COPY_AND_ASSIGN(DisplayPrefsTestGuest); }; TEST_F(DisplayPrefsTest, ListedLayoutOverrides) { UpdateDisplay(""100x100,200x200""); display::DisplayIdList list = display_manager()->GetCurrentDisplayIdList(); display::DisplayIdList dummy_list = display::test::CreateDisplayIdList2( list[0], display::GetNextSynthesizedDisplayId(list[1])); ASSERT_NE(list[0], dummy_list[1]); StoreDisplayLayoutPrefForList(list, display::DisplayPlacement::TOP, 20); StoreDisplayLayoutPrefForList(dummy_list, display::DisplayPlacement::LEFT, 30); display_prefs()->StoreDisplayPowerStateForTest( chromeos::DISPLAY_POWER_INTERNAL_OFF_EXTERNAL_ON); base::CommandLine::ForCurrentProcess()->AppendSwitch( chromeos::switches::kFirstExecAfterBoot); LoadDisplayPreferences(); // requested_power_state_ should be chromeos::DISPLAY_POWER_ALL_ON at boot const base::Optional requested_power_state = display_configurator()->GetRequestedPowerStateForTest(); ASSERT_NE(base::nullopt, requested_power_state); EXPECT_EQ(chromeos::DISPLAY_POWER_ALL_ON, *requested_power_state); // DisplayPowerState should be ignored at boot. EXPECT_EQ(chromeos::DISPLAY_POWER_ALL_ON, display_configurator()->GetRequestedPowerState()); Shell::Get()->display_manager()->UpdateDisplays(); // Check if the layout settings are notified to the system properly. // The new layout overrides old layout. // Inverted one of for specified pair (id1, id2). Not used for the list // (id1, dummy_id) since dummy_id is not connected right now. EXPECT_EQ(""id=2200000257, parent=2200000000, top, 20"", Shell::Get() ->display_manager() ->GetCurrentDisplayLayout() .placement_list[0] .ToString()); EXPECT_EQ(""id=2200000257, parent=2200000000, top, 20"", GetRegisteredDisplayPlacementStr(list)); EXPECT_EQ(""id=2200000258, parent=2200000000, left, 30"", GetRegisteredDisplayPlacementStr(dummy_list)); } TEST_F(DisplayPrefsTest, BasicStores) { WindowTreeHostManager* window_tree_host_manager = Shell::Get()->window_tree_host_manager(); int64_t id1 = display::Screen::GetScreen()->GetPrimaryDisplay().id(); // For each configuration change, we store mirror info only for external // displays. So set internal display first before adding display. display::test::ScopedSetInternalDisplayId set_internal(display_manager(), id1); UpdateDisplay(""200x200*2, 400x300#400x400|300x200*1.25""); display::test::DisplayManagerTestApi display_manager_test(display_manager()); int64_t id2 = display_manager_test.GetSecondaryDisplay().id(); int64_t dummy_id = display::GetNextSynthesizedDisplayId(id2); ASSERT_NE(id1, dummy_id); LoggedInAsUser(); display_manager()->SetLayoutForCurrentDisplays( display::test::CreateDisplayLayout(display_manager(), display::DisplayPlacement::TOP, 10)); const display::DisplayLayout& layout = display_manager()->GetCurrentDisplayLayout(); EXPECT_EQ(display::DisplayPlacement::TOP, layout.placement_list[0].position); EXPECT_EQ(10, layout.placement_list[0].offset); display::DisplayLayoutBuilder dummy_layout_builder(id1); dummy_layout_builder.SetSecondaryPlacement( dummy_id, display::DisplayPlacement::LEFT, 20); std::unique_ptr dummy_layout( dummy_layout_builder.Build()); display::DisplayIdList list = display::test::CreateDisplayIdList2(id1, dummy_id); display_prefs()->StoreDisplayLayoutPrefForTest(list, *dummy_layout); // Can't switch to a display that does not exist. window_tree_host_manager->SetPrimaryDisplayId(dummy_id); EXPECT_NE(dummy_id, display::Screen::GetScreen()->GetPrimaryDisplay().id()); window_tree_host_manager->SetOverscanInsets(id1, gfx::Insets(10, 11, 12, 13)); display_manager()->SetDisplayRotation(id1, display::Display::ROTATE_90, display::Display::RotationSource::USER); constexpr float zoom_factor_1 = 1.f / display::kDsf_2_252; constexpr float zoom_factor_2 = 1.60f; display_manager()->UpdateZoomFactor(id1, zoom_factor_1); display_manager()->UpdateZoomFactor(id2, zoom_factor_2); // Set touch calibration data for display |id2|. ui::TouchscreenDevice touchdevice(11, ui::InputDeviceType::INPUT_DEVICE_USB, std::string(""test touch device""), gfx::Size(123, 456), 1); touchdevice.phys = ""5678""; display::TouchCalibrationData::CalibrationPointPairQuad point_pair_quad_1 = { {std::make_pair(gfx::Point(10, 10), gfx::Point(11, 12)), std::make_pair(gfx::Point(190, 10), gfx::Point(195, 8)), std::make_pair(gfx::Point(10, 90), gfx::Point(12, 94)), std::make_pair(gfx::Point(190, 90), gfx::Point(189, 88))}}; gfx::Size touch_size_1(200, 150); ui::TouchscreenDevice touchdevice_2(12, ui::InputDeviceType::INPUT_DEVICE_USB, std::string(""test touch device 2""), gfx::Size(132, 465), 1); touchdevice_2.phys = ""3456""; display::TouchCalibrationData::CalibrationPointPairQuad point_pair_quad_2 = { {std::make_pair(gfx::Point(10, 10), gfx::Point(11, 12)), std::make_pair(gfx::Point(190, 10), gfx::Point(195, 8)), std::make_pair(gfx::Point(10, 90), gfx::Point(12, 94)), std::make_pair(gfx::Point(190, 90), gfx::Point(189, 88))}}; gfx::Size touch_size_2(150, 150); // Create a 3rd touch device which has the same primary ID as the 2nd touch // device but is connected to a different port. ui::TouchscreenDevice touchdevice_3(15, ui::InputDeviceType::INPUT_DEVICE_USB, std::string(""test touch device 3""), gfx::Size(231, 416), 1); touchdevice_3.phys = ""1357""; display_manager()->SetTouchCalibrationData(id2, point_pair_quad_1, touch_size_1, touchdevice); display_manager()->SetTouchCalibrationData(id2, point_pair_quad_2, touch_size_2, touchdevice_2); display_manager()->SetTouchCalibrationData(id2, point_pair_quad_2, touch_size_1, touchdevice_3); const base::DictionaryValue* displays = local_state()->GetDictionary(prefs::kSecondaryDisplays); const base::DictionaryValue* layout_value = nullptr; std::string key = base::NumberToString(id1) + "","" + base::NumberToString(id2); std::string dummy_key = base::NumberToString(id1) + "","" + base::NumberToString(dummy_id); EXPECT_TRUE(displays->GetDictionary(dummy_key, &layout_value)); display::DisplayLayout stored_layout; EXPECT_TRUE(display::JsonToDisplayLayout(*layout_value, &stored_layout)); ASSERT_EQ(1u, stored_layout.placement_list.size()); EXPECT_EQ(dummy_layout->placement_list[0].position, stored_layout.placement_list[0].position); EXPECT_EQ(dummy_layout->placement_list[0].offset, stored_layout.placement_list[0].offset); const base::ListValue* external_display_mirror_info = local_state()->GetList(prefs::kExternalDisplayMirrorInfo); EXPECT_EQ(0U, external_display_mirror_info->GetSize()); const base::DictionaryValue* properties = local_state()->GetDictionary(prefs::kDisplayProperties); const base::DictionaryValue* property = nullptr; EXPECT_TRUE(properties->GetDictionary(base::NumberToString(id1), &property)); int rotation = 0; EXPECT_TRUE(property->GetInteger(""rotation"", &rotation)); EXPECT_EQ(1, rotation); double display_zoom_1; EXPECT_TRUE(property->GetDouble(""display_zoom_factor"", &display_zoom_1)); EXPECT_NEAR(display_zoom_1, zoom_factor_1, 0.0001); // Internal display never registered the resolution. int width = 0, height = 0; EXPECT_FALSE(property->GetInteger(""width"", &width)); EXPECT_FALSE(property->GetInteger(""height"", &height)); int top = 0, left = 0, bottom = 0, right = 0; EXPECT_TRUE(property->GetInteger(""insets_top"", &top)); EXPECT_TRUE(property->GetInteger(""insets_left"", &left)); EXPECT_TRUE(property->GetInteger(""insets_bottom"", &bottom)); EXPECT_TRUE(property->GetInteger(""insets_right"", &right)); EXPECT_EQ(10, top); EXPECT_EQ(11, left); EXPECT_EQ(12, bottom); EXPECT_EQ(13, right); display::TouchDeviceManager* tdm = display_manager()->touch_device_manager(); display::test::TouchDeviceManagerTestApi tdm_test_api(tdm); display::TouchDeviceManager::TouchAssociationMap expected_touch_associations_map = tdm->touch_associations(); display::TouchDeviceManager::PortAssociationMap expected_port_associations_map = tdm->port_associations(); tdm_test_api.ResetTouchDeviceManager(); EXPECT_FALSE(CompareTouchAssociations(expected_touch_associations_map, tdm->touch_associations())); EXPECT_FALSE(ComparePortAssociations(expected_port_associations_map, tdm->port_associations())); display_prefs()->LoadTouchAssociationPreferenceForTest(); display::TouchDeviceManager::TouchAssociationMap actual_touch_associations_map = tdm->touch_associations(); EXPECT_TRUE(CompareTouchAssociations(actual_touch_associations_map, expected_touch_associations_map)); EXPECT_TRUE(ComparePortAssociations(expected_port_associations_map, tdm->port_associations())); std::string touch_str; EXPECT_TRUE(properties->GetDictionary(base::NumberToString(id2), &property)); EXPECT_TRUE(property->GetInteger(""rotation"", &rotation)); EXPECT_EQ(0, rotation); double display_zoom_2; EXPECT_TRUE(property->GetDouble(""display_zoom_factor"", &display_zoom_2)); EXPECT_NEAR(display_zoom_2, zoom_factor_2, 0.0001); EXPECT_FALSE(property->GetInteger(""insets_top"", &top)); EXPECT_FALSE(property->GetInteger(""insets_left"", &left)); EXPECT_FALSE(property->GetInteger(""insets_bottom"", &bottom)); EXPECT_FALSE(property->GetInteger(""insets_right"", &right)); // Resolution is saved only when the resolution is set // by DisplayManager::SetDisplayMode width = 0; height = 0; EXPECT_FALSE(property->GetInteger(""width"", &width)); EXPECT_FALSE(property->GetInteger(""height"", &height)); display::ManagedDisplayMode mode(gfx::Size(300, 200), 60.0f, false, false, 1.25f /* device_scale_factor */); display_manager()->SetDisplayMode(id2, mode); window_tree_host_manager->SetPrimaryDisplayId(id2); EXPECT_EQ(id2, display::Screen::GetScreen()->GetPrimaryDisplay().id()); EXPECT_TRUE(properties->GetDictionary(base::NumberToString(id1), &property)); width = 0; height = 0; // Internal display shouldn't store its resolution. EXPECT_FALSE(property->GetInteger(""width"", &width)); EXPECT_FALSE(property->GetInteger(""height"", &height)); // External display's resolution must be stored this time because // it's not best. int device_scale_factor = 0; EXPECT_TRUE(properties->GetDictionary(base::NumberToString(id2), &property)); EXPECT_TRUE(property->GetInteger(""width"", &width)); EXPECT_TRUE(property->GetInteger(""height"", &height)); EXPECT_TRUE( property->GetInteger(""device-scale-factor"", &device_scale_factor)); EXPECT_EQ(300, width); EXPECT_EQ(200, height); EXPECT_EQ(1250, device_scale_factor); // The layout is swapped. EXPECT_TRUE(displays->GetDictionary(key, &layout_value)); EXPECT_TRUE(display::JsonToDisplayLayout(*layout_value, &stored_layout)); ASSERT_EQ(1u, stored_layout.placement_list.size()); const display::DisplayPlacement& stored_placement = stored_layout.placement_list[0]; EXPECT_EQ(display::DisplayPlacement::BOTTOM, stored_placement.position); EXPECT_EQ(-10, stored_placement.offset); EXPECT_EQ(id1, stored_placement.display_id); EXPECT_EQ(id2, stored_placement.parent_display_id); EXPECT_EQ(id2, stored_layout.primary_id); std::string primary_id_str; EXPECT_TRUE(layout_value->GetString(kPrimaryIdKey, &primary_id_str)); EXPECT_EQ(base::NumberToString(id2), primary_id_str); display_manager()->SetLayoutForCurrentDisplays( display::test::CreateDisplayLayout(Shell::Get()->display_manager(), display::DisplayPlacement::BOTTOM, 20)); // Test Hardware Mirroring scenario. UpdateDisplay(""1+0-200x200*2,1+0-200x200""); EXPECT_FALSE(display_manager()->IsInSoftwareMirrorMode()); EXPECT_TRUE(display_manager()->IsInHardwareMirrorMode()); EXPECT_TRUE(displays->GetDictionary(key, &layout_value)); EXPECT_TRUE(display::JsonToDisplayLayout(*layout_value, &stored_layout)); EXPECT_EQ(display::DisplayPlacement::BOTTOM, stored_placement.position); EXPECT_EQ(20, stored_placement.offset); EXPECT_EQ(id1, stored_placement.display_id); EXPECT_EQ(id2, stored_placement.parent_display_id); EXPECT_TRUE(properties->GetDictionary(base::NumberToString(id1), &property)); EXPECT_FALSE(property->GetInteger(""width"", &width)); EXPECT_FALSE(property->GetInteger(""height"", &height)); external_display_mirror_info = local_state()->GetList(prefs::kExternalDisplayMirrorInfo); EXPECT_EQ(1U, external_display_mirror_info->GetSize()); // ExternalDisplayInfo stores ID without output index. EXPECT_EQ(base::NumberToString(display::GetDisplayIdWithoutOutputIndex(id2)), external_display_mirror_info->GetList()[0].GetString()); // External display's selected resolution must not change // by mirroring. EXPECT_TRUE(properties->GetDictionary(base::NumberToString(id2), &property)); EXPECT_TRUE(property->GetInteger(""width"", &width)); EXPECT_TRUE(property->GetInteger(""height"", &height)); EXPECT_EQ(300, width); EXPECT_EQ(200, height); // Set new display's selected resolution. display_manager()->RegisterDisplayProperty( display::GetNextSynthesizedDisplayId(id2), display::Display::ROTATE_0, nullptr, gfx::Size(500, 400), 1.0f, 1.0f, 60.f, false); UpdateDisplay(""200x200*2, 600x500#600x500|500x400""); EXPECT_FALSE(display_manager()->IsInMirrorMode()); // Update key as the 2nd display gets new id. id2 = display_manager_test.GetSecondaryDisplay().id(); key = base::NumberToString(id1) + "","" + base::NumberToString(id2); EXPECT_TRUE(displays->GetDictionary(key, &layout_value)); EXPECT_TRUE(display::JsonToDisplayLayout(*layout_value, &stored_layout)); EXPECT_EQ(display::DisplayPlacement::RIGHT, stored_placement.position); EXPECT_EQ(0, stored_placement.offset); EXPECT_EQ(id1, stored_placement.parent_display_id); EXPECT_EQ(id2, stored_placement.display_id); EXPECT_TRUE(layout_value->GetString(kPrimaryIdKey, &primary_id_str)); EXPECT_EQ(base::NumberToString(id1), primary_id_str); // Best resolution should not be saved. EXPECT_TRUE(properties->GetDictionary(base::NumberToString(id2), &property)); EXPECT_FALSE(property->GetInteger(""width"", &width)); EXPECT_FALSE(property->GetInteger(""height"", &height)); // Set yet another new display's selected resolution. display_manager()->RegisterDisplayProperty( display::GetNextSynthesizedDisplayId(id2), display::Display::ROTATE_0, nullptr, gfx::Size(500, 400), 1.0f, 1.0f, 60.f, false); // Disconnect 2nd display first to generate new id for external display. UpdateDisplay(""200x200*2""); UpdateDisplay(""200x200*2, 500x400#600x500|500x400%60.0f""); // Update key as the 2nd display gets new id. id2 = display_manager_test.GetSecondaryDisplay().id(); key = base::NumberToString(id1) + "","" + base::NumberToString(id2); EXPECT_TRUE(displays->GetDictionary(key, &layout_value)); EXPECT_TRUE(display::JsonToDisplayLayout(*layout_value, &stored_layout)); EXPECT_EQ(display::DisplayPlacement::RIGHT, stored_placement.position); EXPECT_EQ(0, stored_placement.offset); EXPECT_TRUE(layout_value->GetString(kPrimaryIdKey, &primary_id_str)); EXPECT_EQ(base::NumberToString(id1), primary_id_str); // External display's selected resolution must be updated. EXPECT_TRUE(properties->GetDictionary(base::NumberToString(id2), &property)); EXPECT_TRUE(property->GetInteger(""width"", &width)); EXPECT_TRUE(property->GetInteger(""height"", &height)); EXPECT_EQ(500, width); EXPECT_EQ(400, height); } TEST_F(DisplayPrefsTest, PreventStore) { LoggedInAsUser(); UpdateDisplay(""400x300#500x400|400x300|300x200""); int64_t id = display::Screen::GetScreen()->GetPrimaryDisplay().id(); // Set display's resolution in single display. It creates the notification and // display preferences should not stored meanwhile. Shell* shell = Shell::Get(); display::ManagedDisplayMode old_mode(gfx::Size(400, 300), 60.0f, false, false); display::ManagedDisplayMode new_mode(gfx::Size(500, 400), 60.0f, false, true); EXPECT_TRUE(shell->resolution_notification_controller() ->PrepareNotificationAndSetDisplayMode( id, old_mode, new_mode, mojom::DisplayConfigSource::kUser, base::OnceClosure())); UpdateDisplay(""500x400#500x400|400x300|300x200""); const base::DictionaryValue* properties = local_state()->GetDictionary(prefs::kDisplayProperties); const base::DictionaryValue* property = nullptr; EXPECT_TRUE(properties->GetDictionary(base::NumberToString(id), &property)); int width = 0, height = 0; EXPECT_FALSE(property->GetInteger(""width"", &width)); EXPECT_FALSE(property->GetInteger(""height"", &height)); // Revert the change. shell->resolution_notification_controller()->RevertResolutionChange(false); base::RunLoop().RunUntilIdle(); // The specified resolution will be stored by SetDisplayMode. Shell::Get()->display_manager()->SetDisplayMode( id, display::ManagedDisplayMode(gfx::Size(300, 200), 60.0f, false, true)); UpdateDisplay(""300x200#500x400|400x300|300x200""); property = nullptr; EXPECT_TRUE(properties->GetDictionary(base::NumberToString(id), &property)); EXPECT_TRUE(property->GetInteger(""width"", &width)); EXPECT_TRUE(property->GetInteger(""height"", &height)); EXPECT_EQ(300, width); EXPECT_EQ(200, height); } TEST_F(DisplayPrefsTest, StoreForSwappedDisplay) { UpdateDisplay(""100x100,200x200""); display::test::DisplayManagerTestApi display_manager_test(display_manager()); int64_t id1 = display::Screen::GetScreen()->GetPrimaryDisplay().id(); int64_t id2 = display_manager_test.GetSecondaryDisplay().id(); LoggedInAsUser(); SwapPrimaryDisplay(); ASSERT_EQ(id1, display_manager_test.GetSecondaryDisplay().id()); std::string key = base::NumberToString(id1) + "","" + base::NumberToString(id2); const base::DictionaryValue* displays = local_state()->GetDictionary(prefs::kSecondaryDisplays); // Initial saved value is swapped. { const base::DictionaryValue* new_value = nullptr; EXPECT_TRUE(displays->GetDictionary(key, &new_value)); display::DisplayLayout stored_layout; EXPECT_TRUE(display::JsonToDisplayLayout(*new_value, &stored_layout)); ASSERT_EQ(1u, stored_layout.placement_list.size()); const display::DisplayPlacement& stored_placement = stored_layout.placement_list[0]; EXPECT_EQ(display::DisplayPlacement::LEFT, stored_placement.position); EXPECT_EQ(0, stored_placement.offset); EXPECT_EQ(id1, stored_placement.display_id); EXPECT_EQ(id2, stored_placement.parent_display_id); EXPECT_EQ(id2, stored_layout.primary_id); } // Updating layout with primary swapped should save the correct value. { display_manager()->SetLayoutForCurrentDisplays( display::test::CreateDisplayLayout(display_manager(), display::DisplayPlacement::TOP, 10)); const base::DictionaryValue* new_value = nullptr; EXPECT_TRUE(displays->GetDictionary(key, &new_value)); display::DisplayLayout stored_layout; EXPECT_TRUE(display::JsonToDisplayLayout(*new_value, &stored_layout)); ASSERT_EQ(1u, stored_layout.placement_list.size()); const display::DisplayPlacement& stored_placement = stored_layout.placement_list[0]; EXPECT_EQ(display::DisplayPlacement::TOP, stored_placement.position); EXPECT_EQ(10, stored_placement.offset); EXPECT_EQ(id1, stored_placement.display_id); EXPECT_EQ(id2, stored_placement.parent_display_id); EXPECT_EQ(id2, stored_layout.primary_id); } // Swapping primary will save the swapped value. { SwapPrimaryDisplay(); const base::DictionaryValue* new_value = nullptr; EXPECT_TRUE(displays->GetDictionary(key, &new_value)); display::DisplayLayout stored_layout; EXPECT_TRUE(displays->GetDictionary(key, &new_value)); EXPECT_TRUE(display::JsonToDisplayLayout(*new_value, &stored_layout)); ASSERT_EQ(1u, stored_layout.placement_list.size()); const display::DisplayPlacement& stored_placement = stored_layout.placement_list[0]; EXPECT_EQ(display::DisplayPlacement::BOTTOM, stored_placement.position); EXPECT_EQ(-10, stored_placement.offset); EXPECT_EQ(id2, stored_placement.display_id); EXPECT_EQ(id1, stored_placement.parent_display_id); EXPECT_EQ(id1, stored_layout.primary_id); } } TEST_F(DisplayPrefsTestGuest, DisplayPrefsTestGuest) { WindowTreeHostManager* window_tree_host_manager = Shell::Get()->window_tree_host_manager(); UpdateDisplay(""200x200*2,200x200""); LoggedInAsGuest(); int64_t id1 = display::Screen::GetScreen()->GetPrimaryDisplay().id(); display::test::ScopedSetInternalDisplayId set_internal( Shell::Get()->display_manager(), id1); int64_t id2 = display::test::DisplayManagerTestApi(display_manager()) .GetSecondaryDisplay() .id(); display_manager()->SetLayoutForCurrentDisplays( display::test::CreateDisplayLayout(display_manager(), display::DisplayPlacement::TOP, 10)); const float scale = 1.25f; display_manager()->UpdateZoomFactor(id1, 1.f / scale); window_tree_host_manager->SetPrimaryDisplayId(id2); int64_t new_primary = display::Screen::GetScreen()->GetPrimaryDisplay().id(); window_tree_host_manager->SetOverscanInsets(new_primary, gfx::Insets(10, 11, 12, 13)); display_manager()->SetDisplayRotation(new_primary, display::Display::ROTATE_90, display::Display::RotationSource::USER); // Does not store the preferences locally. EXPECT_FALSE(local_state() ->FindPreference(prefs::kSecondaryDisplays) ->HasUserSetting()); EXPECT_FALSE(local_state() ->FindPreference(prefs::kDisplayProperties) ->HasUserSetting()); // Settings are still notified to the system. display::Screen* screen = display::Screen::GetScreen(); EXPECT_EQ(id2, screen->GetPrimaryDisplay().id()); const display::DisplayPlacement& placement = display_manager()->GetCurrentDisplayLayout().placement_list[0]; EXPECT_EQ(display::DisplayPlacement::BOTTOM, placement.position); EXPECT_EQ(-10, placement.offset); const display::Display& primary_display = screen->GetPrimaryDisplay(); EXPECT_EQ(""178x176"", primary_display.bounds().size().ToString()); EXPECT_EQ(display::Display::ROTATE_90, primary_display.rotation()); const display::ManagedDisplayInfo& info1 = display_manager()->GetDisplayInfo(id1); EXPECT_FLOAT_EQ(1.f / scale, info1.zoom_factor()); const display::ManagedDisplayInfo& info_primary = display_manager()->GetDisplayInfo(new_primary); EXPECT_EQ(display::Display::ROTATE_90, info_primary.GetActiveRotation()); EXPECT_EQ(1.0f, info_primary.zoom_factor()); } // Test case which accepts the boolean value of the // AllowMGSToStoreDisplayProperties policy. When set to True, this policy allows // managed guest session to store display configuration permanently in the local // state. When set to False or unset, the display configuration is not stored in // the local state. class DisplayPrefsPublicAccountTest : public DisplayPrefsTestGuest, public testing::WithParamInterface { public: bool IsMGSAllowedToStoreDisplayProperties() const { return GetParam(); } void SetUp() override { DisplayPrefsTestGuest::SetUp(); UpdateDisplay(""200x200*2,200x200""); local_state()->SetBoolean(prefs::kAllowMGSToStoreDisplayProperties, IsMGSAllowedToStoreDisplayProperties()); } }; TEST_P(DisplayPrefsPublicAccountTest, StoreDisplayPrefsForPublicAccount) { WindowTreeHostManager* window_tree_host_manager = Shell::Get()->window_tree_host_manager(); LoggedInAsPublicAccount(); int64_t id1 = display::Screen::GetScreen()->GetPrimaryDisplay().id(); display::test::ScopedSetInternalDisplayId set_internal( Shell::Get()->display_manager(), id1); int64_t id2 = display::test::DisplayManagerTestApi(display_manager()) .GetSecondaryDisplay() .id(); display_manager()->SetLayoutForCurrentDisplays( display::test::CreateDisplayLayout(display_manager(), display::DisplayPlacement::TOP, 10)); const float scale = 1.25f; display_manager()->UpdateZoomFactor(id1, 1.f / scale); window_tree_host_manager->SetPrimaryDisplayId(id2); const int64_t new_primary = display::Screen::GetScreen()->GetPrimaryDisplay().id(); window_tree_host_manager->SetOverscanInsets(new_primary, gfx::Insets(10, 11, 12, 13)); display_manager()->SetDisplayRotation(new_primary, display::Display::ROTATE_90, display::Display::RotationSource::USER); // Preferences should only be stored if the AllowMGSToStoreDisplayProperties // policy was set to true. EXPECT_EQ(IsMGSAllowedToStoreDisplayProperties(), local_state() ->FindPreference(prefs::kSecondaryDisplays) ->HasUserSetting()); EXPECT_EQ(IsMGSAllowedToStoreDisplayProperties(), local_state() ->FindPreference(prefs::kDisplayProperties) ->HasUserSetting()); // Settings are still notified to the system. display::Screen* screen = display::Screen::GetScreen(); EXPECT_EQ(id2, screen->GetPrimaryDisplay().id()); const display::DisplayPlacement& placement = display_manager()->GetCurrentDisplayLayout().placement_list[0]; EXPECT_EQ(display::DisplayPlacement::BOTTOM, placement.position); EXPECT_EQ(-10, placement.offset); const display::Display& primary_display = screen->GetPrimaryDisplay(); EXPECT_EQ(""178x176"", primary_display.bounds().size().ToString()); EXPECT_EQ(display::Display::ROTATE_90, primary_display.rotation()); const display::ManagedDisplayInfo& info1 = display_manager()->GetDisplayInfo(id1); EXPECT_FLOAT_EQ(1.f / scale, info1.zoom_factor()); const display::ManagedDisplayInfo& info_primary = display_manager()->GetDisplayInfo(new_primary); EXPECT_EQ(display::Display::ROTATE_90, info_primary.GetActiveRotation()); EXPECT_EQ(1.0f, info_primary.zoom_factor()); } INSTANTIATE_TEST_CASE_P(All, DisplayPrefsPublicAccountTest, testing::Bool()); TEST_F(DisplayPrefsTest, StorePowerStateNoLogin) { EXPECT_FALSE(local_state()->HasPrefPath(prefs::kDisplayPowerState)); // Stores display prefs without login, which still stores the power state. display_prefs()->MaybeStoreDisplayPrefs(); EXPECT_TRUE(local_state()->HasPrefPath(prefs::kDisplayPowerState)); } TEST_F(DisplayPrefsTest, StorePowerStateGuest) { EXPECT_FALSE(local_state()->HasPrefPath(prefs::kDisplayPowerState)); LoggedInAsGuest(); display_prefs()->MaybeStoreDisplayPrefs(); EXPECT_TRUE(local_state()->HasPrefPath(prefs::kDisplayPowerState)); } TEST_F(DisplayPrefsTest, StorePowerStateNormalUser) { EXPECT_FALSE(local_state()->HasPrefPath(prefs::kDisplayPowerState)); LoggedInAsUser(); display_prefs()->MaybeStoreDisplayPrefs(); EXPECT_TRUE(local_state()->HasPrefPath(prefs::kDisplayPowerState)); } TEST_F(DisplayPrefsTest, DisplayPowerStateAfterRestart) { display_prefs()->StoreDisplayPowerStateForTest( chromeos::DISPLAY_POWER_INTERNAL_OFF_EXTERNAL_ON); EXPECT_EQ(""internal_off_external_on"", local_state()->GetString(prefs::kDisplayPowerState)); display_configurator()->reset_requested_power_state_for_test(); LoadDisplayPreferences(); EXPECT_EQ(chromeos::DISPLAY_POWER_INTERNAL_OFF_EXTERNAL_ON, display_configurator()->GetRequestedPowerState()); } TEST_F(DisplayPrefsTest, DontSaveAndRestoreAllOff) { display_prefs()->StoreDisplayPowerStateForTest( chromeos::DISPLAY_POWER_INTERNAL_OFF_EXTERNAL_ON); EXPECT_EQ(""internal_off_external_on"", local_state()->GetString(prefs::kDisplayPowerState)); // Don't save ALL_OFF. display_prefs()->StoreDisplayPowerStateForTest( chromeos::DISPLAY_POWER_ALL_OFF); EXPECT_EQ(""internal_off_external_on"", local_state()->GetString(prefs::kDisplayPowerState)); // Don't restore ALL_OFF. local_state()->SetString(prefs::kDisplayPowerState, ""all_off""); display_configurator()->reset_requested_power_state_for_test(); LoadDisplayPreferences(); EXPECT_EQ(base::nullopt, display_configurator()->GetRequestedPowerStateForTest()); } // Tests that display configuration changes caused by TabletModeController // are not saved. TEST_F(DisplayPrefsTest, DontSaveTabletModeControllerRotations) { Shell* shell = Shell::Get(); display::Display::SetInternalDisplayId( display::Screen::GetScreen()->GetPrimaryDisplay().id()); LoggedInAsUser(); // Populate the properties. display_manager()->SetDisplayRotation(display::Display::InternalDisplayId(), display::Display::ROTATE_180, display::Display::RotationSource::USER); // Reset property to avoid rotation lock display_manager()->SetDisplayRotation(display::Display::InternalDisplayId(), display::Display::ROTATE_0, display::Display::RotationSource::USER); // Open up 270 degrees to trigger tablet mode AccelerometerUpdate update; update.Set(ACCELEROMETER_SOURCE_ATTACHED_KEYBOARD, 0.0f, 0.0f, -base::kMeanGravityFloat); update.Set(ACCELEROMETER_SOURCE_SCREEN, 0.0f, base::kMeanGravityFloat, 0.0f); TabletModeController* controller = Shell::Get()->tablet_mode_controller(); controller->OnAccelerometerUpdated(update); EXPECT_TRUE(controller->InTabletMode()); // Trigger 90 degree rotation update.Set(ACCELEROMETER_SOURCE_ATTACHED_KEYBOARD, base::kMeanGravityFloat, 0.0f, 0.0f); update.Set(ACCELEROMETER_SOURCE_SCREEN, base::kMeanGravityFloat, 0.0f, 0.0f); controller->OnAccelerometerUpdated(update); shell->screen_orientation_controller()->OnAccelerometerUpdated(update); EXPECT_EQ(display::Display::ROTATE_90, GetCurrentInternalDisplayRotation()); const base::DictionaryValue* properties = local_state()->GetDictionary(prefs::kDisplayProperties); const base::DictionaryValue* property = nullptr; EXPECT_TRUE(properties->GetDictionary( base::NumberToString(display::Display::InternalDisplayId()), &property)); int rotation = -1; EXPECT_TRUE(property->GetInteger(""rotation"", &rotation)); EXPECT_EQ(display::Display::ROTATE_0, rotation); // Trigger a save, the acceleration rotation should not be saved as the user // rotation. display_prefs()->MaybeStoreDisplayPrefs(); properties = local_state()->GetDictionary(prefs::kDisplayProperties); property = nullptr; EXPECT_TRUE(properties->GetDictionary( base::NumberToString(display::Display::InternalDisplayId()), &property)); rotation = -1; EXPECT_TRUE(property->GetInteger(""rotation"", &rotation)); EXPECT_EQ(display::Display::ROTATE_0, rotation); } // Tests that the rotation state is saved without a user being logged in. TEST_F(DisplayPrefsTest, StoreRotationStateNoLogin) { display::Display::SetInternalDisplayId( display::Screen::GetScreen()->GetPrimaryDisplay().id()); EXPECT_FALSE(local_state()->HasPrefPath(prefs::kDisplayRotationLock)); bool current_rotation_lock = IsRotationLocked(); display_prefs()->StoreDisplayRotationPrefsForTest(GetRotation(), current_rotation_lock); EXPECT_TRUE(local_state()->HasPrefPath(prefs::kDisplayRotationLock)); const base::DictionaryValue* properties = local_state()->GetDictionary(prefs::kDisplayRotationLock); bool rotation_lock; EXPECT_TRUE(properties->GetBoolean(""lock"", &rotation_lock)); EXPECT_EQ(current_rotation_lock, rotation_lock); int orientation; display::Display::Rotation current_rotation = GetCurrentInternalDisplayRotation(); EXPECT_TRUE(properties->GetInteger(""orientation"", &orientation)); EXPECT_EQ(current_rotation, orientation); } // Tests that the rotation state is saved when a guest is logged in. TEST_F(DisplayPrefsTest, StoreRotationStateGuest) { display::Display::SetInternalDisplayId( display::Screen::GetScreen()->GetPrimaryDisplay().id()); EXPECT_FALSE(local_state()->HasPrefPath(prefs::kDisplayRotationLock)); LoggedInAsGuest(); bool current_rotation_lock = IsRotationLocked(); display_prefs()->StoreDisplayRotationPrefsForTest(GetRotation(), current_rotation_lock); EXPECT_TRUE(local_state()->HasPrefPath(prefs::kDisplayRotationLock)); const base::DictionaryValue* properties = local_state()->GetDictionary(prefs::kDisplayRotationLock); bool rotation_lock; EXPECT_TRUE(properties->GetBoolean(""lock"", &rotation_lock)); EXPECT_EQ(current_rotation_lock, rotation_lock); int orientation; display::Display::Rotation current_rotation = GetCurrentInternalDisplayRotation(); EXPECT_TRUE(properties->GetInteger(""orientation"", &orientation)); EXPECT_EQ(current_rotation, orientation); } // Tests that the rotation state is saved when a normal user is logged in. TEST_F(DisplayPrefsTest, StoreRotationStateNormalUser) { display::Display::SetInternalDisplayId( display::Screen::GetScreen()->GetPrimaryDisplay().id()); EXPECT_FALSE(local_state()->HasPrefPath(prefs::kDisplayRotationLock)); LoggedInAsGuest(); bool current_rotation_lock = IsRotationLocked(); display_prefs()->StoreDisplayRotationPrefsForTest(GetRotation(), current_rotation_lock); EXPECT_TRUE(local_state()->HasPrefPath(prefs::kDisplayRotationLock)); const base::DictionaryValue* properties = local_state()->GetDictionary(prefs::kDisplayRotationLock); bool rotation_lock; EXPECT_TRUE(properties->GetBoolean(""lock"", &rotation_lock)); EXPECT_EQ(current_rotation_lock, rotation_lock); int orientation; display::Display::Rotation current_rotation = GetCurrentInternalDisplayRotation(); EXPECT_TRUE(properties->GetInteger(""orientation"", &orientation)); EXPECT_EQ(current_rotation, orientation); } // Tests that rotation state is loaded without a user being logged in, and that // entering tablet mode applies the state. TEST_F(DisplayPrefsTest, LoadRotationNoLogin) { display::Display::SetInternalDisplayId( display::Screen::GetScreen()->GetPrimaryDisplay().id()); ASSERT_FALSE(local_state()->HasPrefPath(prefs::kDisplayRotationLock)); bool initial_rotation_lock = IsRotationLocked(); ASSERT_FALSE(initial_rotation_lock); display::Display::Rotation initial_rotation = GetCurrentInternalDisplayRotation(); ASSERT_EQ(display::Display::ROTATE_0, initial_rotation); display_prefs()->StoreDisplayRotationPrefsForTest(GetRotation(), initial_rotation_lock); ASSERT_TRUE(local_state()->HasPrefPath(prefs::kDisplayRotationLock)); display_prefs()->StoreDisplayRotationPrefsForTest(display::Display::ROTATE_90, true); LoadDisplayPreferences(); bool display_rotation_lock = display_manager()->registered_internal_display_rotation_lock(); bool display_rotation = display_manager()->registered_internal_display_rotation(); EXPECT_TRUE(display_rotation_lock); EXPECT_EQ(display::Display::ROTATE_90, display_rotation); bool rotation_lock = IsRotationLocked(); display::Display::Rotation before_tablet_mode_rotation = GetCurrentInternalDisplayRotation(); // Settings should not be applied until tablet mode activates EXPECT_FALSE(rotation_lock); EXPECT_EQ(display::Display::ROTATE_0, before_tablet_mode_rotation); // Open up 270 degrees to trigger tablet mode AccelerometerUpdate update; update.Set(ACCELEROMETER_SOURCE_ATTACHED_KEYBOARD, 0.0f, 0.0f, -base::kMeanGravityFloat); update.Set(ACCELEROMETER_SOURCE_SCREEN, 0.0f, base::kMeanGravityFloat, 0.0f); TabletModeController* tablet_mode_controller = Shell::Get()->tablet_mode_controller(); tablet_mode_controller->OnAccelerometerUpdated(update); EXPECT_TRUE(tablet_mode_controller->InTabletMode()); bool screen_orientation_rotation_lock = IsRotationLocked(); display::Display::Rotation tablet_mode_rotation = GetCurrentInternalDisplayRotation(); EXPECT_TRUE(screen_orientation_rotation_lock); EXPECT_EQ(display::Display::ROTATE_90, tablet_mode_rotation); } // Tests that rotation lock being set causes the rotation state to be saved. TEST_F(DisplayPrefsTest, RotationLockTriggersStore) { display::Display::SetInternalDisplayId( display::Screen::GetScreen()->GetPrimaryDisplay().id()); ASSERT_FALSE(local_state()->HasPrefPath(prefs::kDisplayRotationLock)); Shell::Get()->screen_orientation_controller()->ToggleUserRotationLock(); EXPECT_TRUE(local_state()->HasPrefPath(prefs::kDisplayRotationLock)); const base::DictionaryValue* properties = local_state()->GetDictionary(prefs::kDisplayRotationLock); bool rotation_lock; EXPECT_TRUE(properties->GetBoolean(""lock"", &rotation_lock)); } TEST_F(DisplayPrefsTest, SaveUnifiedMode) { LoggedInAsUser(); display_manager()->SetUnifiedDesktopEnabled(true); UpdateDisplay(""200x200,100x100""); display::DisplayIdList list = display_manager()->GetCurrentDisplayIdList(); EXPECT_EQ( ""400x200"", display::Screen::GetScreen()->GetPrimaryDisplay().size().ToString()); const base::DictionaryValue* secondary_displays = local_state()->GetDictionary(prefs::kSecondaryDisplays); const base::DictionaryValue* new_value = nullptr; EXPECT_TRUE(secondary_displays->GetDictionary( display::DisplayIdListToString(list), &new_value)); display::DisplayLayout stored_layout; EXPECT_TRUE(display::JsonToDisplayLayout(*new_value, &stored_layout)); EXPECT_TRUE(stored_layout.default_unified); const base::DictionaryValue* displays = local_state()->GetDictionary(prefs::kDisplayProperties); int64_t unified_id = display::Screen::GetScreen()->GetPrimaryDisplay().id(); EXPECT_FALSE( displays->GetDictionary(base::NumberToString(unified_id), &new_value)); display::test::SetDisplayResolution(display_manager(), unified_id, gfx::Size(200, 100)); EXPECT_EQ( ""200x100"", display::Screen::GetScreen()->GetPrimaryDisplay().size().ToString()); EXPECT_FALSE( displays->GetDictionary(base::NumberToString(unified_id), &new_value)); // Mirror mode should remember if the default mode was unified. display_manager()->SetMirrorMode(display::MirrorMode::kNormal, base::nullopt); ASSERT_TRUE(secondary_displays->GetDictionary( display::DisplayIdListToString(list), &new_value)); EXPECT_TRUE(display::JsonToDisplayLayout(*new_value, &stored_layout)); EXPECT_TRUE(stored_layout.default_unified); display_manager()->SetMirrorMode(display::MirrorMode::kOff, base::nullopt); ASSERT_TRUE(secondary_displays->GetDictionary( display::DisplayIdListToString(list), &new_value)); EXPECT_TRUE(display::JsonToDisplayLayout(*new_value, &stored_layout)); EXPECT_TRUE(stored_layout.default_unified); // Exit unified mode. display_manager()->SetDefaultMultiDisplayModeForCurrentDisplays( display::DisplayManager::EXTENDED); ASSERT_TRUE(secondary_displays->GetDictionary( display::DisplayIdListToString(list), &new_value)); EXPECT_TRUE(display::JsonToDisplayLayout(*new_value, &stored_layout)); EXPECT_FALSE(stored_layout.default_unified); } TEST_F(DisplayPrefsTest, RestoreUnifiedMode) { const int64_t first_display_id = 210000001; const int64_t second_display_id = 220000002; display::ManagedDisplayInfo first_display_info = display::CreateDisplayInfo(first_display_id, gfx::Rect(1, 1, 500, 500)); display::ManagedDisplayInfo second_display_info = display::CreateDisplayInfo(second_display_id, gfx::Rect(2, 2, 500, 500)); std::vector display_info_list; display_info_list.emplace_back(first_display_info); display_manager()->OnNativeDisplaysChanged(display_info_list); Shell::Get()->window_tree_host_manager()->SetPrimaryDisplayId( first_display_id); EXPECT_FALSE(display_manager()->IsInUnifiedMode()); EXPECT_FALSE(display_manager()->IsInMirrorMode()); display::DisplayIdList list = display::test::CreateDisplayIdList2(first_display_id, second_display_id); StoreDisplayBoolPropertyForList(list, ""default_unified"", true); StoreDisplayPropertyForList( list, ""primary-id"", std::make_unique(base::NumberToString(first_display_id))); LoadDisplayPreferences(); // Should not restore to unified unless unified desktop is enabled. display_info_list.emplace_back(second_display_info); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_FALSE(display_manager()->IsInUnifiedMode()); // Restored to unified. display_manager()->SetUnifiedDesktopEnabled(true); StoreDisplayBoolPropertyForList(list, ""default_unified"", true); LoadDisplayPreferences(); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_TRUE(display_manager()->IsInUnifiedMode()); // Remove the second display. display_info_list.erase(display_info_list.end() - 1); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_FALSE(display_manager()->IsInUnifiedMode()); // Restored to mirror, then unified. std::set external_display_mirror_info; external_display_mirror_info.emplace( display::GetDisplayIdWithoutOutputIndex(second_display_id)); StoreExternalDisplayMirrorInfo(external_display_mirror_info); StoreDisplayBoolPropertyForList(list, ""default_unified"", true); LoadDisplayPreferences(); display_info_list.emplace_back(second_display_info); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_TRUE(display_manager()->IsInMirrorMode()); display_manager()->SetMirrorMode(display::MirrorMode::kOff, base::nullopt); EXPECT_TRUE(display_manager()->IsInUnifiedMode()); // Remove the second display. display_info_list.erase(display_info_list.end() - 1); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_FALSE(display_manager()->IsInUnifiedMode()); // Sanity check. Restore to extended. external_display_mirror_info.clear(); StoreExternalDisplayMirrorInfo(external_display_mirror_info); StoreDisplayBoolPropertyForList(list, ""default_unified"", false); LoadDisplayPreferences(); display_info_list.emplace_back(second_display_info); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_FALSE(display_manager()->IsInMirrorMode()); EXPECT_FALSE(display_manager()->IsInUnifiedMode()); } TEST_F(DisplayPrefsTest, SaveThreeDisplays) { LoggedInAsUser(); UpdateDisplay(""200x200,200x200,300x300""); display::DisplayIdList list = display_manager()->GetCurrentDisplayIdList(); ASSERT_EQ(3u, list.size()); display::DisplayLayoutBuilder builder(list[0]); builder.AddDisplayPlacement(list[1], list[0], display::DisplayPlacement::RIGHT, 0); builder.AddDisplayPlacement(list[2], list[0], display::DisplayPlacement::BOTTOM, 100); display_manager()->SetLayoutForCurrentDisplays(builder.Build()); const base::DictionaryValue* secondary_displays = local_state()->GetDictionary(prefs::kSecondaryDisplays); const base::DictionaryValue* new_value = nullptr; EXPECT_TRUE(secondary_displays->GetDictionary( display::DisplayIdListToString(list), &new_value)); } TEST_F(DisplayPrefsTest, RestoreThreeDisplays) { LoggedInAsUser(); int64_t id1 = display::Screen::GetScreen()->GetPrimaryDisplay().id(); display::DisplayIdList list = display::test::CreateDisplayIdListN(id1, 3); display::DisplayLayoutBuilder builder(list[0]); builder.AddDisplayPlacement(list[1], list[0], display::DisplayPlacement::LEFT, 0); builder.AddDisplayPlacement(list[2], list[1], display::DisplayPlacement::BOTTOM, 100); display_prefs()->StoreDisplayLayoutPrefForTest(list, *builder.Build()); LoadDisplayPreferences(); UpdateDisplay(""200x200,200x200,300x300""); display::DisplayIdList new_list = display_manager()->GetCurrentDisplayIdList(); ASSERT_EQ(3u, list.size()); ASSERT_EQ(list[0], new_list[0]); ASSERT_EQ(list[1], new_list[1]); ASSERT_EQ(list[2], new_list[2]); EXPECT_EQ(gfx::Rect(0, 0, 200, 200), display_manager()->GetDisplayForId(list[0]).bounds()); EXPECT_EQ(gfx::Rect(-200, 0, 200, 200), display_manager()->GetDisplayForId(list[1]).bounds()); EXPECT_EQ(gfx::Rect(-100, 200, 300, 300), display_manager()->GetDisplayForId(list[2]).bounds()); } TEST_F(DisplayPrefsTest, LegacyTouchCalibrationDataSupport) { UpdateDisplay(""800x600,1200x800""); LoggedInAsUser(); int64_t id = display::Screen::GetScreen()->GetPrimaryDisplay().id(); display::TouchCalibrationData::CalibrationPointPairQuad point_pair_quad = { {std::make_pair(gfx::Point(10, 10), gfx::Point(11, 12)), std::make_pair(gfx::Point(190, 10), gfx::Point(195, 8)), std::make_pair(gfx::Point(10, 90), gfx::Point(12, 94)), std::make_pair(gfx::Point(190, 90), gfx::Point(189, 88))}}; gfx::Size touch_size(200, 150); display::TouchCalibrationData data(point_pair_quad, touch_size); display_prefs()->StoreLegacyTouchDataForTest(id, data); display::TouchDeviceManager* tdm = display_manager()->touch_device_manager(); display::test::TouchDeviceManagerTestApi tdm_test_api(tdm); tdm_test_api.ResetTouchDeviceManager(); display_prefs()->LoadTouchAssociationPreferenceForTest(); const display::TouchDeviceManager::TouchAssociationMap& association_map = tdm->touch_associations(); const display::TouchDeviceIdentifier& fallback_identifier = display::TouchDeviceIdentifier::GetFallbackTouchDeviceIdentifier(); EXPECT_TRUE(association_map.count(fallback_identifier)); EXPECT_TRUE(association_map.at(fallback_identifier).count(id)); EXPECT_EQ(association_map.at(fallback_identifier).at(id).calibration_data, data); int64_t id_2 = display::test::DisplayManagerTestApi(display_manager()) .GetSecondaryDisplay() .id(); gfx::Size touch_size_2(300, 300); display::TouchCalibrationData data_2(point_pair_quad, touch_size_2); const ui::TouchscreenDevice touchdevice_4( 19, ui::InputDeviceType::INPUT_DEVICE_USB, std::string(""test touch device 4""), gfx::Size(231, 416), 1); display::TouchDeviceIdentifier identifier = display::TouchDeviceIdentifier::FromDevice(touchdevice_4); display_manager()->SetTouchCalibrationData(id_2, point_pair_quad, touch_size_2, touchdevice_4); EXPECT_TRUE(tdm->touch_associations().count(identifier)); EXPECT_TRUE(tdm->touch_associations().at(identifier).count(id_2)); EXPECT_EQ(tdm->touch_associations().at(identifier).at(id_2).calibration_data, data_2); tdm_test_api.ResetTouchDeviceManager(); EXPECT_TRUE(tdm->touch_associations().empty()); display_prefs()->LoadTouchAssociationPreferenceForTest(); EXPECT_TRUE(tdm->touch_associations().count(fallback_identifier)); EXPECT_TRUE(tdm->touch_associations().at(fallback_identifier).count(id)); EXPECT_EQ( tdm->touch_associations().at(fallback_identifier).at(id).calibration_data, data); EXPECT_TRUE(tdm->touch_associations().count(identifier)); EXPECT_TRUE(tdm->touch_associations().at(identifier).count(id_2)); EXPECT_EQ(tdm->touch_associations().at(identifier).at(id_2).calibration_data, data_2); } TEST_F(DisplayPrefsTest, ExternalDisplayMirrorInfo) { LoggedInAsUser(); base::CommandLine::ForCurrentProcess()->AppendSwitch( chromeos::switches::kFirstExecAfterBoot); const int64_t internal_display_id = display::test::DisplayManagerTestApi(display_manager()) .SetFirstDisplayAsInternalDisplay(); constexpr int64_t first_display_id = 210000001; constexpr int64_t second_display_id = 220000002; const int64_t first_display_masked_id = display::GetDisplayIdWithoutOutputIndex(first_display_id); const int64_t second_display_masked_id = display::GetDisplayIdWithoutOutputIndex(second_display_id); display::ManagedDisplayInfo first_display_info = display::CreateDisplayInfo(first_display_id, gfx::Rect(1, 1, 500, 500)); display::ManagedDisplayInfo second_display_info = display::CreateDisplayInfo(second_display_id, gfx::Rect(2, 2, 500, 500)); std::vector display_info_list; // There's no external display now. display_info_list.push_back(display::CreateDisplayInfo( internal_display_id, gfx::Rect(0, 0, 100, 100))); display_manager()->OnNativeDisplaysChanged(display_info_list); // Add first display id to the external display mirror info. std::set external_display_mirror_info; external_display_mirror_info.emplace(first_display_masked_id); StoreExternalDisplayMirrorInfo(external_display_mirror_info); LoadDisplayPreferences(); const base::ListValue* pref_external_display_mirror_info = local_state()->GetList(prefs::kExternalDisplayMirrorInfo); EXPECT_EQ(1U, pref_external_display_mirror_info->GetSize()); EXPECT_EQ(base::NumberToString(first_display_masked_id), pref_external_display_mirror_info->GetList()[0].GetString()); // Add first display, mirror mode restores and the external display mirror // info does not change. display_info_list.emplace_back(first_display_info); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_TRUE(display_manager()->IsInMirrorMode()); pref_external_display_mirror_info = local_state()->GetList(prefs::kExternalDisplayMirrorInfo); EXPECT_EQ(1U, pref_external_display_mirror_info->GetSize()); EXPECT_EQ(base::NumberToString(first_display_masked_id), pref_external_display_mirror_info->GetList()[0].GetString()); // Add second display, mirror mode persists and the second display id is added // to the external display mirror info. display_info_list.emplace_back(second_display_info); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_TRUE(display_manager()->IsInMirrorMode()); pref_external_display_mirror_info = local_state()->GetList(prefs::kExternalDisplayMirrorInfo); EXPECT_EQ(2U, pref_external_display_mirror_info->GetSize()); EXPECT_EQ(base::NumberToString(first_display_masked_id), pref_external_display_mirror_info->GetList()[0].GetString()); EXPECT_EQ(base::NumberToString(second_display_masked_id), pref_external_display_mirror_info->GetList()[1].GetString()); // Disconnect all external displays. display_info_list.erase(display_info_list.begin() + 1, display_info_list.end()); display_manager()->OnNativeDisplaysChanged(display_info_list); // Clear external display mirror info and only add second display id to it. external_display_mirror_info.clear(); external_display_mirror_info.emplace(second_display_masked_id); StoreExternalDisplayMirrorInfo(external_display_mirror_info); LoadDisplayPreferences(); pref_external_display_mirror_info = local_state()->GetList(prefs::kExternalDisplayMirrorInfo); EXPECT_EQ(1U, pref_external_display_mirror_info->GetSize()); EXPECT_EQ(base::NumberToString(second_display_masked_id), pref_external_display_mirror_info->GetList()[0].GetString()); // Add first display, mirror mode is off and the external display mirror info // does not change. display_info_list.emplace_back(first_display_info); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_FALSE(display_manager()->IsInMirrorMode()); pref_external_display_mirror_info = local_state()->GetList(prefs::kExternalDisplayMirrorInfo); EXPECT_EQ(1U, pref_external_display_mirror_info->GetSize()); EXPECT_EQ(base::NumberToString(second_display_masked_id), pref_external_display_mirror_info->GetList()[0].GetString()); // Add second display, mirror mode remains off and the second display id is // removed from the external display mirror info. display_info_list.emplace_back(second_display_info); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_FALSE(display_manager()->IsInMirrorMode()); pref_external_display_mirror_info = local_state()->GetList(prefs::kExternalDisplayMirrorInfo); EXPECT_EQ(0U, pref_external_display_mirror_info->GetSize()); } TEST_F(DisplayPrefsTest, ExternalDisplayConnectedBeforeLoadingPrefs) { LoggedInAsUser(); base::CommandLine::ForCurrentProcess()->AppendSwitch( chromeos::switches::kFirstExecAfterBoot); const int64_t internal_display_id = display::test::DisplayManagerTestApi(display_manager()) .SetFirstDisplayAsInternalDisplay(); constexpr int64_t external_display_id = 210000001; display::ManagedDisplayInfo external_display_info = display::CreateDisplayInfo(external_display_id, gfx::Rect(1, 1, 500, 500)); // Both internal and external displays connect before the prefs are loaded. std::vector display_info_list; display_info_list.push_back(display::CreateDisplayInfo( internal_display_id, gfx::Rect(0, 0, 100, 100))); display_info_list.push_back(external_display_info); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_FALSE(display_manager()->IsInMirrorMode()); EXPECT_EQ(2u, display_manager()->num_connected_displays()); // Add external display id to the external display mirror info. std::set external_display_mirror_info; const int64_t external_display_masked_id = display::GetDisplayIdWithoutOutputIndex(external_display_id); external_display_mirror_info.emplace(external_display_masked_id); StoreExternalDisplayMirrorInfo(external_display_mirror_info); // Load the preferences and simulate a native display reconfiguration. Expect // that we are mirroring now. LoadDisplayPreferences(); // Simulate a change in display configuration between loading the prefs, and // reconfiguring after the prefs have been loaded. Make sure that the external // display mirror configs are not overwritten, and the loaded prefs will be // applied. display_manager()->SetMirrorMode(display::MirrorMode::kOff, base::nullopt); display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_TRUE(display_manager()->IsInMirrorMode()); } TEST_F(DisplayPrefsTest, DisplayMixedMirrorMode) { LoggedInAsUser(); const int64_t internal_display_id = display::test::DisplayManagerTestApi(display_manager()) .SetFirstDisplayAsInternalDisplay(); constexpr int64_t first_display_id = 210000001; constexpr int64_t second_display_id = 220000002; std::vector display_info_list; display_info_list.push_back(display::CreateDisplayInfo( internal_display_id, gfx::Rect(0, 0, 100, 100))); display_info_list.push_back( display::CreateDisplayInfo(first_display_id, gfx::Rect(1, 1, 500, 500))); display_info_list.push_back( display::CreateDisplayInfo(second_display_id, gfx::Rect(2, 2, 500, 500))); // Store mixed mirror mode parameters which specify mirroring from the // internal display to the first external display. display::DisplayIdList dst_ids; dst_ids.emplace_back(first_display_id); base::Optional mixed_params( base::in_place, internal_display_id, dst_ids); display_prefs()->StoreDisplayMixedMirrorModeParamsForTest(mixed_params); LoadDisplayPreferences(); // Connect both first and second external display. Mixed mirror mode is // restored. display_manager()->OnNativeDisplaysChanged(display_info_list); EXPECT_TRUE(display_manager()->IsInSoftwareMirrorMode()); EXPECT_EQ(internal_display_id, display_manager()->mirroring_source_id()); display::DisplayIdList destination_ids = display_manager()->GetMirroringDestinationDisplayIdList(); EXPECT_EQ(1U, destination_ids.size()); EXPECT_EQ(first_display_id, destination_ids[0]); // Check the preferences. const base::DictionaryValue* pref_data = local_state()->GetDictionary(prefs::kDisplayMixedMirrorModeParams); EXPECT_EQ(base::NumberToString(internal_display_id), pref_data->FindKey(""mirroring_source_id"")->GetString()); const base::Value* destination_ids_value = pref_data->FindKey(""mirroring_destination_ids""); EXPECT_EQ(1U, destination_ids_value->GetList().size()); EXPECT_EQ(base::NumberToString(first_display_id), destination_ids_value->GetList()[0].GetString()); // Overwrite current mixed mirror mode with a new configuration. (Mirror from // the first external display to the second external display) dst_ids.clear(); dst_ids.emplace_back(second_display_id); base::Optional new_mixed_params( base::in_place, first_display_id, dst_ids); display_manager()->SetMirrorMode(display::MirrorMode::kMixed, new_mixed_params); EXPECT_TRUE(display_manager()->IsInSoftwareMirrorMode()); EXPECT_EQ(first_display_id, display_manager()->mirroring_source_id()); destination_ids = display_manager()->GetMirroringDestinationDisplayIdList(); EXPECT_EQ(1U, destination_ids.size()); EXPECT_EQ(second_display_id, destination_ids[0]); // Check the preferences. pref_data = local_state()->GetDictionary(prefs::kDisplayMixedMirrorModeParams); EXPECT_EQ(base::NumberToString(first_display_id), pref_data->FindKey(""mirroring_source_id"")->GetString()); destination_ids_value = pref_data->FindKey(""mirroring_destination_ids""); EXPECT_EQ(1U, destination_ids_value->GetList().size()); EXPECT_EQ(base::NumberToString(second_display_id), destination_ids_value->GetList()[0].GetString()); // Turn off mirror mode. display_manager()->SetMirrorMode(display::MirrorMode::kOff, base::nullopt); EXPECT_FALSE(display_manager()->IsInMirrorMode()); // Check the preferences. pref_data = local_state()->GetDictionary(prefs::kDisplayMixedMirrorModeParams); EXPECT_TRUE(pref_data->empty()); } } // namespace ash ",16166,True,3338.9990054602536,median " #include ""toonz/tstageobject.h"" // TnzLib includes #include ""toonz/tstageobjecttree.h"" #include ""toonz/tstageobjectspline.h"" #include ""toonz/txsheet.h"" #include ""toonz/observer.h"" #include ""toonz/txshlevelcolumn.h"" #include ""toonz/txshcell.h"" #include ""toonz/stage.h"" #include ""toonz/tcamera.h"" #include ""toonz/doubleparamcmd.h"" #include ""toonz/tpinnedrangeset.h"" // TnzExt includes #include ""ext/plasticskeleton.h"" #include ""ext/plasticskeletondeformation.h"" #include ""ext/plasticdeformerstorage.h"" // TnzCore includes #include ""tstream.h"" #include ""tstroke.h"" #include ""tconvert.h"" #include ""tundo.h"" #include ""tconst.h"" // Qt includes #include // tcg includes #include ""tcg/tcg_function_types.h"" // STD includes #include #include using namespace std; // // Per un problema su alcune macchine, solo Release. // il problema si verifica ruotando gli oggetti sul camera stand // #ifdef _WIN32 #pragma optimize("""", off) #endif TAffine makeRotation(double ang) { return TRotation(ang); } #ifdef _WIN32 #pragma optimize("""", on) #endif DEFINE_CLASS_CODE(TStageObject, 102) //************************************************************************************************ // Local namespace //************************************************************************************************ namespace { enum StageObjectType { NONE = 0, CAMERA = 1, TABLE = 2, PEGBAR = 5, COLUMN = 6 }; const int StageObjectTypeShift = 28; const int StageObjectMaxIndex = ((1 << StageObjectTypeShift) - 1); const int StageObjectIndexMask = ((1 << StageObjectTypeShift) - 1); } // namespace //************************************************************************************************ // TStageObjectParams implementation //************************************************************************************************ TStageObjectParams::TStageObjectParams() : m_spline(0), m_noScaleZ(0) { } //----------------------------------------------------------------------------- TStageObjectParams::TStageObjectParams(TStageObjectParams *data) : m_id(data->m_id), m_parentId(data->m_parentId), m_children(data->m_children), m_keyframes(data->m_keyframes), m_cycleEnabled(data->m_cycleEnabled), m_spline(data->m_spline), m_status(data->m_status), m_handle(data->m_handle), m_parentHandle(data->m_parentHandle), m_x(data->m_x), m_y(data->m_y), m_z(data->m_z), m_so(data->m_so), m_rot(data->m_rot), m_scalex(data->m_scalex), m_scaley(data->m_scaley), m_scale(data->m_scale), m_posPath(data->m_posPath), m_shearx(data->m_shearx), m_sheary(data->m_sheary), m_skeletonDeformation(data->m_skeletonDeformation), m_noScaleZ(data->m_noScaleZ), m_center(data->m_center), m_offset(data->m_offset), m_name(data->m_name), m_isOpened(data->m_isOpened), m_pinnedRangeSet(data->m_pinnedRangeSet->clone()) { } //--------------------------------------------------------------------------- TStageObjectParams::~TStageObjectParams() { delete m_pinnedRangeSet; } //--------------------------------------------------------------------------- TStageObjectParams *TStageObjectParams::clone() { return new TStageObjectParams(this); } //=========================================================================== // Utility Functions //--------------------------------------------------------------------------- TStageObjectId toStageObjectId(string s) { if (s == ""None"") return TStageObjectId::NoneId; else if (s == ""Table"") return TStageObjectId::TableId; else if (isInt(s)) { TStageObjectId id; id.setCode(toInt(s)); return id; } else if (s.length() > 3) { if (s.substr(0, 3) == ""Col"") return TStageObjectId::ColumnId(toInt(s.substr(3)) - 1); else if (s.substr(0, 3) == ""Peg"") return TStageObjectId::PegbarId(toInt(s.substr(3)) - 1); else if (s.length() > 6 && s.substr(0, 6) == ""Camera"") return TStageObjectId::CameraId(toInt(s.substr(6)) - 1); } return TStageObjectId::NoneId; } //----------------------------------------------------------------------------- ostream &operator<<(ostream &out, const TStageObjectId &id) { return out << id.toString(); } //************************************************************************************************ // TStageObjectId implementation //************************************************************************************************ TStageObjectId::TStageObjectId() : m_id(NONE << StageObjectTypeShift) {} //----------------------------------------------------------------------------- TStageObjectId::~TStageObjectId() {} //----------------------------------------------------------------------------- bool TStageObjectId::isCamera() const { return m_id >> StageObjectTypeShift == CAMERA; } //----------------------------------------------------------------------------- bool TStageObjectId::isTable() const { return m_id >> StageObjectTypeShift == TABLE; } //----------------------------------------------------------------------------- bool TStageObjectId::isPegbar() const { return m_id >> StageObjectTypeShift == PEGBAR; } //----------------------------------------------------------------------------- bool TStageObjectId::isColumn() const { return m_id >> StageObjectTypeShift == COLUMN; } //----------------------------------------------------------------------------- const TStageObjectId TStageObjectId::NoneId(NONE << StageObjectTypeShift); //----------------------------------------------------------------------------- const TStageObjectId TStageObjectId::TableId(TABLE << StageObjectTypeShift); //----------------------------------------------------------------------------- const TStageObjectId TStageObjectId::CameraId(int index) { assert(0 <= index && index <= StageObjectMaxIndex); return TStageObjectId(CAMERA << StageObjectTypeShift | index); } //----------------------------------------------------------------------------- const TStageObjectId TStageObjectId::PegbarId(int index) { assert(0 <= index && index <= StageObjectMaxIndex); return TStageObjectId(PEGBAR << StageObjectTypeShift | index); } //----------------------------------------------------------------------------- const TStageObjectId TStageObjectId::ColumnId(int index) { assert(0 <= index && index <= StageObjectMaxIndex); return TStageObjectId(COLUMN << StageObjectTypeShift | index); } //----------------------------------------------------------------------------- string TStageObjectId::toString() const { int index = m_id & StageObjectIndexMask; string shortName; switch (m_id >> StageObjectTypeShift) { case NONE: shortName = ""None""; break; case CAMERA: shortName = ""Camera"" + ::toString(index + 1); break; case TABLE: shortName = ""Table""; break; case PEGBAR: shortName = ""Peg"" + ::toString(index + 1); break; case COLUMN: shortName = ""Col"" + ::toString(index + 1); break; default: shortName = ""BadPegbar""; } return shortName; } //----------------------------------------------------------------------------- int TStageObjectId::getIndex() const { return m_id & StageObjectIndexMask; } //============================================================================= namespace { // TStageObject Utility //----------------------------------------------------------------------------- TDoubleKeyframe withFrame(TDoubleKeyframe k, double frame) { k.m_frame = frame; return k; } //----------------------------------------------------------------------------- bool setKeyframe(const TDoubleParamP ¶m, const TDoubleKeyframe &kf, int frame, const double &easeIn, const double &easeOut) { if (!kf.m_isKeyframe) return false; TDoubleKeyframe kfCopy = kf; kfCopy.m_frame = frame; if (easeIn >= 0.0) kfCopy.m_speedIn = TPointD(-easeIn, kfCopy.m_speedIn.y); if (easeOut >= 0.0) kfCopy.m_speedOut = TPointD(easeOut, kfCopy.m_speedOut.y); param->setKeyframe(kfCopy); return true; } //----------------------------------------------------------------------------- void setkey(const TDoubleParamP ¶m, int frame) { KeyframeSetter setter(param.getPointer(), -1, false); setter.createKeyframe(frame); } //----------------------------------------------------------------------------- void updateUnit(TDoubleParam *param) { for (int i = 0; i < param->getKeyframeCount(); i++) { TDoubleKeyframe k = param->getKeyframe(i); k.m_value /= Stage::inch; param->setKeyframe(i, k); } } //----------------------------------------------------------------------------- string convertTo4InchCenterUnits(string handle) { // per convenzione un handle del tipo 'a'..'z' utilizza // la vecchia convenzione per i centri (4 inch invece di 8) if (handle.length() == 1 && 'A' <= handle[0] && handle[0] <= 'Z' && handle[0] != 'B') return string(1, handle[0] + 'a' - 'A'); else return handle; } //----------------------------------------------------------------------------- TPointD updateDagPosition(const TPointD &pos, const VersionNumber &tnzVersion) { if (tnzVersion < VersionNumber(1, 16)) return TConst::nowhere; return pos; } //----------------------------------------------------------------------------- // Update the passed stage object keyframe and keyframe type specification with // a new keyframe. Returns true if specifications match, false otherwise. bool touchEaseAndCompare(const TDoubleKeyframe &kf, TStageObject::Keyframe &stageKf, TDoubleKeyframe::Type &type) { bool initialization = (type == TDoubleKeyframe::None); if (initialization) type = kf.m_type; if (kf.m_type != type || (kf.m_type != TDoubleKeyframe::SpeedInOut && kf.m_type != TDoubleKeyframe::EaseInOut && (kf.m_prevType != TDoubleKeyframe::None && kf.m_prevType != TDoubleKeyframe::SpeedInOut && kf.m_prevType != TDoubleKeyframe::EaseInOut))) { stageKf.m_easeIn = -1.0; stageKf.m_easeOut = -1.0; return false; } double easeIn = -kf.m_speedIn.x; if (initialization) stageKf.m_easeIn = easeIn; else if (stageKf.m_easeIn != easeIn) stageKf.m_easeIn = -1.0; double easeOut = kf.m_speedOut.x; if (initialization) stageKf.m_easeOut = easeOut; else if (stageKf.m_easeOut != easeOut) stageKf.m_easeOut = -1.0; return true; } //----------------------------------------------------------------------------- } // namespace //----------------------------------------------------------------------------- //************************************************************************************************ // TStageObject::LazyData implementation //************************************************************************************************ TStageObject::LazyData::LazyData() : m_time(-1.0) { } //************************************************************************************************ // TStageObject implementation //************************************************************************************************ TStageObject::TStageObject(TStageObjectTree *tree, TStageObjectId id) : m_tree(tree), m_id(id), m_parent(0), m_name(""""), m_isOpened(false), m_spline(0), m_status(XY), m_x(new TDoubleParam()), m_y(new TDoubleParam()), m_z(new TDoubleParam()), m_so(new TDoubleParam()), m_rot(new TDoubleParam()), m_scalex(new TDoubleParam(1.0)), m_scaley(new TDoubleParam(1.0)), m_scale(new TDoubleParam(1.0)), m_posPath(new TDoubleParam()), m_shearx(new TDoubleParam()), m_sheary(new TDoubleParam()), m_center(), m_offset(), m_cycleEnabled(false), m_handle(""B""), m_parentHandle(""B""), m_dagNodePos(TConst::nowhere), m_camera(0), m_locked(false), m_noScaleZ(0), m_pinnedRangeSet(0), m_ikflag(0), m_groupSelector(-1) { // NOTA: per le unita' di misura controlla anche tooloptions.cpp m_x->setName(""W_EW""); m_x->setMeasureName(""length.x""); m_x->addObserver(this); m_y->setName(""W_NS""); m_y->setMeasureName(""length.y""); m_y->addObserver(this); m_z->setName(""W_Z""); m_z->setMeasureName(id.isCamera() ? ""zdepth.cam"" : ""zdepth""); m_z->addObserver(this); m_so->setName(""W_SO""); m_so->addObserver(this); m_rot->setName(""W_Rotation""); m_rot->setMeasureName(""angle""); m_rot->addObserver(this); m_scalex->setName(""W_ScaleH""); m_scalex->setMeasureName(""scale""); m_scalex->addObserver(this); m_scaley->setName(""W_ScaleV""); m_scaley->setMeasureName(""scale""); m_scaley->addObserver(this); m_scale->setName(""W_Scale""); m_scale->setMeasureName(""scale""); m_scale->addObserver(this); m_shearx->setName(""W_ShearH""); m_shearx->setMeasureName(""shear""); m_shearx->addObserver(this); m_sheary->setName(""W_ShearV""); m_sheary->setMeasureName(""shear""); m_sheary->addObserver(this); m_posPath->setName(""posPath""); m_posPath->setMeasureName(""percentage2""); m_posPath->addObserver(this); m_tree->setGrammar(m_x); m_tree->setGrammar(m_y); m_tree->setGrammar(m_z); m_tree->setGrammar(m_so); m_tree->setGrammar(m_rot); m_tree->setGrammar(m_scalex); m_tree->setGrammar(m_scaley); m_tree->setGrammar(m_scale); m_tree->setGrammar(m_shearx); m_tree->setGrammar(m_sheary); m_tree->setGrammar(m_posPath); if (id.isCamera()) m_camera = new TCamera(); m_pinnedRangeSet = new TPinnedRangeSet(); } //----------------------------------------------------------------------------- TStageObject::~TStageObject() { if (m_spline) { if (m_posPath) m_spline->removeParam(m_posPath.getPointer()); m_spline->release(); } if (m_x) m_x->removeObserver(this); if (m_y) m_y->removeObserver(this); if (m_z) m_z->removeObserver(this); if (m_so) m_so->removeObserver(this); if (m_rot) m_rot->removeObserver(this); if (m_scalex) m_scalex->removeObserver(this); if (m_scaley) m_scaley->removeObserver(this); if (m_scale) m_scale->removeObserver(this); if (m_shearx) m_shearx->removeObserver(this); if (m_sheary) m_sheary->removeObserver(this); if (m_posPath) m_posPath->removeObserver(this); if (m_skeletonDeformation) { PlasticDeformerStorage::instance()->releaseDeformationData(m_skeletonDeformation.getPointer()); m_skeletonDeformation->removeObserver(this); } delete m_camera; delete m_pinnedRangeSet; } //----------------------------------------------------------------------------- const TStageObject::LazyData &TStageObject::lazyData() const { typedef tcg::function Func; return m_lazyData(tcg::bind1st(Func(), *this)); } //----------------------------------------------------------------------------- TStageObject::LazyData &TStageObject::lazyData() { return const_cast(static_cast(*this).lazyData()); } //----------------------------------------------------------------------------- void TStageObject::update(LazyData &ld) const { if (ld.m_time >= 0.0) invalidate(ld); updateKeyframes(ld); } //----------------------------------------------------------------------------- void TStageObject::onChange(const class TParamChange &c) { // Rationale: Since a stage object holds many parameters (or par references), // it may receive multiple notifications at the same time - but it should // actually refresh its data only ONCE for 'em all. // Even worse, the stage object may be notified for EACH touched key of just // one of its parameters. This means this function gets called A LOT. // Thus, we're just SCHEDULING for a data refresh. The actual refresh happens // whenever the scheduled datas are accessed. if (c.m_keyframeChanged) m_lazyData.invalidate(); // Both invalidate placement AND keyframes else invalidate(); // Invalidate placement only } //----------------------------------------------------------------------------- TStageObjectId TStageObject::getId() const { return m_id; } //----------------------------------------------------------------------------- double TStageObject::paramsTime(double t) const { const KeyframeMap &keyframes = lazyData().m_keyframes; if (m_cycleEnabled && keyframes.size() > 1) { int firstT = keyframes.begin()->first; if (t <= firstT) return t; int lastT = keyframes.rbegin()->first; int tRange = lastT - firstT + 1; assert(tRange > 0); int it = tfloor(t); double ft = t - it; return firstT + ((it - firstT) % tRange) + ft; } else return t; } //----------------------------------------------------------------------------- void TStageObject::setName(const std::string &name) { m_name = (name == m_id.toString()) ? std::string() : name; } //----------------------------------------------------------------------------- string TStageObject::getName() const { if (m_name != """") return m_name; if (!m_id.isColumn()) return m_id.toString(); wstring s = L""Col"" + toWideString(m_id.getIndex() + 1); return toString(s); } //----------------------------------------------------------------------------- string TStageObject::getFullName() const { string name = getName(); if (m_id.isColumn()) { if (name.find(""Col"") == 0 && name.length() > 3 && name.find_first_not_of(""0123456789"", 3) == string::npos) return name; else return name + "" ("" + toString(m_id.getIndex() + 1) + "")""; } else return name; } //----------------------------------------------------------------------------- void TStageObject::setParent(const TStageObjectId &parentId) { assert(m_tree); TStageObject *newParent = 0; if (parentId != TStageObjectId::NoneId) { newParent = m_tree->getStageObject(parentId); assert(newParent); // cerco di evitare i cicli TStageObject *p = newParent; while (p->m_parent) { if (p->m_parent->getId() == getId()) return; p = p->m_parent; } } else { if (!m_id.isCamera() && !m_id.isTable()) { newParent = m_tree->getStageObject(TStageObjectId::TableId); assert(newParent); } } if (m_parent) m_parent->m_children.remove(this); m_parent = newParent; if (m_parent) m_parent->m_children.insert(m_parent->m_children.end(), this); invalidate(); #ifndef NDEBUG if (m_id.isCamera()) { } else if (m_id.isTable()) { assert(m_parent == 0); } else if (m_id.isColumn()) { assert(m_parent && (m_parent->m_id.isTable() || m_parent->m_id.isColumn() || m_parent->m_id.isPegbar() || m_parent->m_id.isCamera())); } else if (m_id.isPegbar()) { assert(m_parent && (m_parent->m_id.isTable() || m_parent->m_id.isCamera() || m_parent->m_id.isPegbar())); } else { assert(0); } #endif } //----------------------------------------------------------------------------- void TStageObject::detachFromParent() { if (m_parent) m_parent->m_children.remove(this); m_parent = 0; invalidate(); } //----------------------------------------------------------------------------- void TStageObject::attachChildrenToParent(const TStageObjectId &parentId) { while (!m_children.empty()) { TStageObject *son = *m_children.begin(); if (son) son->setParent(parentId); } } //----------------------------------------------------------------------------- TStageObjectId TStageObject::getParent() const { return m_parent ? m_parent->m_id : TStageObjectId(); } //----------------------------------------------------------------------------- bool TStageObject::isAncestor(TStageObject *stageObject) const { if (!stageObject) return false; if (stageObject == (TStageObject *)m_parent) return true; else if (m_parent == 0) return false; else return m_parent->isAncestor(stageObject); } //----------------------------------------------------------------------------- TStageObjectSpline *TStageObject::getSpline() const { return m_spline; } //----------------------------------------------------------------------------- void TStageObject::doSetSpline(TStageObjectSpline *spline) { TDoubleParam *param = m_posPath.getPointer(); bool uppkEnabled = isUppkEnabled(); if (!spline) { if (uppkEnabled && m_spline) m_spline->removeParam(param); if (m_spline) m_spline->release(); m_spline = 0; enablePath(false); } else { if (m_spline != spline) { if (m_spline && uppkEnabled) m_spline->removeParam(param); if (m_spline) m_spline->release(); m_spline = spline; m_spline->addRef(); if (m_spline && uppkEnabled) m_spline->addParam(param); } if (!isPathEnabled()) enablePath(true); } } //----------------------------------------------------------------------------- void TStageObject::setSpline(TStageObjectSpline *spline) { doSetSpline(spline); TNotifier::instance()->notify(TXsheetChange()); TNotifier::instance()->notify(TStageChange()); invalidate(); } //----------------------------------------------------------------------------- void TStageObject::setStatus(Status status) { if (m_status == status) return; bool oldPathEnabled = isPathEnabled(); bool oldUppkEnabled = isUppkEnabled(); m_status = status; bool pathEnabled = isPathEnabled(); bool uppkEnabled = isUppkEnabled(); if (pathEnabled) { if (!m_spline) doSetSpline(m_tree->createSpline()); else if (oldUppkEnabled != uppkEnabled) { TDoubleParam *param = getParam(T_Path); if (uppkEnabled) m_spline->addParam(param); else m_spline->removeParam(param); } } else { doSetSpline(0); } invalidate(); } //----------------------------------------------------------------------------- void TStageObject::enableAim(bool enabled) { setStatus((Status)((m_status & ~STATUS_MASK) | (enabled ? PATH_AIM : PATH))); } //----------------------------------------------------------------------------- void TStageObject::enablePath(bool enabled) { if (isPathEnabled() != enabled) setStatus(enabled ? PATH : XY); } //----------------------------------------------------------------------------- void TStageObject::enableUppk(bool enabled) { assert(isPathEnabled()); setStatus((Status)((m_status & ~UPPK_MASK) | (enabled ? UPPK_MASK : 0))); } //----------------------------------------------------------------------------- void TStageObject::setCenter(double frame, const TPointD ¢er) { TPointD c = center - getHandlePos(m_handle, (int)frame); TAffine aff = computeLocalPlacement(frame); TPointD delta = aff * c - aff * m_center; m_center = c; m_offset += delta; invalidate(); } //----------------------------------------------------------------------------- TPointD TStageObject::getCenter(double frame) const { return m_center + getHandlePos(m_handle, (int)frame); } //----------------------------------------------------------------------------- TPointD TStageObject::getOffset() const { return m_offset; } //----------------------------------------------------------------------------- void TStageObject::setOffset(const TPointD &off) { m_offset = off; invalidate(); } //----------------------------------------------------------------------------- void TStageObject::getCenterAndOffset(TPointD ¢er, TPointD &offset) const { center = m_center; offset = m_offset; } //----------------------------------------------------------------------------- void TStageObject::setCenterAndOffset(const TPointD ¢er, const TPointD &offset) { m_center = center; m_offset = offset; invalidate(); } //----------------------------------------------------------------------------- void TStageObject::setHandle(const std::string &s) { m_handle = s; if (!s.empty() && s[0] == 'H') m_offset = m_center = TPointD(); invalidate(); } //----------------------------------------------------------------------------- void TStageObject::setParentHandle(const std::string &s) { m_parentHandle = s; invalidate(); } //----------------------------------------------------------------------------- TPointD TStageObject::getHandlePos(string handle, int row) const { double unit = 8; if (handle == """") return TPointD(); else if (handle.length() > 1 && handle[0] == 'H') return m_tree->getHandlePos(m_id, handle, row); else if (handle.length() == 1 && 'A' <= handle[0] && handle[0] <= 'Z') return TPointD(unit * (handle[0] - 'B'), 0); else if (handle.length() == 1 && 'a' <= handle[0] && handle[0] <= 'z') return TPointD(0.5 * unit * (handle[0] - 'b'), 0); else return TPointD(0, 0); } //----------------------------------------------------------------------------- bool TStageObject::isKeyframe(int frame) const { const KeyframeMap &keyframes = lazyData().m_keyframes; return keyframes.find(frame) != keyframes.end(); } //----------------------------------------------------------------------------- bool TStageObject::is52FullKeyframe(int frame) const { return m_rot->isKeyframe(frame) && m_x->isKeyframe(frame) && m_y->isKeyframe(frame) && m_z->isKeyframe(frame) && m_posPath->isKeyframe(frame) && m_scalex->isKeyframe(frame) && m_scaley->isKeyframe(frame) && m_shearx->isKeyframe(frame) && m_sheary->isKeyframe(frame); } //----------------------------------------------------------------------------- bool TStageObject::isFullKeyframe(int frame) const { return m_rot->isKeyframe(frame) && m_x->isKeyframe(frame) && m_y->isKeyframe(frame) && m_z->isKeyframe(frame) && m_so->isKeyframe(frame) && m_posPath->isKeyframe(frame) && m_scalex->isKeyframe(frame) && m_scaley->isKeyframe(frame) && m_scale->isKeyframe(frame) && m_shearx->isKeyframe(frame) && m_sheary->isKeyframe(frame); } //----------------------------------------------------------------------------- TStageObject::Keyframe TStageObject::getKeyframe(int frame) const { const KeyframeMap &keyframes = lazyData().m_keyframes; std::map::const_iterator it; it = keyframes.find(frame); if (it == keyframes.end()) { TStageObject::Keyframe k; k.m_channels[TStageObject::T_Angle] = m_rot->getValue(frame); k.m_channels[TStageObject::T_X] = m_x->getValue(frame); k.m_channels[TStageObject::T_Y] = m_y->getValue(frame); k.m_channels[TStageObject::T_Z] = m_z->getValue(frame); k.m_channels[TStageObject::T_SO] = m_so->getValue(frame); k.m_channels[TStageObject::T_ScaleX] = m_scalex->getValue(frame); k.m_channels[TStageObject::T_ScaleY] = m_scaley->getValue(frame); k.m_channels[TStageObject::T_Scale] = m_scale->getValue(frame); k.m_channels[TStageObject::T_Path] = m_posPath->getValue(frame); k.m_channels[TStageObject::T_ShearX] = m_shearx->getValue(frame); k.m_channels[TStageObject::T_ShearY] = m_sheary->getValue(frame); if (m_skeletonDeformation) m_skeletonDeformation->getKeyframeAt(frame, k.m_skeletonKeyframe); k.m_isKeyframe = false; return k; } else return it->second; } //----------------------------------------------------------------------------- void TStageObject::setKeyframeWithoutUndo(int frame, const TStageObject::Keyframe &k) { KeyframeMap &keyframes = lazyData().m_keyframes; bool keyWasSet = false; keyWasSet = ::setKeyframe(m_rot, k.m_channels[TStageObject::T_Angle], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; keyWasSet = ::setKeyframe(m_x, k.m_channels[TStageObject::T_X], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; keyWasSet = ::setKeyframe(m_y, k.m_channels[TStageObject::T_Y], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; keyWasSet = ::setKeyframe(m_z, k.m_channels[TStageObject::T_Z], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; keyWasSet = ::setKeyframe(m_so, k.m_channels[TStageObject::T_SO], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; keyWasSet = ::setKeyframe(m_posPath, k.m_channels[TStageObject::T_Path], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; keyWasSet = ::setKeyframe(m_scalex, k.m_channels[TStageObject::T_ScaleX], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; keyWasSet = ::setKeyframe(m_scaley, k.m_channels[TStageObject::T_ScaleY], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; keyWasSet = ::setKeyframe(m_scale, k.m_channels[TStageObject::T_Scale], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; keyWasSet = ::setKeyframe(m_shearx, k.m_channels[TStageObject::T_ShearX], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; keyWasSet = ::setKeyframe(m_sheary, k.m_channels[TStageObject::T_ShearY], frame, k.m_easeIn, k.m_easeOut) || keyWasSet; if (m_skeletonDeformation) keyWasSet = m_skeletonDeformation->setKeyframe(k.m_skeletonKeyframe, frame, k.m_easeIn, k.m_easeOut) || keyWasSet; if (keyWasSet) keyframes[frame] = k; invalidate(); } //----------------------------------------------------------------------------- void TStageObject::setKeyframeWithoutUndo(int frame) { if (isFullKeyframe(frame)) return; setkey(m_x, frame); setkey(m_y, frame); setkey(m_z, frame); setkey(m_so, frame); setkey(m_posPath, frame); setkey(m_rot, frame); setkey(m_scalex, frame); setkey(m_scaley, frame); setkey(m_scale, frame); setkey(m_shearx, frame); setkey(m_sheary, frame); // Plastic keys are currently not *created* by xsheet commands. /*if(m_skeletonDeformation) { const PlasticSkeleton* skeleton = m_skeletonDeformation->skeleton(); const tcg::list& vertices = skeleton->vertices(); tcg::list::const_iterator vt, vEnd(vertices.end()); for(vt = vertices.begin(); vt != vertices.end(); ++vt) { SkVD* vd = m_skeletonDeformation->vertexDeformation(vt->name()); assert(vd); for(int p=0; pm_params[p], frame); } }*/ } //----------------------------------------------------------------------------- void TStageObject::removeKeyframeWithoutUndo(int frame) { KeyframeMap &keyframes = lazyData().m_keyframes; double &time = lazyData().m_time; if (!isKeyframe(frame)) return; keyframes.erase(frame); m_rot->deleteKeyframe(frame); m_x->deleteKeyframe(frame); m_y->deleteKeyframe(frame); m_z->deleteKeyframe(frame); m_so->deleteKeyframe(frame); m_scalex->deleteKeyframe(frame); m_scaley->deleteKeyframe(frame); m_scale->deleteKeyframe(frame); m_posPath->deleteKeyframe(frame); m_shearx->deleteKeyframe(frame); m_sheary->deleteKeyframe(frame); if (m_skeletonDeformation) m_skeletonDeformation->deleteKeyframe(frame); time = -1; if ((int)keyframes.size() < 2) m_cycleEnabled = false; invalidate(); } //----------------------------------------------------------------------------- bool TStageObject::moveKeyframe(int dst, int src) { assert(dst != src); if (isKeyframe(dst) || !isKeyframe(src)) return false; setKeyframeWithoutUndo(dst, getKeyframe(src)); removeKeyframeWithoutUndo(src); assert(isKeyframe(dst)); assert(!isKeyframe(src)); invalidate(); return true; } //----------------------------------------------------------------------------- bool TStageObject::canMoveKeyframes(std::set &frames, int delta) { if (delta == 0) return false; std::set::iterator it; for (it = frames.begin(); it != frames.end(); ++it) { int f = *it; if (!isKeyframe(f)) return false; f += delta; if (f < 0) return false; if (frames.find(f) == frames.end() && isKeyframe(f)) return false; } return true; } //----------------------------------------------------------------------------- bool TStageObject::moveKeyframes(std::set &frames, int delta) { if (!canMoveKeyframes(frames, delta)) return false; if (delta < 0) { std::set::iterator it; for (it = frames.begin(); it != frames.end(); ++it) { bool ret = moveKeyframe(*it + delta, *it); assert(ret); } } else { std::set::reverse_iterator ti; for (ti = frames.rbegin(); ti != frames.rend(); ++ti) { bool ret = moveKeyframe(*ti + delta, *ti); assert(ret); } } return true; } //----------------------------------------------------------------------------- void TStageObject::getKeyframes(KeyframeMap &keyframes) const { keyframes = lazyData().m_keyframes; } //----------------------------------------------------------------------------- bool TStageObject::getKeyframeRange(int &r0, int &r1) const { const KeyframeMap &keyframes = lazyData().m_keyframes; if (keyframes.empty()) { r0 = 0; r1 = -1; return false; } r0 = keyframes.begin()->first; r1 = keyframes.rbegin()->first; return true; } //----------------------------------------------------------------------------- bool TStageObject::getKeyframeSpan(int row, int &r0, double &ease0, int &r1, double &ease1) const { const KeyframeMap &keyframes = lazyData().m_keyframes; KeyframeMap::const_iterator it = keyframes.lower_bound(row); if (it == keyframes.end() || it == keyframes.begin() || it->first == row) { r0 = 0; r1 = -1; ease0 = ease1 = 0; return false; } r1 = it->first; ease1 = it->second.m_easeIn; --it; r0 = it->first; ease0 = it->second.m_easeOut; return true; } //----------------------------------------------------------------------------- void TStageObject::setParam(Channel type, double frame, double val) { assert(0); } //----------------------------------------------------------------------------- double TStageObject::getParam(Channel type, double frame) const { switch (type) { case T_Angle: return m_rot->getValue(frame); case T_X: return m_x->getValue(frame); case T_Y: return m_y->getValue(frame); case T_Z: return m_z->getValue(frame); case T_SO: return m_so->getValue(frame); case T_ScaleX: return m_scalex->getValue(frame); case T_ScaleY: return m_scaley->getValue(frame); case T_Scale: return m_scale->getValue(frame); case T_Path: return m_posPath->getValue(frame); case T_ShearX: return m_shearx->getValue(frame); case T_ShearY: return m_sheary->getValue(frame); default: assert(false); return 0; } } //----------------------------------------------------------------------------- TDoubleParam *TStageObject::getParam(Channel channel) const { switch (channel) { case T_X: return m_x.getPointer(); case T_Y: return m_y.getPointer(); case T_Z: return m_z.getPointer(); case T_SO: return m_so.getPointer(); case T_Angle: return m_rot.getPointer(); case T_Path: return m_posPath.getPointer(); case T_ScaleX: return m_scalex.getPointer(); case T_ScaleY: return m_scaley.getPointer(); case T_Scale: return m_scale.getPointer(); case T_ShearX: return m_shearx.getPointer(); case T_ShearY: return m_sheary.getPointer(); default: return 0; } } //----------------------------------------------------------------------------- PlasticSkeletonDeformationP TStageObject::getPlasticSkeletonDeformation() const { return m_skeletonDeformation; } //----------------------------------------------------------------------------- void TStageObject::setPlasticSkeletonDeformation(const PlasticSkeletonDeformationP &sd) { if (m_skeletonDeformation == sd) return; if (m_skeletonDeformation) { PlasticDeformerStorage::instance()->releaseDeformationData(m_skeletonDeformation.getPointer()); m_skeletonDeformation->setGrammar(0); m_skeletonDeformation->removeObserver(this); } m_skeletonDeformation = sd; if (m_skeletonDeformation) { m_skeletonDeformation->setGrammar(m_tree->getGrammar()); m_skeletonDeformation->addObserver(this); } } //----------------------------------------------------------------------------- TStageObject *TStageObject::clone() { assert(m_tree); TStageObjectId pegId = getId(); TStageObjectId newPegId = TStageObjectId::NoneId; int newIndex = pegId.getIndex(); if (pegId.isCamera()) { while ((m_tree->getStageObject(TStageObjectId::CameraId(newIndex), false) != 0L) || (pegId.getIndex() == newIndex)) ++newIndex; newPegId = TStageObjectId::CameraId(newIndex); } else if (pegId.isColumn()) { while ((m_tree->getStageObject(TStageObjectId::ColumnId(newIndex), false) != 0L) || (pegId.getIndex() == newIndex)) ++newIndex; newPegId = TStageObjectId::ColumnId(newIndex); } else if (pegId.isPegbar()) { while ((m_tree->getStageObject(TStageObjectId::PegbarId(newIndex), false) != 0L) || (pegId.getIndex() == newIndex)) ++newIndex; newPegId = TStageObjectId::PegbarId(newIndex); } else { assert(!""Unknown stage object type""); return 0L; } assert(newPegId != TStageObjectId::NoneId); assert(newIndex >= 0); assert(newPegId.getIndex() != pegId.getIndex()); // aggiunge lo stage object clonato nel stage object tree TStageObject *clonedPeg = m_tree->getStageObject(newPegId, true); TStageObject *cloned = clonedPeg; assert(cloned); assert(cloned->m_tree == m_tree); KeyframeMap &keyframes = lazyData().m_keyframes; KeyframeMap &clonedKeyframes = cloned->lazyData().m_keyframes; std::map::iterator itKf = keyframes.begin(); for (; itKf != keyframes.end(); ++itKf) { clonedKeyframes.insert(make_pair( itKf->first, itKf->second)); } cloned->m_cycleEnabled = m_cycleEnabled; cloned->lazyData().m_time = lazyData().m_time; cloned->m_localPlacement = m_localPlacement; cloned->m_absPlacement = m_absPlacement; cloned->m_status = m_status; cloned->doSetSpline(m_spline); cloned->m_x = static_cast(m_x->clone()); cloned->m_y = static_cast(m_y->clone()); cloned->m_z = static_cast(m_z->clone()); cloned->m_so = static_cast(m_so->clone()); cloned->m_rot = static_cast(m_rot->clone()); cloned->m_scalex = static_cast(m_scalex->clone()); cloned->m_scaley = static_cast(m_scaley->clone()); cloned->m_scale = static_cast(m_scale->clone()); cloned->m_posPath = static_cast(m_posPath->clone()); cloned->m_shearx = static_cast(m_shearx->clone()); cloned->m_sheary = static_cast(m_sheary->clone()); if (m_skeletonDeformation) cloned->m_skeletonDeformation = new PlasticSkeletonDeformation(*m_skeletonDeformation); cloned->m_noScaleZ = m_noScaleZ; cloned->m_center = m_center; cloned->m_offset = m_offset; cloned->m_name = m_name; cloned->m_dagNodePos = m_dagNodePos; return cloned; } //----------------------------------------------------------------------------- bool TStageObject::isCycleEnabled() const { return m_cycleEnabled; } //----------------------------------------------------------------------------- void TStageObject::enableCycle(bool on) { m_cycleEnabled = on; } //----------------------------------------------------------------------------- TStageObject *TStageObject::findRoot(double frame) const { if (!m_parent) return NULL; TStageObject *parent = m_parent; while (parent->m_parent && parent->lazyData().m_time != frame) parent = parent->m_parent; return parent; } //----------------------------------------------------------------------------- TStageObject *TStageObject::getPinnedDescendant(int frame) { if (getPinnedRangeSet()->isPinned(frame)) return this; for (list::iterator it = m_children.begin(); it != m_children.end(); ++it) { TStageObject *child = *it; if (child->getPinnedRangeSet()->isPinned(frame)) return child; TStageObject *pinned = child->getPinnedDescendant(frame); if (pinned) return pinned; } return 0; } //----------------------------------------------------------------------------- TAffine TStageObject::computeIkRootOffset(int t) { if (m_ikflag > 0) return TAffine(); // get normal movement (which will be left-multiplied to the IK-part) setStatus(XY); invalidate(); TAffine basePlacement = getPlacement(t); setStatus(IK); invalidate(); TStageObject *foot = getPinnedDescendant(t); if (foot == 0) { foot = this; setStatus(XY); } m_ikflag++; invalidate(); TAffine placement = foot->getPlacement(t).inv(); int t0 = 0; const TPinnedRangeSet::Range *range = foot->getPinnedRangeSet()->getRange(t); if (range) t0 = range->first; while (t0 > 0) { TStageObject *oldFoot = getPinnedDescendant(t0 - 1); if (oldFoot == 0) break; // oldFoot = this; assert(oldFoot != foot); TAffine changeFootAff = oldFoot->getPlacement(t0).inv() * foot->getPlacement(t0); placement = changeFootAff * placement; foot = oldFoot; range = oldFoot->getPinnedRangeSet()->getRange(t0 - 1); t0 = 0; if (range) t0 = range->first; } m_ikflag--; invalidate(); placement = foot->getPinnedRangeSet()->getPlacement() * placement; return basePlacement * placement; } //----------------------------------------------------------------------------- /* inline double getPosPathAtCP(const TStroke* path, int cpIndex) { int n = path->getControlPointCount(); return path->getLengthAtControlPoint(tcrop(cpIndex*4,0,n-1)); } //----------------------------------------------------------------------------- */ TAffine TStageObject::computeLocalPlacement(double frame) { frame = paramsTime(frame); if (lazyData().m_time != frame) { double sc = m_scale->getValue(frame); double sx = sc * m_scalex->getValue(frame); double sy = sc * m_scaley->getValue(frame); double ang = m_rot->getValue(frame); double shx = m_shearx->getValue(frame); double shy = m_sheary->getValue(frame); TPointD position; double posPath = 0; switch (m_status & STATUS_MASK) { case XY: position.x = m_x->getValue(frame) * Stage::inch; position.y = m_y->getValue(frame) * Stage::inch; break; case PATH: assert(m_spline); assert(m_spline->getStroke()); posPath = m_spline->getStroke()->getLength() * m_posPath->getValue(frame) * 0.01; position = m_spline->getStroke()->getPointAtLength(posPath); break; case PATH_AIM: assert(m_spline); assert(m_spline->getStroke()); posPath = m_spline->getStroke()->getLength() * m_posPath->getValue(frame) * 0.01; position = m_spline->getStroke()->getPointAtLength(posPath); if (m_spline->getStroke()->getLength() > 1e-5) ang += rad2degree(atan(m_spline->getStroke()->getSpeedAtLength(posPath))); break; case IK: return computeIkRootOffset(frame); break; } TAffine shear(1, shx, 0, shy, 1, 0); TPointD handlePos = getHandlePos(m_handle, (int)frame); TPointD center = (m_center + handlePos) * Stage::inch; TPointD pos = m_offset; if (m_parent) pos += m_parent->getHandlePos(m_parentHandle, (int)frame); pos = pos * Stage::inch + position; m_localPlacement = TTranslation(pos) * makeRotation(ang) * shear * TScale(sx, sy) * TTranslation(-center); } return m_localPlacement; } //----------------------------------------------------------------------------- TAffine TStageObject::getPlacement(double t) { double &time = lazyData().m_time; if (time == t) return m_absPlacement; if (time != -1) { if (!m_parent) invalidate(); else findRoot(t)->invalidate(); } double tt = paramsTime(t); TAffine place; if (m_parent) place = m_parent->getPlacement(t) * computeLocalPlacement(tt); else place = computeLocalPlacement(tt); m_absPlacement = place; time = t; return place; } //----------------------------------------------------------------------------- double TStageObject::getZ(double t) { double tt = paramsTime(t); if (m_parent) return m_parent->getZ(t) + m_z->getValue(tt); else return m_z->getValue(tt); } //----------------------------------------------------------------------------- double TStageObject::getSO(double t) { double tt = paramsTime(t); if (m_parent) return m_parent->getSO(t) + m_so->getValue(tt); else return m_so->getValue(tt); } //----------------------------------------------------------------------------- double TStageObject::getGlobalNoScaleZ() const { return m_parent ? m_parent->getGlobalNoScaleZ() + m_noScaleZ : m_noScaleZ; } //----------------------------------------------------------------------------- double TStageObject::getNoScaleZ() const { return m_noScaleZ; } //----------------------------------------------------------------------------- void TStageObject::setNoScaleZ(double noScaleZ) { if (m_noScaleZ == noScaleZ) return; m_noScaleZ = noScaleZ; invalidate(); } //----------------------------------------------------------------------------- void TStageObject::invalidate(LazyData &ld) const { // Since this is an invalidation function, access to the invalidable data should // not trigger a data update ld.m_time = -1; std::list::const_iterator cit = m_children.begin(); for (; cit != m_children.end(); ++cit) (*cit)->invalidate(); } //----------------------------------------------------------------------------- void TStageObject::invalidate() { invalidate(m_lazyData(tcg::direct_access)); } //----------------------------------------------------------------------------- TAffine TStageObject::getParentPlacement(double t) const { return m_parent ? m_parent->getPlacement(t) : TAffine(); } //----------------------------------------------------------------------------- // Rebuild the keyframes map void TStageObject::updateKeyframes(LazyData &ld) const { KeyframeMap &keyframes = ld.m_keyframes; // Clear the map keyframes.clear(); // Gather all sensible parameters in a vector std::vector params; if (m_status == XY) { params.push_back(m_x.getPointer()); params.push_back(m_y.getPointer()); } else { params.push_back(m_posPath.getPointer()); } params.push_back(m_z.getPointer()); params.push_back(m_so.getPointer()); params.push_back(m_rot.getPointer()); params.push_back(m_scalex.getPointer()); params.push_back(m_scaley.getPointer()); params.push_back(m_scale.getPointer()); params.push_back(m_shearx.getPointer()); params.push_back(m_sheary.getPointer()); if (m_skeletonDeformation) { params.push_back(m_skeletonDeformation->skeletonIdsParam().getPointer()); // Add Plastic Skeleton params too SkD::vd_iterator vdt, vdEnd; m_skeletonDeformation->vertexDeformations(vdt, vdEnd); for (; vdt != vdEnd; ++vdt) { const std::pair &vd = *vdt; for (int p = 0; p < SkVD::PARAMS_COUNT; ++p) params.push_back(vd.second->m_params[p].getPointer()); } } // Scan each parameter for a key frame - add each in a set std::set frames; int p, pCount = params.size(); for (p = 0; p < pCount; ++p) { TDoubleParam *param = params[p]; int k, kCount = param->getKeyframeCount(); for (k = 0; k < kCount; ++k) { const TDoubleKeyframe &kf = param->getKeyframe(k); frames.insert((int)kf.m_frame); } } // Traverse said set and build a TStageObject keyframe for each found instant std::set::iterator ft, fEnd(frames.end()); for (ft = frames.begin(); ft != fEnd; ++ft) { int f = *ft; // Add values TStageObject::Keyframe stageKf; stageKf.m_channels[TStageObject::T_Angle] = m_rot->getKeyframeAt(f); stageKf.m_channels[TStageObject::T_X] = m_x->getKeyframeAt(f); stageKf.m_channels[TStageObject::T_Y] = m_y->getKeyframeAt(f); stageKf.m_channels[TStageObject::T_Z] = m_z->getKeyframeAt(f); stageKf.m_channels[TStageObject::T_SO] = m_so->getKeyframeAt(f); stageKf.m_channels[TStageObject::T_ScaleX] = m_scalex->getKeyframeAt(f); stageKf.m_channels[TStageObject::T_ScaleY] = m_scaley->getKeyframeAt(f); stageKf.m_channels[TStageObject::T_Scale] = m_scale->getKeyframeAt(f); stageKf.m_channels[TStageObject::T_Path] = m_posPath->getKeyframeAt(f); stageKf.m_channels[TStageObject::T_ShearX] = m_shearx->getKeyframeAt(f); stageKf.m_channels[TStageObject::T_ShearY] = m_sheary->getKeyframeAt(f); if (m_skeletonDeformation) m_skeletonDeformation->getKeyframeAt(f, stageKf.m_skeletonKeyframe); stageKf.m_isKeyframe = true; // Build the stage keyframe's global ease factors stageKf.m_easeIn = -1; stageKf.m_easeOut = -1; TDoubleKeyframe::Type type = TDoubleKeyframe::None; bool easeOk = true; // Start from analyzing standard channels for (int c = 0; easeOk && c < T_ChannelCount; ++c) { const TDoubleKeyframe &kf = stageKf.m_channels[c]; if (!kf.m_isKeyframe) continue; easeOk = touchEaseAndCompare(kf, stageKf, type); } // Finally, check the skeleton deformation keyframes const std::map &vdfs = stageKf.m_skeletonKeyframe.m_vertexKeyframes; std::map::const_iterator vdft, vdfEnd(vdfs.end()); for (vdft = vdfs.begin(); easeOk && vdft != vdfEnd; ++vdft) { for (int p = 0; p < SkVD::PARAMS_COUNT; ++p) { const TDoubleKeyframe &kf = vdft->second.m_keyframes[p]; if (!kf.m_isKeyframe) continue; easeOk = touchEaseAndCompare(kf, stageKf, type); } } keyframes[f] = stageKf; } } //----------------------------------------------------------------------------- void TStageObject::updateKeyframes() { return updateKeyframes(m_lazyData(tcg::direct_access)); } //----------------------------------------------------------------------------- void TStageObject::saveData(TOStream &os) { TStageObjectId parentId = getParent(); std::map attr; attr[""id""] = parentId.toString(); attr[""handle""] = m_handle; attr[""parentHandle""] = m_parentHandle; os.openChild(""parent"", attr); os.closeChild(); if (m_name != """") os.child(""name"") << m_name; os.child(""isOpened"") << (int)m_isOpened; if (isGrouped()) { os.openChild(""groupIds""); int i; for (i = 0; i < m_groupId.size(); i++) os << m_groupId[i]; os.closeChild(); os.openChild(""groupNames""); for (i = 0; i < m_groupName.size(); i++) os << m_groupName[i]; os.closeChild(); } m_pinnedRangeSet->saveData(os); os.child(""center"") << m_center.x << m_center.y << -m_offset.x << -m_offset.y; os.child(""status"") << (int)m_status; if (m_noScaleZ != 0) os.child(""noScaleZ"") << m_noScaleZ; if (m_spline) os.child(""splinep"") << m_spline; if (!m_x->isDefault()) os.child(""x"") << *m_x; if (!m_y->isDefault()) os.child(""y"") << *m_y; if (!m_z->isDefault()) os.child(""z"") << *m_z; if (!m_so->isDefault()) os.child(""so"") << *m_so; if (!m_scalex->isDefault()) os.child(""sx"") << *m_scalex; if (!m_scaley->isDefault()) os.child(""sy"") << *m_scaley; if (!m_scale->isDefault()) os.child(""sc"") << *m_scale; if (!m_rot->isDefault()) os.child(""rot"") << *m_rot; if (!m_posPath->isDefault()) os.child(""pos"") << *m_posPath; if (!m_shearx->isDefault()) os.child(""shx"") << *m_shearx; if (!m_sheary->isDefault()) os.child(""shy"") << *m_sheary; if (m_cycleEnabled) os.child(""cycle"") << 1; if (m_skeletonDeformation) os.child(""plasticSD"") << *m_skeletonDeformation; os.child(""nodePos"") << m_dagNodePos.x << m_dagNodePos.y; if (getId().isCamera()) { os.openChild(""camera""); m_camera->saveData(os); os.closeChild(); /*TDimensionD size = m_camera->getSize(); TDimension res = m_camera->getRes(); bool isXPrevalence = m_camera->isXPrevalence(); os.child(""cameraSize"") << size.lx << size.ly; os.child(""cameraRes"") << res.lx << res.ly; os.child(""xPrevalence"") << (int)isXPrevalence;*/ } } //----------------------------------------------------------------------------- void TStageObject::loadData(TIStream &is) { VersionNumber tnzVersion = is.getVersion(); string tagName; QList groupIds; QList groupNames; KeyframeMap &keyframes = lazyData().m_keyframes; while (is.matchTag(tagName)) { if (tagName == ""parent"") { string parentIdStr = is.getTagAttribute(""id""); string handle = is.getTagAttribute(""handle""); string parentHandle = is.getTagAttribute(""parentHandle""); if (tnzVersion < VersionNumber(1, 15)) { handle = convertTo4InchCenterUnits(handle); parentHandle = convertTo4InchCenterUnits(parentHandle); } if (parentIdStr == """") // vecchio formato is >> parentIdStr; else { } TStageObjectId parentId = toStageObjectId(parentIdStr); if (m_id != TStageObjectId::NoneId && parentId != TStageObjectId::NoneId) { assert(parentId != m_id); setParent(parentId); } if (handle != """") setHandle(handle); if (parentHandle != """") setParentHandle(parentHandle); } else if (tagName == ""center"") { is >> m_center.x >> m_center.y >> m_offset.x >> m_offset.y; m_offset = -m_offset; } else if (tagName == ""name"") is >> m_name; else if (tagName == ""x"") is >> *m_x; else if (tagName == ""y"") is >> *m_y; else if (tagName == ""z"") is >> *m_z; else if (tagName == ""so"") is >> *m_so; else if (tagName == ""rot"") is >> *m_rot; else if (tagName == ""sx"") is >> *m_scalex; else if (tagName == ""sy"") is >> *m_scaley; else if (tagName == ""sc"") is >> *m_scale; else if (tagName == ""shx"") is >> *m_shearx; else if (tagName == ""shy"") is >> *m_sheary; else if (tagName == ""pos"") is >> *m_posPath; else if (tagName == ""posCP"") { TDoubleParam posCP; is >> posCP; } // Ghibli 6.2 release. cfr else if (tagName == ""noScaleZ"") is >> m_noScaleZ; else if (tagName == ""isOpened"") { int v = 0; is >> v; m_isOpened = (bool)v; } else if (tagName == ""pinnedStatus"") { m_pinnedRangeSet->loadData(is); } else if (tagName == ""status"") { int v = 0; is >> v; m_status = (Status)v; } else if (tagName == ""spline"") { TStageObjectSpline *spline = m_tree->createSpline(); is >> *spline; m_spline = spline; m_spline->addRef(); } else if (tagName == ""splinep"") { TPersist *p = 0; is >> p; m_spline = dynamic_cast(p); m_tree->insertSpline(m_spline); m_spline->addRef(); } else if (tagName == ""cycle"") { int dummy; is >> dummy; m_cycleEnabled = true; } else if (tagName == ""nodePos"") { TPointD pos; is >> pos.x >> pos.y; m_dagNodePos = updateDagPosition(pos, tnzVersion); //is >> m_dagNodePos.x >> m_dagNodePos.y; } //***** camera parameters till toonz 6.0 ******** else if (tagName == ""cameraSize"") { TDimensionD size(0, 0); is >> size.lx >> size.ly; if (m_camera) m_camera->setSize(size); } else if (tagName == ""cameraRes"") { TDimension res(0, 0); is >> res.lx >> res.ly; if (m_camera) m_camera->setRes(res); } //***** camera parameters toonz 6.1 ******** november 2009 else if (tagName == ""camera"") m_camera->loadData(is); else if (tagName == ""groupIds"") { int groupId; while (!is.eos()) { is >> groupId; groupIds.push_back(groupId); } } else if (tagName == ""groupNames"") { wstring groupName; while (!is.eos()) { is >> groupName; groupNames.push_back(groupName); } } else if (tagName == ""plasticSD"") { PlasticSkeletonDeformation *sd = new PlasticSkeletonDeformation; is >> *sd; setPlasticSkeletonDeformation(sd); } else throw TException(""TStageObject::loadData. unexpected tag: "" + tagName); is.matchEndTag(); } if (!groupIds.isEmpty()) { assert(groupIds.size() == groupNames.size()); int i; for (i = 0; i < groupIds.size(); i++) { setGroupId(groupIds[i]); setGroupName(groupNames[i]); } } if (tnzVersion < VersionNumber(1, 13)) { updateUnit(m_y.getPointer()); updateUnit(m_x.getPointer()); } if (tnzVersion < VersionNumber(1, 14)) { double factor = 1.0 / Stage::inch; m_center = m_center * factor; m_offset = m_offset * factor; } if (tnzVersion < VersionNumber(1, 16) && !keyframes.empty()) { std::map::iterator itKf = keyframes.begin(); std::set keyframeIndexSet; for (; itKf != keyframes.end(); itKf++) if (is52FullKeyframe(itKf->first)) keyframeIndexSet.insert(itKf->first); std::set::iterator itKfInd = keyframeIndexSet.begin(); for (; itKfInd != keyframeIndexSet.end(); itKfInd++) setkey(m_scale, *itKfInd); } updateKeyframes(); if (m_spline != 0 && isUppkEnabled()) m_spline->addParam(m_posPath.getPointer()); invalidate(); } //----------------------------------------------------------------------------- TStageObjectParams *TStageObject::getParams() const { TStageObjectParams *data = new TStageObjectParams(); data->m_name = m_name; data->m_center = m_center; data->m_noScaleZ = m_noScaleZ; data->m_id = m_id; data->m_parentId = getParent(); data->m_offset = m_offset; data->m_status = m_status; data->m_x = m_x; data->m_y = m_y; data->m_z = m_z; data->m_so = m_so; data->m_rot = m_rot; data->m_scalex = m_scalex; data->m_scaley = m_scaley; data->m_scale = m_scale; data->m_posPath = m_posPath; data->m_shearx = m_shearx; data->m_sheary = m_sheary; data->m_skeletonDeformation = m_skeletonDeformation; data->m_cycleEnabled = m_cycleEnabled; data->m_spline = m_spline; data->m_handle = m_handle; data->m_parentHandle = m_parentHandle; if (m_pinnedRangeSet) data->m_pinnedRangeSet = m_pinnedRangeSet->clone(); return data; } //----------------------------------------------------------------------------- void TStageObject::assignParams(const TStageObjectParams *src, bool doParametersClone) { m_name = src->m_name; m_center = src->m_center; m_noScaleZ = src->m_noScaleZ; m_offset = src->m_offset; m_status = src->m_status; if (m_spline) m_spline->release(); m_spline = src->m_spline; if (m_spline) m_spline->addRef(); if (doParametersClone) { m_x->copy(src->m_x.getPointer()); m_y->copy(src->m_y.getPointer()); m_z->copy(src->m_z.getPointer()); m_so->copy(src->m_so.getPointer()); m_rot->copy(src->m_rot.getPointer()); m_scalex->copy(src->m_scalex.getPointer()); m_scaley->copy(src->m_scaley.getPointer()); m_scale->copy(src->m_scale.getPointer()); m_posPath->copy(src->m_posPath.getPointer()); m_shearx->copy(src->m_shearx.getPointer()); m_sheary->copy(src->m_sheary.getPointer()); if (src->m_skeletonDeformation) setPlasticSkeletonDeformation(new PlasticSkeletonDeformation(*src->m_skeletonDeformation)); } else { m_x = src->m_x.getPointer(); m_x->addObserver(this); m_y = src->m_y.getPointer(); m_y->addObserver(this); m_z = src->m_z.getPointer(); m_z->addObserver(this); m_so = src->m_so.getPointer(); m_so->addObserver(this); m_rot = src->m_rot.getPointer(); m_rot->addObserver(this); m_scalex = src->m_scalex.getPointer(); m_scalex->addObserver(this); m_scaley = src->m_scaley.getPointer(); m_scaley->addObserver(this); m_scale = src->m_scale.getPointer(); m_scale->addObserver(this); m_posPath = src->m_posPath.getPointer(); m_posPath->addObserver(this); m_shearx = src->m_shearx.getPointer(); m_shearx->addObserver(this); m_sheary = src->m_sheary.getPointer(); m_sheary->addObserver(this); m_skeletonDeformation = src->m_skeletonDeformation; if (m_skeletonDeformation) m_skeletonDeformation->addObserver(this); } m_handle = src->m_handle; m_parentHandle = src->m_parentHandle; m_cycleEnabled = src->m_cycleEnabled; if (m_pinnedRangeSet) *m_pinnedRangeSet = *src->m_pinnedRangeSet; updateKeyframes(); if (m_spline && isUppkEnabled()) m_spline->addParam(m_posPath.getPointer()); invalidate(); } //----------------------------------------------------------------------------- // // objectZ e' la posizione dell'oggetto lungo l'asse Z // il default e' 0. valori grandi rappresentano oggetti piu' vicini alla camera // la distanza iniziale fra tavolo e camera e' 1000 // // cameraZ e' la posizione della camera lungo l'asse Z // il default e' 0. valori negativi indicano che la camera si avvicina al tavolo // (che raggiungerebbe per un valore di -1000) // bool TStageObject::perspective(TAffine &aff, const TAffine &cameraAff, double cameraZ, const TAffine &objectAff, double objectZ, double objectNoScaleZ) { TPointD cameraPos(cameraAff.a13, cameraAff.a23); TPointD objectPos(objectAff.a13, objectAff.a23); const double focus = 1000; const double nearPlane = 1; /*-- dzはカメラとオブジェクトの間の距離、focus(=1000)はPegbarをZ軸方向に動かさなかった場合のデフォルト距離 --*/ double dz = focus + cameraZ - objectZ; if (dz < nearPlane) { aff = TAffine(); return false; } double noScaleSc = 1 - objectNoScaleZ / focus; aff = cameraAff * TScale((focus + cameraZ) / dz) * cameraAff.inv() * objectAff * TScale(noScaleSc); return true; } //----------------------------------------------------------------------------- int TStageObject::setGroupId(int value) { m_groupSelector++; m_groupId.insert(m_groupSelector, value); return m_groupSelector; } //----------------------------------------------------------------------------- void TStageObject::setGroupId(int value, int position) { assert(position >= 0 && position <= m_groupId.size()); m_groupId.insert(position, value); if (m_groupSelector + 1 >= position) m_groupSelector++; } //----------------------------------------------------------------------------- int TStageObject::getGroupId() { return m_groupId.isEmpty() || m_groupSelector < 0 || m_groupSelector >= m_groupId.size() ? 0 : m_groupId[m_groupSelector]; } //----------------------------------------------------------------------------- QStack TStageObject::getGroupIdStack() { return m_groupId; } //----------------------------------------------------------------------------- void TStageObject::removeGroupId(int position) { if (!isGrouped()) return; assert(position >= 0 && position <= m_groupId.size()); m_groupId.remove(position); if (m_groupSelector + 1 >= position && m_groupSelector > -1) m_groupSelector--; } //----------------------------------------------------------------------------- int TStageObject::removeGroupId() { m_groupId.remove(m_groupSelector); if (m_groupSelector > -1) m_groupSelector--; return m_groupSelector + 1; } //----------------------------------------------------------------------------- bool TStageObject::isGrouped() { return !m_groupId.isEmpty(); } //----------------------------------------------------------------------------- bool TStageObject::isContainedInGroup(int groupId) { return m_groupId.contains(groupId); } //----------------------------------------------------------------------------- void TStageObject::setGroupName(const wstring &name, int position) { int groupSelector = position < 0 ? m_groupSelector : position; assert(groupSelector >= 0 && groupSelector <= m_groupName.size()); m_groupName.insert(groupSelector, name); } //----------------------------------------------------------------------------- wstring TStageObject::getGroupName(bool fromEditor) { int groupSelector = fromEditor ? m_groupSelector + 1 : m_groupSelector; return m_groupName.isEmpty() || groupSelector < 0 || groupSelector >= m_groupName.size() ? L"""" : m_groupName[groupSelector]; } //----------------------------------------------------------------------------- QStack TStageObject::getGroupNameStack() { return m_groupName; } //----------------------------------------------------------------------------- int TStageObject::removeGroupName(bool fromEditor) { int groupSelector = fromEditor ? m_groupSelector + 1 : m_groupSelector; if (!isGrouped()) return -1; assert(groupSelector >= 0 && groupSelector <= m_groupName.size()); m_groupName.remove(groupSelector); return groupSelector; } //----------------------------------------------------------------------------- void TStageObject::removeGroupName(int position) { int groupSelector = position < 0 ? m_groupSelector : position; assert(groupSelector >= 0 && groupSelector <= m_groupName.size()); m_groupName.remove(groupSelector); } //----------------------------------------------------------------------------- void TStageObject::removeFromAllGroup() { m_groupId.clear(); m_groupName.clear(); m_groupSelector = -1; } //----------------------------------------------------------------------------- void TStageObject::editGroup() { m_groupSelector--; } //----------------------------------------------------------------------------- bool TStageObject::isGroupEditing() { return isGrouped() && m_groupSelector == -1; } //----------------------------------------------------------------------------- void TStageObject::closeEditingGroup(int groupId) { if (!m_groupId.contains(groupId)) return; m_groupSelector = 0; while (m_groupId[m_groupSelector] != groupId && m_groupSelector < m_groupId.size()) m_groupSelector++; } //----------------------------------------------------------------------------- int TStageObject::getEditingGroupId() { if (!isGrouped() || m_groupSelector + 1 >= m_groupId.size()) return -1; return m_groupId[m_groupSelector + 1]; } //----------------------------------------------------------------------------- wstring TStageObject::getEditingGroupName() { if (!isGrouped() || m_groupSelector + 1 >= m_groupName.size()) return L""""; return m_groupName[m_groupSelector + 1]; } ",16194,True,3142.10486749069,median "[[cluster-nodes-stats]] === Nodes stats API ++++ Nodes stats ++++ Returns cluster nodes statistics. [[cluster-nodes-stats-api-request]] ==== {api-request-title} `GET /_nodes/stats` + `GET /_nodes//stats` + `GET /_nodes/stats/` + `GET /_nodes//stats/` + `GET /_nodes/stats//` + `GET /_nodes//stats//` [[cluster-nodes-stats-api-prereqs]] ==== {api-prereq-title} * If the {es} {security-features} are enabled, you must have the `monitor` or `manage` <> to use this API. [[cluster-nodes-stats-api-desc]] ==== {api-description-title} You can use the cluster nodes stats API to retrieve statistics for nodes in a cluster. All the nodes selective options are explained <>. By default, all stats are returned. You can limit the returned information by using metrics. [[cluster-nodes-stats-api-path-params]] ==== {api-path-parms-title} ``:: (Optional, string) Limits the information returned to the specific metrics. A comma-separated list of the following options: + -- `adaptive_selection`:: Statistics about <>. `breaker`:: Statistics about the field data circuit breaker. `discovery`:: Statistics about the discovery. `fs`:: File system information, data path, free disk space, read/write stats. `http`:: HTTP connection information. `indexing_pressure`:: Statistics about the node's indexing load and related rejections. `indices`:: Indices stats about size, document count, indexing and deletion times, search times, field cache size, merges and flushes. `ingest`:: Statistics about ingest preprocessing. `jvm`:: JVM stats, memory pool information, garbage collection, buffer pools, number of loaded/unloaded classes. `os`:: Operating system stats, load average, mem, swap. `process`:: Process statistics, memory consumption, cpu usage, open file descriptors. `thread_pool`:: Statistics about each thread pool, including current size, queue and rejected tasks. `transport`:: Transport statistics about sent and received bytes in cluster communication. -- ``:: (Optional, string) Limit the information returned for `indices` metric to the specific index metrics. It can be used only if `indices` (or `all`) metric is specified. Supported metrics are: + -- * `completion` * `docs` * `fielddata` * `flush` * `get` * `indexing` * `merge` * `query_cache` * `recovery` * `refresh` * `request_cache` * `search` * `segments` * `store` * `translog` * `warmer` -- include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=node-id] [[cluster-nodes-stats-api-query-params]] ==== {api-query-parms-title} include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=completion-fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fielddata-fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=groups] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=level] `types`:: (Optional, string) A comma-separated list of document types for the `indexing` index metric. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=timeoutparms] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=include-segment-file-sizes] [role=""child_attributes""] [[cluster-nodes-stats-api-response-body]] ==== {api-response-body-title} `_nodes`:: (object) Contains statistics about the number of nodes selected by the request. + .Properties of `_nodes` [%collapsible%open] ==== `total`:: (integer) Total number of nodes selected by the request. `successful`:: (integer) Number of nodes that responded successfully to the request. `failed`:: (integer) Number of nodes that rejected the request or failed to respond. If this value is not `0`, a reason for the rejection or failure is included in the response. ==== `cluster_name`:: (string) Name of the cluster. Based on the <> setting. `nodes`:: (object) Contains statistics for the nodes selected by the request. + .Properties of `nodes` [%collapsible%open] ==== ``:: (object) Contains statistics for the node. + .Properties of `` [%collapsible%open] ===== `timestamp`:: (integer) Time the node stats were collected for this response. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `name`:: (string) Human-readable identifier for the node. Based on the <> setting. `transport_address`:: (string) Host and port for the <>, used for internal communication between nodes in a cluster. `host`:: (string) Network host for the node, based on the <> setting. `ip`:: (string) IP address and port for the node. `roles`:: (array of strings) Roles assigned to the node. See <>. `attributes`:: (object) Contains a list of attributes for the node. [[cluster-nodes-stats-api-response-body-indices]] `indices`:: (object) Contains statistics about indices with shards assigned to the node. + .Properties of `indices` [%collapsible%open] ====== `docs`:: (object) Contains statistics about documents across all primary shards assigned to the node. + .Properties of `docs` [%collapsible%open] ======= `count`:: (integer) include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-count] `deleted`:: (integer) include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-deleted] ======= `store`:: (object) Contains statistics about the size of shards assigned to the node. + .Properties of `store` [%collapsible%open] ======= `size`:: (<>) Total size of all shards assigned to the node. `size_in_bytes`:: (integer) Total size, in bytes, of all shards assigned to the node. `reserved`:: (<>) A prediction of how much larger the shard stores on this node will eventually grow due to ongoing peer recoveries, restoring snapshots, and similar activities. A value of `-1b` indicates that this is not available. `reserved_in_bytes`:: (integer) A prediction, in bytes, of how much larger the shard stores on this node will eventually grow due to ongoing peer recoveries, restoring snapshots, and similar activities. A value of `-1` indicates that this is not available. ======= `indexing`:: (object) Contains statistics about indexing operations for the node. + .Properties of `indexing` [%collapsible%open] ======= `index_total`:: (integer) Total number of indexing operations. `index_time`:: (<>) Total time spent performing indexing operations. `index_time_in_millis`:: (integer) Total time in milliseconds spent performing indexing operations. `index_current`:: (integer) Number of indexing operations currently running. `index_failed`:: (integer) Number of failed indexing operations. `delete_total`:: (integer) Total number of deletion operations. `delete_time`:: (<>) Time spent performing deletion operations. `delete_time_in_millis`:: (integer) Time in milliseconds spent performing deletion operations. `delete_current`:: (integer) Number of deletion operations currently running. `noop_update_total`:: (integer) Total number of noop operations. `is_throttled`:: (Boolean) Number of times operations were throttled. `throttle_time`:: (<>) Total time spent throttling operations. `throttle_time_in_millis`:: (integer) Total time in milliseconds spent throttling operations. ======= `get`:: (object) Contains statistics about get operations for the node. + .Properties of `get` [%collapsible%open] ======= `total`:: (integer) Total number of get operations. `getTime`:: (<>) Time spent performing get operations. `time_in_millis`:: (integer) Time in milliseconds spent performing get operations. `exists_total`:: (integer) Total number of successful get operations. `exists_time`:: (<>) Time spent performing successful get operations. `exists_time_in_millis`:: (integer) Time in milliseconds spent performing successful get operations. `missing_total`:: (integer) Total number of failed get operations. `missing_time`:: (<>) Time spent performing failed get operations. `missing_time_in_millis`:: (integer) Time in milliseconds spent performing failed get operations. `current`:: (integer) Number of get operations currently running. ======= `search`:: (object) Contains statistics about search operations for the node. + .Properties of `search` [%collapsible%open] ======= `open_contexts`:: (integer) Number of open search contexts. `query_total`:: (integer) Total number of query operations. `query_time`:: (<>) Time spent performing query operations. `query_time_in_millis`:: (integer) Time in milliseconds spent performing query operations. `query_current`:: (integer) Number of query operations currently running. `fetch_total`:: (integer) Total number of fetch operations. `fetch_time`:: (<>) Time spent performing fetch operations. `fetch_time_in_millis`:: (integer) Time in milliseconds spent performing fetch operations. `fetch_current`:: (integer) Number of fetch operations currently running. `scroll_total`:: (integer) Total number of scroll operations. `scroll_time`:: (<>) Time spent performing scroll operations. `scroll_time_in_millis`:: (integer) Time in milliseconds spent performing scroll operations. `scroll_current`:: (integer) Number of scroll operations currently running. `suggest_total`:: (integer) Total number of suggest operations. `suggest_time`:: (<>) Time spent performing suggest operations. `suggest_time_in_millis`:: (integer) Time in milliseconds spent performing suggest operations. `suggest_current`:: (integer) Number of suggest operations currently running. ======= `merges`:: (object) Contains statistics about merge operations for the node. + .Properties of `merges` [%collapsible%open] ======= `current`:: (integer) Number of merge operations currently running. `current_docs`:: (integer) Number of document merges currently running. `current_size`:: (<>) Memory used performing current document merges. `current_size_in_bytes`:: (integer) Memory, in bytes, used performing current document merges. `total`:: (integer) Total number of merge operations. `total_time`:: (<>) Total time spent performing merge operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing merge operations. `total_docs`:: (integer) Total number of merged documents. `total_size`:: (<>) Total size of document merges. `total_size_in_bytes`:: (integer) Total size of document merges in bytes. `total_stopped_time`:: (<>) Total time spent stopping merge operations. `total_stopped_time_in_millis`:: (integer) Total time in milliseconds spent stopping merge operations. `total_throttled_time`:: (<>) Total time spent throttling merge operations. `total_throttled_time_in_millis`:: (integer) Total time in milliseconds spent throttling merge operations. `total_auto_throttle`:: (<>) Size of automatically throttled merge operations. `total_auto_throttle_in_bytes`:: (integer) Size, in bytes, of automatically throttled merge operations. ======= `refresh`:: (object) Contains statistics about refresh operations for the node. + .Properties of `refresh` [%collapsible%open] ======= `total`:: (integer) Total number of refresh operations. `total_time`:: (<>) Total time spent performing refresh operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing refresh operations. `external_total`:: (integer) Total number of external refresh operations. `external_total_time`:: (<>) Total time spent performing external operations. `external_total_time_in_millis`:: (integer) Total time in milliseconds spent performing external operations. `listeners`:: (integer) Number of refresh listeners. ======= `flush`:: (object) Contains statistics about flush operations for the node. + .Properties of `flush` [%collapsible%open] ======= `total`:: (integer) Number of flush operations. `periodic`:: (integer) Number of flush periodic operations. `total_time`:: (<>) Total time spent performing flush operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing flush operations. ======= `warmer`:: (object) Contains statistics about index warming operations for the node. + .Properties of `warmer` [%collapsible%open] ======= `current`:: (integer) Number of active index warmers. `total`:: (integer) Total number of index warmers. `total_time`:: (<>) Total time spent performing index warming operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing index warming operations. ======= `query_cache`:: (object) Contains statistics about the query cache across all shards assigned to the node. + .Properties of `query_cache` [%collapsible%open] ======= `memory_size`:: (<>) Total amount of memory used for the query cache across all shards assigned to the node. `memory_size_in_bytes`:: (integer) Total amount of memory, in bytes, used for the query cache across all shards assigned to the node. `total_count`:: (integer) Total count of hits, misses, and cached queries in the query cache. `hit_count`:: (integer) Number of query cache hits. `miss_count`:: (integer) Number of query cache misses. `cache_size`:: (integer) Size, in bytes, of the query cache. `cache_count`:: (integer) Count of queries in the query cache. `evictions`:: (integer) Number of query cache evictions. ======= `fielddata`:: (object) Contains statistics about the field data cache across all shards assigned to the node. + .Properties of `fielddata` [%collapsible%open] ======= `memory_size`:: (<>) Total amount of memory used for the field data cache across all shards assigned to the node. `memory_size_in_bytes`:: (integer) Total amount of memory, in bytes, used for the field data cache across all shards assigned to the node. `evictions`:: (integer) Number of fielddata evictions. ======= `completion`:: (object) Contains statistics about completions across all shards assigned to the node. + .Properties of `completion` [%collapsible%open] ======= `size`:: (<>) Total amount of memory used for completion across all shards assigned to the node. `size_in_bytes`:: (integer) Total amount of memory, in bytes, used for completion across all shards assigned to the node. ======= `segments`:: (object) Contains statistics about segments across all shards assigned to the node. + .Properties of `segments` [%collapsible%open] ======= `count`:: (integer) Number of segments. `memory`:: (<>) Total amount of memory used for segments across all shards assigned to the node. `memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for segments across all shards assigned to the node. `terms_memory`:: (<>) Total amount of memory used for terms across all shards assigned to the node. `terms_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for terms across all shards assigned to the node. `stored_fields_memory`:: (<>) Total amount of memory used for stored fields across all shards assigned to the node. `stored_fields_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for stored fields across all shards assigned to the node. `term_vectors_memory`:: (<>) Total amount of memory used for term vectors across all shards assigned to the node. `term_vectors_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for term vectors across all shards assigned to the node. `norms_memory`:: (<>) Total amount of memory used for normalization factors across all shards assigned to the node. `norms_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for normalization factors across all shards assigned to the node. `points_memory`:: (<>) Total amount of memory used for points across all shards assigned to the node. `points_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for points across all shards assigned to the node. `doc_values_memory`:: (<>) Total amount of memory used for doc values across all shards assigned to the node. `doc_values_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for doc values across all shards assigned to the node. `index_writer_memory`:: (<>) Total amount of memory used by all index writers across all shards assigned to the node. `index_writer_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by all index writers across all shards assigned to the node. `version_map_memory`:: (<>) Total amount of memory used by all version maps across all shards assigned to the node. `version_map_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by all version maps across all shards assigned to the node. `fixed_bit_set`:: (<>) Total amount of memory used by fixed bit sets across all shards assigned to the node. + Fixed bit sets are used for nested object field types and type filters for <> fields. `fixed_bit_set_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by fixed bit sets across all shards assigned to the node. + Fixed bit sets are used for nested object field types and type filters for <> fields. `max_unsafe_auto_id_timestamp`:: (integer) Time of the most recently retried indexing request. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `file_sizes`:: (object) Contains statistics about the size of the segment file. + .Properties of `file_sizes` [%collapsible%open] ======== `size`:: (<>) Size of the segment file. `size_in_bytes`:: (integer) Size, in bytes, of the segment file. `description`:: (string) Description of the segment file. ======== ======= `translog`:: (object) Contains statistics about transaction log operations for the node. + .Properties of `translog` [%collapsible%open] ======= `operations`:: (integer) Number of transaction log operations. `size`:: (<>) Size of the transaction log. `size_in_bytes`:: (integer) Size, in bytes, of the transaction log. `uncommitted_operations`:: (integer) Number of uncommitted transaction log operations. `uncommitted_size`:: (<>) Size of uncommitted transaction log operations. `uncommitted_size_in_bytes`:: (integer) Size, in bytes, of uncommitted transaction log operations. `earliest_last_modified_age`:: (integer) Earliest last modified age for the transaction log. ======= `request_cache`:: (object) Contains statistics about the request cache across all shards assigned to the node. + .Properties of `request_cache` [%collapsible%open] ======= `memory_size`:: (<>) Memory used by the request cache. `memory_size_in_bytes`:: (integer) Memory, in bytes, used by the request cache. `evictions`:: (integer) Number of request cache operations. `hit_count`:: (integer) Number of request cache hits. `miss_count`:: (integer) Number of request cache misses. ======= `recovery`:: (object) Contains statistics about recovery operations for the node. + .Properties of `recovery` [%collapsible%open] ======= `current_as_source`:: (integer) Number of recoveries that used an index shard as a source. `current_as_target`:: (integer) Number of recoveries that used an index shard as a target. `throttle_time`:: (<>) Time by which recovery operations were delayed due to throttling. `throttle_time_in_millis`:: (integer) Time in milliseconds recovery operations were delayed due to throttling. ======= ====== [[cluster-nodes-stats-api-response-body-os]] `os`:: (object) Contains statistics about the operating system for the node. + .Properties of `os` [%collapsible%open] ====== `timestamp`:: (integer) Last time the operating system statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `cpu`:: (object) Contains statistics about CPU usage for the node. + .Properties of `cpu` [%collapsible%open] ======= `percent`:: (integer) Recent CPU usage for the whole system, or `-1` if not supported. `load_average`:: (object) Contains statistics about load averages on the system. + .Properties of `load_average` [%collapsible%open] ======== `1m`:: (float) One-minute load average on the system (field is not present if one-minute load average is not available). `5m`:: (float) Five-minute load average on the system (field is not present if five-minute load average is not available). `15m`:: (float) Fifteen-minute load average on the system (field is not present if fifteen-minute load average is not available). ======== ======= `mem`:: (object) Contains statistics about memory usage for the node. + .Properties of `mem` [%collapsible%open] ======= `total`:: (<>) Total amount of physical memory. `total_in_bytes`:: (integer) Total amount of physical memory in bytes. `free`:: (<>) Amount of free physical memory. `free_in_bytes`:: (integer) Amount of free physical memory in bytes. `used`:: (<>) Amount of used physical memory. `used_in_bytes`:: (integer) Amount of used physical memory in bytes. `free_percent`:: (integer) Percentage of free memory. `used_percent`:: (integer) Percentage of used memory. ======= `swap`:: (object) Contains statistics about swap space for the node. + .Properties of `swap` [%collapsible%open] ======= `total`:: (<>) Total amount of swap space. `total_in_bytes`:: (integer) Total amount of swap space in bytes. `free`:: (<>) Amount of free swap space. `free_in_bytes`:: (integer) Amount of free swap space in bytes. `used`:: (<>) Amount of used swap space. `used_in_bytes`:: (integer) Amount of used swap space in bytes. ======= `cgroup` (Linux only):: (object) Contains cgroup statistics for the node. + NOTE: For the cgroup stats to be visible, cgroups must be compiled into the kernel, the `cpu` and `cpuacct` cgroup subsystems must be configured and stats must be readable from `/sys/fs/cgroup/cpu` and `/sys/fs/cgroup/cpuacct`. + .Properties of `cgroup` [%collapsible%open] ======= `cpuacct` (Linux only):: (object) Contains statistics about `cpuacct` control group for the node. + .Properties of `cpuacct` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `cpuacct` control group to which the {es} process belongs. `usage_nanos` (Linux only):: (integer) The total CPU time (in nanoseconds) consumed by all tasks in the same cgroup as the {es} process. ======== `cpu` (Linux only):: (object) Contains statistics about `cpu` control group for the node. + .Properties of `cpu` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `cpu` control group to which the {es} process belongs. `cfs_period_micros` (Linux only):: (integer) The period of time (in microseconds) for how regularly all tasks in the same cgroup as the {es} process should have their access to CPU resources reallocated. `cfs_quota_micros` (Linux only):: (integer) The total amount of time (in microseconds) for which all tasks in the same cgroup as the {es} process can run during one period `cfs_period_micros`. `stat` (Linux only):: (object) Contains CPU statistics for the node. + .Properties of `stat` [%collapsible%open] ========= `number_of_elapsed_periods` (Linux only):: (integer) The number of reporting periods (as specified by `cfs_period_micros`) that have elapsed. `number_of_times_throttled` (Linux only):: (integer) The number of times all tasks in the same cgroup as the {es} process have been throttled. `time_throttled_nanos` (Linux only):: (integer) The total amount of time (in nanoseconds) for which all tasks in the same cgroup as the {es} process have been throttled. ========= ======== `memory` (Linux only):: (object) Contains statistics about the `memory` control group for the node. + .Properties of `memory` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `memory` control group to which the {es} process belongs. `limit_in_bytes` (Linux only):: (string) The maximum amount of user memory (including file cache) allowed for all tasks in the same cgroup as the {es} process. This value can be too big to store in a `long`, so is returned as a string so that the value returned can exactly match what the underlying operating system interface returns. Any value that is too large to parse into a `long` almost certainly means no limit has been set for the cgroup. `usage_in_bytes` (Linux only):: (string) The total current memory usage by processes in the cgroup (in bytes) by all tasks in the same cgroup as the {es} process. This value is stored as a string for consistency with `limit_in_bytes`. ======== ======= ====== [[cluster-nodes-stats-api-response-body-process]] `process`:: (object) Contains process statistics for the node. + .Properties of `process` [%collapsible%open] ====== `timestamp`:: (integer) Last time the statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `open_file_descriptors`:: (integer) Number of opened file descriptors associated with the current or `-1` if not supported. `max_file_descriptors`:: (integer) Maximum number of file descriptors allowed on the system, or `-1` if not supported. `cpu`:: (object) Contains CPU statistics for the node. + .Properties of `cpu` [%collapsible%open] ======= `percent`:: (integer) CPU usage in percent, or `-1` if not known at the time the stats are computed. `total`:: (<>) CPU time used by the process on which the Java virtual machine is running. `total_in_millis`:: (integer) CPU time (in milliseconds) used by the process on which the Java virtual machine is running, or `-1` if not supported. ======= `mem`:: (object) Contains virtual memory statistics for the node. + .Properties of `mem` [%collapsible%open] ======= `total_virtual`:: (<>) Size of virtual memory that is guaranteed to be available to the running process. `total_virtual_in_bytes`:: (integer) Size in bytes of virtual memory that is guaranteed to be available to the running process. ======= ====== [[cluster-nodes-stats-api-response-body-jvm]] `jvm`:: (object) Contains Java Virtual Machine (JVM) statistics for the node. + .Properties of `jvm` [%collapsible%open] ====== `timestamp`:: (integer) Last time JVM statistics were refreshed. `uptime`:: (<>) JVM uptime. `uptime_in_millis`:: (integer) JVM uptime in milliseconds. `mem`:: (object) Contains JVM memory usage statistics for the node. + .Properties of `mem` [%collapsible%open] ======= `heap_used`:: (<>) Memory currently in use by the heap. `heap_used_in_bytes`:: (integer) Memory, in bytes, currently in use by the heap. `heap_used_percent`:: (integer) Percentage of memory currently in use by the heap. `heap_committed`:: (<>) Amount of memory available for use by the heap. `heap_committed_in_bytes`:: (integer) Amount of memory, in bytes, available for use by the heap. `heap_max`:: (<>) Maximum amount of memory available for use by the heap. `heap_max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the heap. `non_heap_used`:: (<>) Non-heap memory used. `non_heap_used_in_bytes`:: (integer) Non-heap memory used, in bytes. `non_heap_committed`:: (<>) Amount of non-heap memory available. `non_heap_committed_in_bytes`:: (integer) Amount of non-heap memory available, in bytes. `pools`:: (object) Contains statistics about heap memory usage for the node. + .Properties of `pools` [%collapsible%open] ======== `young`:: (object) Contains statistics about memory usage by the young generation heap for the node. + .Properties of `young` [%collapsible%open] ========= `used`:: (<>) Memory used by the young generation heap. `used_in_bytes`:: (integer) Memory, in bytes, used by the young generation heap. `max`:: (<>) Maximum amount of memory available for use by the young generation heap. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the young generation heap. `peak_used`:: (<>) Largest amount of memory historically used by the young generation heap. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the young generation heap. `peak_max`:: (<>) Largest amount of memory historically used by the young generation heap. `peak_max_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the young generation heap. ========= `survivor`:: (object) Contains statistics about memory usage by the survivor space for the node. + .Properties of `survivor` [%collapsible%open] ========= `used`:: (<>) Memory used by the survivor space. `used_in_bytes`:: (integer) Memory, in bytes, used by the survivor space. `max`:: (<>) Maximum amount of memory available for use by the survivor space. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the survivor space. `peak_used`:: (<>) Largest amount of memory historically used by the survivor space. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the survivor space. `peak_max`:: (<>) Largest amount of memory historically used by the survivor space. `peak_max_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the survivor space. ========= `old`:: (object) Contains statistics about memory usage by the old generation heap for the node. + .Properties of `old` [%collapsible%open] ========= `used`:: (<>) Memory used by the old generation heap. `used_in_bytes`:: (integer) Memory, in bytes, used by the old generation heap. `max`:: (<>) Maximum amount of memory available for use by the old generation heap. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the old generation heap. `peak_used`:: (<>) Largest amount of memory historically used by the old generation heap. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the old generation heap. `peak_max`:: (<>) Highest memory limit historically available for use by the old generation heap. `peak_max_in_bytes`:: (integer) Highest memory limit, in bytes, historically available for use by the old generation heap. ========= ======== ======= `threads`:: (object) Contains statistics about JVM thread usage for the node. + .Properties of `threads` [%collapsible%open] ======= `count`:: (integer) Number of active threads in use by JVM. `peak_count`:: (integer) Highest number of threads used by JVM. ======= `gc`:: (object) Contains statistics about JVM garbage collectors for the node. + .Properties of `gc` [%collapsible%open] ======= `collectors`:: (object) Contains statistics about JVM garbage collectors for the node. + .Properties of `collectors` [%collapsible%open] ======== `young`:: (object) Contains statistics about JVM garbage collectors that collect young generation objects for the node. + .Properties of `young` [%collapsible%open] ========= `collection_count`:: (integer) Number of JVM garbage collectors that collect young generation objects. `collection_time`:: (<>) Total time spent by JVM collecting young generation objects. `collection_time_in_millis`:: (integer) Total time in milliseconds spent by JVM collecting young generation objects. ========= `old`:: (object) Contains statistics about JVM garbage collectors that collect old generation objects for the node. + .Properties of `old` [%collapsible%open] ========= `collection_count`:: (integer) Number of JVM garbage collectors that collect old generation objects. `collection_time`:: (<>) Total time spent by JVM collecting old generation objects. `collection_time_in_millis`:: (integer) Total time in milliseconds spent by JVM collecting old generation objects. ========= ======== ======= `buffer_pools`:: (object) Contains statistics about JVM buffer pools for the node. + .Properties of `buffer_pools` [%collapsible%open] ======= `mapped`:: (object) Contains statistics about mapped JVM buffer pools for the node. + .Properties of `mapped` [%collapsible%open] ======== `count`:: (integer) Number of mapped buffer pools. `used`:: (<>) Size of mapped buffer pools. `used_in_bytes`:: (integer) Size, in bytes, of mapped buffer pools. `total_capacity`:: (<>) Total capacity of mapped buffer pools. `total_capacity_in_bytes`:: (integer) Total capacity, in bytes, of mapped buffer pools. ======== `direct`:: (object) Contains statistics about direct JVM buffer pools for the node. + .Properties of `direct` [%collapsible%open] ======== `count`:: (integer) Number of direct buffer pools. `used`:: (<>) Size of direct buffer pools. `used_in_bytes`:: (integer) Size, in bytes, of direct buffer pools. `total_capacity`:: (<>) Total capacity of direct buffer pools. `total_capacity_in_bytes`:: (integer) Total capacity, in bytes, of direct buffer pools. ======== ======= `classes`:: (object) Contains statistics about classes loaded by JVM for the node. + .Properties of `classes` [%collapsible%open] ======= `current_loaded_count`:: (integer) Number of classes currently loaded by JVM. `total_loaded_count`:: (integer) Total number of classes loaded since the JVM started. `total_unloaded_count`:: (integer) Total number of classes unloaded since the JVM started. ======= ====== [[cluster-nodes-stats-api-response-body-threadpool]] `thread_pool`:: (object) Contains thread pool statistics for the node + .Properties of `thread_pool` [%collapsible%open] ====== ``:: (object) Contains statistics about the thread pool for the node. + .Properties of `` [%collapsible%open] ======= `threads`:: (integer) Number of threads in the thread pool. `queue`:: (integer) Number of tasks in queue for the thread pool. `active`:: (integer) Number of active threads in the thread pool. `rejected`:: (integer) Number of tasks rejected by the thread pool executor. `largest`:: (integer) Highest number of active threads in the thread pool. `completed`:: (integer) Number of tasks completed by the thread pool executor. ======= ====== [[cluster-nodes-stats-api-response-body-fs]] `fs`:: (object) Contains file store statistics for the node. + .Properties of `fs` [%collapsible%open] ====== `timestamp`:: (integer) Last time the file stores statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `total`:: (object) Contains statistics for all file stores of the node. + .Properties of `total` [%collapsible%open] ======= `total`:: (<>) Total size of all file stores. `total_in_bytes`:: (integer) Total size (in bytes) of all file stores. `free`:: (<>) Total unallocated disk space in all file stores. `free_in_bytes`:: (integer) Total number of unallocated bytes in all file stores. `available`:: (<>) Total disk space available to this Java virtual machine on all file stores. Depending on OS or process level restrictions, this might appear less than `free`. This is the actual amount of free disk space the {es} node can utilise. `available_in_bytes`:: (integer) Total number of bytes available to this Java virtual machine on all file stores. Depending on OS or process level restrictions, this might appear less than `free_in_bytes`. This is the actual amount of free disk space the {es} node can utilise. ======= [[cluster-nodes-stats-fs-data]] `data`:: (array of objects) List of all file stores. + .Properties of `data` [%collapsible%open] ======= `path`:: (string) Path to the file store. `mount`:: (string) Mount point of the file store (ex: /dev/sda2). `type`:: (string) Type of the file store (ex: ext4). `total`:: (<>) Total size of the file store. `total_in_bytes`:: (integer) Total size (in bytes) of the file store. `free`:: (<>) Total amount of unallocated disk space in the file store. `free_in_bytes`:: (integer) Total number of unallocated bytes in the file store. `available`:: (<>) Total amount of disk space available to this Java virtual machine on this file store. `available_in_bytes`:: (integer) Total number of bytes available to this Java virtual machine on this file store. ======= `io_stats` (Linux only):: (objects) Contains I/O statistics for the node. + .Properties of `io_stats` [%collapsible%open] ======= `devices` (Linux only):: (array) Array of disk metrics for each device that is backing an {es} data path. These disk metrics are probed periodically and averages between the last probe and the current probe are computed. + .Properties of `devices` [%collapsible%open] ======== `device_name` (Linux only):: (string) The Linux device name. `operations` (Linux only):: (integer) The total number of read and write operations for the device completed since starting {es}. `read_operations` (Linux only):: (integer) The total number of read operations for the device completed since starting {es}. `write_operations` (Linux only):: (integer) The total number of write operations for the device completed since starting {es}. `read_kilobytes` (Linux only):: (integer) The total number of kilobytes read for the device since starting {es}. `write_kilobytes` (Linux only):: (integer) The total number of kilobytes written for the device since starting {es}. ======== `operations` (Linux only):: (integer) The total number of read and write operations across all devices used by {es} completed since starting {es}. `read_operations` (Linux only):: (integer) The total number of read operations for across all devices used by {es} completed since starting {es}. `write_operations` (Linux only):: (integer) The total number of write operations across all devices used by {es} completed since starting {es}. `read_kilobytes` (Linux only):: (integer) The total number of kilobytes read across all devices used by {es} since starting {es}. `write_kilobytes` (Linux only):: (integer) The total number of kilobytes written across all devices used by {es} since starting {es}. ======= ====== [[cluster-nodes-stats-api-response-body-transport]] `transport`:: (object) Contains transport statistics for the node. + .Properties of `transport` [%collapsible%open] ====== `server_open`:: (integer) Current number of inbound TCP connections used for internal communication between nodes. `total_outbound_connections`:: (integer) The cumulative number of outbound transport connections that this node has opened since it started. Each transport connection may comprise multiple TCP connections but is only counted once in this statistic. Transport connections are typically <> so this statistic should remain constant in a stable cluster. `rx_count`:: (integer) Total number of RX (receive) packets received by the node during internal cluster communication. `rx_size`:: (<>) Size of RX packets received by the node during internal cluster communication. `rx_size_in_bytes`:: (integer) Size, in bytes, of RX packets received by the node during internal cluster communication. `tx_count`:: (integer) Total number of TX (transmit) packets sent by the node during internal cluster communication. `tx_size`:: (<>) Size of TX packets sent by the node during internal cluster communication. `tx_size_in_bytes`:: (integer) Size, in bytes, of TX packets sent by the node during internal cluster communication. ====== [[cluster-nodes-stats-api-response-body-http]] `http`:: (object) Contains http statistics for the node. + .Properties of `http` [%collapsible%open] ====== `current_open`:: (integer) Current number of open HTTP connections for the node. `total_opened`:: (integer) Total number of HTTP connections opened for the node. ====== [[cluster-nodes-stats-api-response-body-breakers]] `breakers`:: (object) Contains circuit breaker statistics for the node. + .Properties of `breakers` [%collapsible%open] ====== ``:: (object) Contains statistics for the circuit breaker. + .Properties of `` [%collapsible%open] ======= `limit_size_in_bytes`:: (integer) Memory limit, in bytes, for the circuit breaker. `limit_size`:: (<>) Memory limit for the circuit breaker. `estimated_size_in_bytes`:: (integer) Estimated memory used, in bytes, for the operation. `estimated_size`:: (<>) Estimated memory used for the operation. `overhead`:: (float) A constant that all estimates for the circuit breaker are multiplied with to calculate a final estimate. `tripped`:: (integer) Total number of times the circuit breaker has been triggered and prevented an out of memory error. ======= ====== [[cluster-nodes-stats-api-response-body-script]] `script`:: (object) Contains script statistics for the node. + .Properties of `script` [%collapsible%open] ====== `compilations`:: (integer) Total number of inline script compilations performed by the node. `cache_evictions`:: (integer) Total number of times the script cache has evicted old data. `compilation_limit_triggered`:: (integer) Total number of times the <> circuit breaker has limited inline script compilations. ====== [[cluster-nodes-stats-api-response-body-discovery]] `discovery`:: (object) Contains node discovery statistics for the node. + .Properties of `discovery` [%collapsible%open] ====== `cluster_state_queue`:: (object) Contains statistics for the cluster state queue of the node. + .Properties of `cluster_state_queue` [%collapsible%open] ======= `total`:: (integer) Total number of cluster states in queue. `pending`:: (integer) Number of pending cluster states in queue. `committed`:: (integer) Number of committed cluster states in queue. ======= `published_cluster_states`:: (object) Contains statistics for the published cluster states of the node. + .Properties of `published_cluster_states` [%collapsible%open] ======= `full_states`:: (integer) Number of published cluster states. `incompatible_diffs`:: (integer) Number of incompatible differences between published cluster states. `compatible_diffs`:: (integer) Number of compatible differences between published cluster states. ======= ====== [[cluster-nodes-stats-api-response-body-ingest]] `ingest`:: (object) Contains ingest statistics for the node. + .Properties of `ingest` [%collapsible%open] ====== `total`:: (object) Contains statistics about ingest operations for the node. + .Properties of `total` [%collapsible%open] ======= `count`:: (integer) Total number of documents ingested during the lifetime of this node. `time`:: (<>) Total time spent preprocessing ingest documents during the lifetime of this node. `time_in_millis`:: (integer) Total time, in milliseconds, spent preprocessing ingest documents during the lifetime of this node. `current`:: (integer) Total number of documents currently being ingested. `failed`:: (integer) Total number of failed ingest operations during the lifetime of this node. ======= `pipelines`:: (object) Contains statistics about ingest pipelines for the node. + .Properties of `pipelines` [%collapsible%open] ======= ``:: (object) Contains statistics about the ingest pipeline. + .Properties of `` [%collapsible%open] ======== `count`:: (integer) Number of documents preprocessed by the ingest pipeline. `time`:: (<>) Total time spent preprocessing documents in the ingest pipeline. `time_in_millis`:: (integer) Total time, in milliseconds, spent preprocessing documents in the ingest pipeline. `failed`:: (integer) Total number of failed operations for the ingest pipeline. `processors`:: (array of objects) Contains statistics for the ingest processors for the ingest pipeline. + .Properties of `processors` [%collapsible%open] ========= ``:: (object) Contains statistics for the ingest processor. + .Properties of `` [%collapsible%open] ========== `count`:: (integer) Number of documents transformed by the processor. `time`:: (<>) Time spent by the processor transforming documents. `time_in_millis`:: (integer) Time, in milliseconds, spent by the processor transforming documents. `current`:: (integer) Number of documents currently being transformed by the processor. `failed`:: (integer) Number of failed operations for the processor. ========== ========= ======== ======= ====== [[cluster-nodes-stats-api-response-body-indexing-pressure]] `indexing_pressure`:: (object) Contains <> statistics for the node. + .Properties of `indexing_pressure` [%collapsible%open] ====== `memory`:: (object) Contains statistics for memory consumption from indexing load. + .Properties of `` [%collapsible%open] ======= `current`:: (object) Contains statistics for current indexing load. + .Properties of `` [%collapsible%open] ======== `combined_coordinating_and_primary`:: (<>) Memory consumed by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `combined_coordinating_and_primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `coordinating`:: (<>) Memory consumed by indexing requests in the coordinating stage. `coordinating_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating stage. `primary`:: (<>) Memory consumed by indexing requests in the primary stage. `primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the primary stage. `replica`:: (<>) Memory consumed by indexing requests in the replica stage. `replica_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the replica stage. `all`:: (<>) Memory consumed by indexing requests in the coordinating, primary, or replica stage. `all_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating, primary, or replica stage. ======== `total`:: (object) Contains statistics for the cumulative indexing load since the node started. + .Properties of `` [%collapsible%open] ======== `combined_coordinating_and_primary`:: (<>) Memory consumed by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `combined_coordinating_and_primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `coordinating`:: (<>) Memory consumed by indexing requests in the coordinating stage. `coordinating_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating stage. `primary`:: (<>) Memory consumed by indexing requests in the primary stage. `primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the primary stage. `replica`:: (<>) Memory consumed by indexing requests in the replica stage. `replica_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the replica stage. `all`:: (<>) Memory consumed by indexing requests in the coordinating, primary, or replica stage. `all_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating, primary, or replica stage. `coordinating_rejections`:: (integer) Number of indexing requests rejected in the coordinating stage. `primary_rejections`:: (integer) Number of indexing requests rejected in the primary stage. `replica_rejections`:: (integer) Number of indexing requests rejected in the replica stage. ======== `limit`:: (<>) Configured memory limit for the indexing requests. Replica requests have an automatic limit that is 1.5x this value. `limit_in_bytes`:: (integer) Configured memory limit, in bytes, for the indexing requests. Replica requests have an automatic limit that is 1.5x this value. ======= ====== [[cluster-nodes-stats-api-response-body-adaptive-selection]] `adaptive_selection`:: (object) Contains adaptive selection statistics for the node. + .Properties of `adaptive_selection` [%collapsible%open] ====== `outgoing_searches`:: (integer) The number of outstanding search requests from the node these stats are for to the keyed node. `avg_queue_size`:: (integer) The exponentially weighted moving average queue size of search requests on the keyed node. `avg_service_time`:: (<>) The exponentially weighted moving average service time of search requests on the keyed node. `avg_service_time_ns`:: (integer) The exponentially weighted moving average service time, in nanoseconds, of search requests on the keyed node. `avg_response_time`:: (<>) The exponentially weighted moving average response time of search requests on the keyed node. `avg_response_time_ns`:: (integer) The exponentially weighted moving average response time, in nanoseconds, of search requests on the keyed node. `rank`:: (string) The rank of this node; used for shard selection when routing search requests. ====== ===== ==== [[cluster-nodes-stats-api-example]] ==== {api-examples-title} [source,console] -------------------------------------------------- # return just indices GET /_nodes/stats/indices # return just os and process GET /_nodes/stats/os,process # return just process for node with IP address 10.0.0.1 GET /_nodes/10.0.0.1/stats/process -------------------------------------------------- All stats can be explicitly requested via `/_nodes/stats/_all` or `/_nodes/stats?metric=_all`. You can get information about indices stats on `node`, `indices`, or `shards` level. [source,console] -------------------------------------------------- # Fielddata summarized by node GET /_nodes/stats/indices/fielddata?fields=field1,field2 # Fielddata summarized by node and index GET /_nodes/stats/indices/fielddata?level=indices&fields=field1,field2 # Fielddata summarized by node, index, and shard GET /_nodes/stats/indices/fielddata?level=shards&fields=field1,field2 # You can use wildcards for field names GET /_nodes/stats/indices/fielddata?fields=field* -------------------------------------------------- You can get statistics about search groups for searches executed on this node. [source,console] -------------------------------------------------- # All groups with all stats GET /_nodes/stats?groups=_all # Some groups from just the indices stats GET /_nodes/stats/indices?groups=foo,bar -------------------------------------------------- [[cluster-nodes-stats-ingest-ex]] ===== Retrieve ingest statistics only To return only ingest-related node statistics, set the `` path parameter to `ingest` and use the <> query parameter. [source,console] -------------------------------------------------- GET /_nodes/stats/ingest?filter_path=nodes.*.ingest -------------------------------------------------- You can use the `metric` and `filter_path` query parameters to get the same response. [source,console] -------------------------------------------------- GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest -------------------------------------------------- To further refine the response, change the `filter_path` value. For example, the following request only returns ingest pipeline statistics. [source,console] -------------------------------------------------- GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest.pipelines -------------------------------------------------- ",12335,True,2575.9624837012534,median "[[release-notes-7.2.1]] == {es} version 7.2.1 Also see <>. [[enhancement-7.2.1]] [float] === Enhancements Infra/Core:: * Add default CLI JVM options {pull}44545[#44545] (issue: {issue}42021[#42021]) Infra/Plugins:: * Do not checksum all bytes at once in plugin install {pull}44649[#44649] (issue: {issue}44545[#44545]) Machine Learning:: * Improve message when native controller cannot connect {pull}43565[#43565] (issue: {issue}42341[#42341]) * Introduce a setting for the process connect timeout {pull}43234[#43234] [[bug-7.2.1]] [float] === Bug fixes Analysis:: * Issue deprecation warnings for preconfigured delimited_payload_filter {pull}43684[#43684] (issues: {issue}26625[#26625], {issue}43568[#43568]) Authentication:: * Fix credential encoding for OIDC token request {pull}43808[#43808] (issue: {issue}43709[#43709]) Data Frame:: * Reorder format priorities in dest mapping {pull}43602[#43602] * Adjust error message {pull}43455[#43455] * Size the GET stats search by number of Ids requested {pull}43206[#43206] (issue: {issue}43203[#43203]) Distributed:: * Fix DefaultShardOperationFailedException subclass xcontent serialization {pull}43435[#43435] (issue: {issue}43423[#43423]) Engine:: * AsyncIOProcessor preserve thread context {pull}43729[#43729] Features/CAT APIs:: * Fix indices shown in _cat/indices {pull}43286[#43286] (issues: {issue}33888[#33888], {issue}38824[#38824], {issue}39933[#39933]) Features/ILM:: * Account for node versions during allocation in ILM Shrink {pull}43300[#43300] (issue: {issue}41879[#41879]) Features/Indices APIs:: * Check shard limit after applying index templates {pull}44619[#44619] (issues: {issue}34021[#34021], {issue}44567[#44567], {issue}44619[#44619]) * Validate index settings after applying templates {pull}44612[#44612] (issues: {issue}34021[#34021], {issue}44567[#44567]) * Prevent NullPointerException in TransportRolloverAction {pull}43353[#43353] (issue: {issue}43296[#43296]) Infra/Packaging:: * Restore setting up temp dir for windows service {pull}44541[#44541] * Fix the bundled jdk flag to be passed through windows startup {pull}43502[#43502] Machine Learning:: * Fix datafeed checks when a concrete remote index is present {pull}43923[#43923] * Don't persist model state at the end of lookback if the lookback did not generate any input {ml-pull}527[#527] (issue: {ml-issue}519[#519]) * Don't write model size stats when job is closed without any input {ml-pull}516[#516] (issue: {ml-issue}394[#394]) Mapping:: * Prevent types deprecation warning for indices.exists requests {pull}43963[#43963] (issue: {issue}43905[#43905]) * Add include_type_name in indices.exitst REST API spec {pull}43910[#43910] (issue: {issue}43905[#43905]) * Fix index_prefix sub field name on nested text fields {pull}43862[#43862] (issue: {issue}43741[#43741]) Network:: * Reconnect remote cluster when seeds are changed {pull}43379[#43379] (issue: {issue}37799[#37799]) SQL:: * Fix NPE in case of subsequent scrolled requests for a CSV/TSV formatted response {pull}43365[#43365] (issue: {issue}43327[#43327]) * Increase hard limit for sorting on aggregates {pull}43220[#43220] (issue: {issue}43168[#43168]) Search:: * Fix wrong logic in `match_phrase` query with multi-word synonyms {pull}43941[#43941] (issue: {issue}43308[#43308]) * Fix UOE on search requests that match a sparse role query {pull}43668[#43668] (issue: {issue}42857[#42857]) * Fix propagation of enablePositionIncrements in QueryStringQueryBuilder {pull}43578[#43578] (issue: {issue}43574[#43574]) * Fix round up of date range without rounding {pull}43303[#43303] (issue: {issue}43277[#43277]) Security:: * SecurityIndexSearcherWrapper doesn't always carry over caches and similarity {pull}43436[#43436] [[release-notes-7.2.0]] == {es} version 7.2.0 Also see <>. [float] === Known issues * Indices created in 6.x with <> and <> fields using formats that are incompatible with java.time patterns will cause parsing errors, incorrect date calculations or wrong search results. https://github.com/elastic/elasticsearch/pull/52555 This is fixed in {es} 7.7 and later versions. [[breaking-7.2.0]] [float] === Breaking changes Cluster Coordination:: * Reject port ranges in `discovery.seed_hosts` {pull}41404[#41404] (issue: {issue}40786[#40786]) [[breaking-java-7.2.0]] [float] === Breaking Java changes Infra/Plugins:: * Remove IndexStore and DirectoryService {pull}42446[#42446] [[deprecation-7.2.0]] [float] === Deprecations Authorization:: * Deprecate permission over aliases {pull}38059[#38059] Features/Features:: * Add deprecation check for ILM poll interval <1s {pull}41096[#41096] (issue: {issue}39163[#39163]) Mapping:: * Enforce Completion Context Limit {pull}38675[#38675] (issue: {issue}32741[#32741]) Reindex:: * Reindex from remote deprecation of escaped index {pull}41005[#41005] (issue: {issue}40303[#40303]) Search:: * Deprecate using 0 value for `min_children` in `has_child` query #41548 {pull}41555[#41555] (issue: {issue}41548[#41548]) * Deprecate support for first line empty in msearch API {pull}41442[#41442] (issue: {issue}41011[#41011]) Security:: * Deprecate the native realm migration tool {pull}42142[#42142] [[feature-7.2.0]] [float] === New features Authentication:: * Add an OpenID Connect authentication realm {pull}40674[#40674] Distributed:: * Add support for replicating closed indices {pull}39499[#39499] (issues: {issue}33888[#33888], {issue}33903[#33903], {issue}37359[#37359], {issue}37413[#37413], {issue}38024[#38024], {issue}38326[#38326], {issue}38327[#38327], {issue}38329[#38329], {issue}38421[#38421], {issue}38631[#38631], {issue}38767[#38767], {issue}38854[#38854], {issue}38955[#38955], {issue}39006[#39006], {issue}39110[#39110], {issue}39186[#39186], {issue}39249[#39249], {issue}39364[#39364]) Infra/Scripting:: * Add painless string split function (splitOnToken) {pull}39772[#39772] (issue: {issue}20952[#20952]) * Add a Painless Context REST API {pull}39382[#39382] Machine Learning:: * Add data frame feature {pull}38934[#38934] Ranking:: * Expose proximity boosting {pull}39385[#39385] (issue: {issue}33382[#33382]) * Add randomScore function in script_score query {pull}40186[#40186] (issue: {issue}31461[#31461]) SQL:: * Add initial geo support {pull}42031[#42031] (issues: {issue}29872[#29872], {issue}37206[#37206]) * Implement CASE... WHEN... THEN... ELSE... END {pull}41349[#41349] (issue: {issue}36200[#36200]) * Introduce MAD (MedianAbsoluteDeviation) aggregation {pull}40048[#40048] (issue: {issue}39597[#39597]) * Introduce SQL TIME data type {pull}39802[#39802] (issue: {issue}38174[#38174]) * Introduce the columnar option for REST requests {pull}39287[#39287] (issue: {issue}37702[#37702]) Snapshot/Restore:: * Allow snapshotting replicated closed indices {pull}39644[#39644] (issue: {issue}33888[#33888]) Suggesters:: * Search as you type fieldmapper {pull}35600[#35600] (issue: {issue}33160[#33160]) Features/Ingest:: * Add HTML strip processor {pull}41888[#41888] Search:: * Add an option to force the numeric type of a field sort {pull}38095[#38095] (issue: {issue}32601[#32601]) [[enhancement-7.2.0]] [float] === Enhancements Aggregations:: * Use the breadth first collection mode for significant terms aggs. {pull}29042[#29042] (issue: {issue}28652[#28652]) * Disallow null/empty or duplicate composite sources {pull}41359[#41359] (issue: {issue}32414[#32414]) * Move top-level pipeline aggs out of QuerySearchResult {pull}40319[#40319] (issue: {issue}40177[#40177]) * Remove throws IOException from PipelineAggregationBuilder#create {pull}40222[#40222] * Better error messages when pipelines reference incompatible aggs {pull}40068[#40068] (issues: {issue}25273[#25273], {issue}30152[#30152]) * Do not allow Sampler to allocate more than maxDoc size, better CB accounting {pull}39381[#39381] (issue: {issue}34269[#34269]) * Force selection of calendar or fixed intervals in date histo agg {pull}33727[#33727] Allocation:: * Reset failed allocation counter before executing routing commands {pull}41050[#41050] (issue: {issue}39546[#39546]) * Supporting automatic release of index blocks. Closes #39334 {pull}40338[#40338] (issue: {issue}39334[#39334]) Analysis:: * Add flag to declare token filters as updateable {pull}36103[#36103] (issue: {issue}29051[#29051]) Authentication:: * Hash token values for storage {pull}41792[#41792] (issues: {issue}39631[#39631], {issue}40765[#40765]) * Security Tokens moved to a new separate index {pull}40742[#40742] (issue: {issue}34454[#34454]) * Support concurrent refresh of refresh tokens {pull}39631[#39631] (issue: {issue}36872[#36872]) * Add enabled status for token and api key service {pull}38687[#38687] (issue: {issue}38535[#38535]) Authorization:: * Support mustache templates in role mappings {pull}39984[#39984] (issue: {issue}36567[#36567]) * Add .code_internal-* index pattern to kibana user {pull}42247[#42247] * Add granular API key privileges {pull}41488[#41488] (issue: {issue}40031[#40031]) * Add Kibana application privileges for monitoring and ml reserved roles {pull}40651[#40651] * Support roles with application privileges against wildcard applications {pull}40398[#40398] CCR:: * Replay history of operations in remote recovery {pull}39153[#39153] (issues: {issue}35975[#35975], {issue}39000[#39000]) CRUD:: * Add details to BulkShardRequest#getDescription() {pull}41711[#41711] * Add version-based validation to reindex requests {pull}38504[#38504] (issue: {issue}37855[#37855]) Cluster Coordination:: * Add GET /_cluster/master endpoint {pull}40047[#40047] * Only connect to new nodes on new cluster state {pull}39629[#39629] (issues: {issue}29025[#29025], {issue}31547[#31547]) * Add has_voting_exclusions flag to cluster health output {pull}38568[#38568] Data Frame:: * Persist and restore checkpoint and position {pull}41942[#41942] (issue: {issue}41752[#41752]) * Complete the Data Frame task on stop {pull}41752[#41752] * Data Frame stop all {pull}41156[#41156] * Data Frame HLRC Get Stats API {pull}40327[#40327] * Data Frame HLRC Get API {pull}40209[#40209] * Data Frame HLRC Preview API {pull}40206[#40206] * Data Frame HLRC start & stop APIs {pull}40154[#40154] (issue: {issue}29546[#29546]) * Add Data Frame client to the Java HLRC {pull}39921[#39921] Discovery-Plugins:: * Upgrade SDK and test discovery-ec2 credential providers {pull}41732[#41732] Distributed:: * Prevent in-place downgrades and invalid upgrades {pull}41731[#41731] * Add index name to cluster block exception {pull}41489[#41489] (issue: {issue}40870[#40870]) * Noop peer recoveries on closed index {pull}41400[#41400] (issue: {issue}33888[#33888]) * Do not trim unsafe commits when open readonly engine {pull}41041[#41041] (issue: {issue}33888[#33888]) * Avoid background sync on relocated primary {pull}40800[#40800] (issue: {issue}40731[#40731]) * No mapper service and index caches for replicated closed indices {pull}40423[#40423] * Add support for replicating closed indices {pull}39499[#39499] (issues: {issue}33888[#33888], {issue}33903[#33903], {issue}37359[#37359], {issue}37413[#37413], {issue}38024[#38024], {issue}38326[#38326], {issue}38327[#38327], {issue}38329[#38329], {issue}38421[#38421], {issue}38631[#38631], {issue}38767[#38767], {issue}38854[#38854], {issue}38955[#38955], {issue}39006[#39006], {issue}39110[#39110], {issue}39186[#39186], {issue}39249[#39249], {issue}39364[#39364]) Docs Infrastructure:: * Docs: Simplifying setup by using module configuration variant syntax {pull}40879[#40879] Engine:: * Simplify initialization of max_seq_no of updates {pull}41161[#41161] (issues: {issue}33842[#33842], {issue}40249[#40249]) * Adjust init map size of user data of index commit {pull}40965[#40965] * Don't mark shard as refreshPending on stats fetching {pull}40458[#40458] (issues: {issue}33835[#33835], {issue}33847[#33847]) * Reject illegal flush parameters {pull}40213[#40213] (issue: {issue}36342[#36342]) * Always fail engine if delete operation fails {pull}40117[#40117] (issue: {issue}33256[#33256]) * Combine overriddenOps and skippedOps in translog {pull}39771[#39771] (issue: {issue}33317[#33317]) * Return cached segments stats if `include_unloaded_segments` is true {pull}39698[#39698] (issue: {issue}39512[#39512]) * Allow inclusion of unloaded segments in stats {pull}39512[#39512] * Never block on scheduled refresh if a refresh is running {pull}39462[#39462] * Expose external refreshes through the stats API {pull}38643[#38643] (issue: {issue}36712[#36712]) * Make setting index.translog.sync_interval be dynamic {pull}37382[#37382] (issue: {issue}32763[#32763]) Features/CAT APIs:: * Add start and stop time to cat recovery API {pull}40378[#40378] * Return 0 for negative ""free"" and ""total"" memory reported by the OS {pull}42725[#42725] (issue: {issue}42157[#42157]) Features/Indices APIs:: * Introduce aliases version {pull}41397[#41397] (issue: {issue}41396[#41396]) * Improve error message for absence of indices {pull}39789[#39789] (issues: {issue}38964[#38964], {issue}39296[#39296]) * Improved error message for absence of indices closes #38964 {pull}39296[#39296] Features/Java High Level REST Client:: * Added param ignore_throttled=false when indicesOptions.ignoreThrottle… {pull}42393[#42393] (issue: {issue}42358[#42358]) * Ignore 409 conflict in reindex responses {pull}39543[#39543] Features/Monitoring:: * Add packaging to cluster stats response {pull}41048[#41048] (issue: {issue}39378[#39378]) Geo:: * Improve accuracy for Geo Centroid Aggregation {pull}41033[#41033] (issue: {issue}41032[#41032]) * Add support for z values to libs/geo classes {pull}38921[#38921] * Add ST_WktToSQL function {pull}35416[#35416] (issue: {issue}29872[#29872]) Infra/Core:: * Validate non-secure settings are not in keystore {pull}42209[#42209] (issue: {issue}41831[#41831]) * Implement XContentParser.genericMap and XContentParser.genericMapOrdered methods {pull}42059[#42059] * Remove manual parsing of JVM options {pull}41962[#41962] (issue: {issue}30684[#30684]) * Clarify some ToXContent implementations behaviour {pull}41000[#41000] (issue: {issue}16347[#16347]) * Remove String interning from `o.e.index.Index`. {pull}40350[#40350] (issue: {issue}40263[#40263]) * Do not swallow exceptions in TimedRunnable {pull}39856[#39856] (issue: {issue}36137[#36137]) Infra/Logging:: * Reduce garbage from allocations in DeprecationLogger {pull}38780[#38780] (issues: {issue}35754[#35754], {issue}37411[#37411], {issue}37530[#37530]) Infra/Packaging:: * Clearer error message - installing windows service {pull}33804[#33804] Infra/Resiliency:: * Limit max direct memory size to half of heap size {pull}42006[#42006] (issues: {issue}41954[#41954], {issue}41962[#41962]) Infra/Scripting:: * Add implicit this for class binding in Painless {pull}40285[#40285] * Whitelist geo methods for Painless {pull}40180[#40180] (issue: {issue}24946[#24946]) Machine Learning:: * Improve message misformation error in file structure finder {pull}42175[#42175] * Improve hard_limit audit message {pull}42086[#42086] (issue: {issue}38034[#38034]) * Add validation that rejects duplicate detectors in PutJobAction {pull}40967[#40967] (issue: {issue}39704[#39704]) * Add created_by info to usage stats {pull}40518[#40518] (issue: {issue}38403[#38403]) * Data frame transforms config HLRC objects {pull}39691[#39691] * Use scaling thread pool and xpack.ml.max_open_jobs cluster-wide dynamic {pull}39320[#39320] (issue: {issue}29809[#29809]) * Add task recovery on node change {pull}39416[#39416] * Stop tasks on failure {pull}39203[#39203] * Add _preview endpoint {pull}38924[#38924] * Use hardened compiler options to build 3rd party libraries {ml-pull}453[#453] * Only select more complex trend models for forecasting if there is evidence that they are needed {ml-pull}463[#463] * Improve residual model selection {ml-pull}468[#468] * Stop linking to libcrypt on Linux {ml-pull}480[#480] * Improvements to hard_limit audit message {ml-pull}486[#486] * Increase maximum forecast interval from 8 weeks to a limit based on the amount of data seen, up to a maximum of 10 years {ml-pull}214[#214] and {pull}41082[#41082] (issue: {issue}41103[#41103]) Mapping:: * Updates max dimensions for sparse_vector and dense_vector to 1024. {pull}40597[#40597] (issue: {issue}40492[#40492]) * Add ignore_above in ICUCollationKeywordFieldMapper {pull}40414[#40414] (issue: {issue}40413[#40413]) * Adding a soft limit to the field name length. Closes #33651 {pull}40309[#40309] (issue: {issue}33651[#33651]) Network:: * Update ciphers for TLSv1.3 and JDK11 if available {pull}42082[#42082] (issues: {issue}38646[#38646], {issue}41385[#41385], {issue}41808[#41808]) * Show SSL usage when security is not disabled {pull}40672[#40672] (issue: {issue}37433[#37433]) * Optimize Bulk Message Parsing and Message Length Parsing {pull}39634[#39634] (issue: {issue}39286[#39286]) * Netty transport accept plaintext connections {pull}39532[#39532] (issue: {issue}39531[#39531]) * Chunk + Throttle Netty Writes {pull}39286[#39286] Ranking:: * Improve error message for ln/log with negative results in function score {pull}41609[#41609] (issue: {issue}41509[#41509]) Recovery:: * Peer recovery should flush at the end {pull}41660[#41660] (issues: {issue}33888[#33888], {issue}39588[#39588], {issue}40024[#40024]) * Peer recovery should not indefinitely retry on mapping error {pull}41099[#41099] (issue: {issue}40913[#40913]) * Init global checkpoint after copy commit in peer recovery {pull}40823[#40823] (issue: {issue}33888[#33888]) * Ensure sendBatch not called recursively {pull}39988[#39988] Reindex:: * Reindex from Remote allow date math {pull}40303[#40303] (issue: {issue}23533[#23533]) SQL:: * Implement IIF(, , ) {pull}41420[#41420] (issue: {issue}40917[#40917]) * Use field caps inside DESCRIBE TABLE as well {pull}41377[#41377] (issue: {issue}34071[#34071]) * Implement CURRENT_TIME/CURTIME functions {pull}40662[#40662] (issue: {issue}40648[#40648]) * Polish behavior of SYS TABLES command {pull}40535[#40535] (issue: {issue}40348[#40348]) * Adjust the precision and scale for drivers {pull}40467[#40467] (issue: {issue}40357[#40357]) * Polish parsing of CAST expression {pull}40428[#40428] * Fix classpath discovery on Java 10+ {pull}40420[#40420] (issue: {issue}40388[#40388]) * Spec tests now use classpath discovery {pull}40388[#40388] (issue: {issue}40358[#40358]) * Implement `::` cast operator {pull}38774[#38774] (issue: {issue}38717[#38717]) Search:: * Fix range query edge cases {pull}41160[#41160] (issue: {issue}40937[#40937]) * Add stopword support to IntervalBuilder {pull}39637[#39637] * Shortcut counts on exists queries {pull}39570[#39570] (issue: {issue}37475[#37475]) * Completion suggestions to be reduced once instead of twice {pull}39255[#39255] * Rename SearchRequest#withLocalReduction {pull}39108[#39108] * Tie break search shard iterator comparisons on cluster alias {pull}38853[#38853] * Clean up ShardSearchLocalRequest {pull}38574[#38574] * Handle unmapped fields in _field_caps API {pull}34071[#34071] * Make 0 as invalid value for `min_children` in `has_child` query {pull}33073[#33073] (issue: {issue}32949[#32949]) * Analyze numbers, dates and ips with a whitespace analyzer in text queries {pull}27395[#27395] * Add date and date_nanos conversion to the numeric_type sort option {pull}40199[#40199] * Add `use_field` option to intervals query {pull}40157[#40157] * Add overlapping, before, after filters to intervals query {pull}38999[#38999] Security:: * Support concurrent refresh of refresh tokens {pull}38382[#38382] (issue: {issue}36872[#36872]) Snapshot/Restore:: * Remove IndexShard dependency from Repository {pull}42213[#42213] * Add shared access signature authentication support {pull}42117[#42117] * Support multiple repositories in get snapshot request {pull}41799[#41799] (issue: {issue}41210[#41210]) * Implement Bulk Deletes for GCS Repository {pull}41368[#41368] (issue: {issue}40322[#40322]) * Add Bulk Delete Api to BlobStore {pull}40322[#40322] (issues: {issue}40144[#40144], {issue}40250[#40250]) * Async Snapshot Repository Deletes {pull}40144[#40144] (issues: {issue}39656[#39656], {issue}39657[#39657]) * Allow snapshotting replicated closed indices {pull}39644[#39644] (issue: {issue}33888[#33888]) * Add support for S3 intelligent tiering (#38836) {pull}39376[#39376] (issue: {issue}38836[#38836]) Store:: * Log missing file exception when failing to read metadata snapshot {pull}32920[#32920] Suggesters:: * Tie-break completion suggestions with same score and surface form {pull}39564[#39564] [[bug-7.2.0]] [float] === Bug fixes Aggregations:: * Update error message for allowed characters in aggregation names {pull}41573[#41573] (issue: {issue}41567[#41567]) * Fix FiltersAggregation NPE when `filters` is empty {pull}41459[#41459] (issue: {issue}41408[#41408]) * Fix unmapped field handling in the composite aggregation {pull}41280[#41280] Allocation:: * Avoid bubbling up failures from a shard that is recovering {pull}42287[#42287] (issues: {issue}30919[#30919], {issue}40107[#40107]) * Changed the position of reset counter {pull}39678[#39678] (issue: {issue}39546[#39546]) Analysis:: * Always use IndexAnalyzers in analyze transport action {pull}40769[#40769] (issue: {issue}29021[#29021]) * Fix anaylze NullPointerException when AnalyzeTokenList tokens is null {pull}39332[#39332] * Fix anaylze NullPointerException when AnalyzeTokenList tokens is null {pull}39180[#39180] Authentication:: * Refresh remote JWKs on all errors {pull}42850[#42850] * Fix refresh remote JWKS logic {pull}42662[#42662] * Fix settings prefix for realm truststore password {pull}42336[#42336] (issues: {issue}30241[#30241], {issue}41663[#41663]) * Merge claims from userinfo and ID Token correctly {pull}42277[#42277] * Do not refresh realm cache unless required {pull}42169[#42169] (issue: {issue}35218[#35218]) * Amend `prepareIndexIfNeededThenExecute` for security token refresh {pull}41697[#41697] * Fix token Invalidation when retries exhausted {pull}39799[#39799] Authorization:: * _cat/indices with Security, hide names when wildcard {pull}38824[#38824] (issue: {issue}37190[#37190]) CCR:: * CCR should not replicate private/internal settings {pull}43067[#43067] (issue: {issue}41268[#41268]) CRUD:: * Fix NPE when rejecting bulk updates {pull}42923[#42923] Cluster Coordination:: * Reset state recovery after successful recovery {pull}42576[#42576] (issue: {issue}39172[#39172]) * Omit non-masters in ClusterFormationFailureHelper {pull}41344[#41344] Data Frame:: * Rewrite start and stop to answer with acknowledged {pull}42589[#42589] (issue: {issue}42450[#42450]) * Set DF task state to stopped when stopping {pull}42516[#42516] (issue: {issue}42441[#42441]) * Add support for fixed_interval, calendar_interval, remove interval {pull}42427[#42427] (issues: {issue}33727[#33727], {issue}42297[#42297]) Distributed:: * Avoid loading retention leases while writing them {pull}42620[#42620] (issue: {issue}41430[#41430]) * Do not use ifSeqNo for update requests on mixed cluster {pull}42596[#42596] (issue: {issue}42561[#42561]) * Prevent order being lost for _nodes API filters {pull}42045[#42045] (issue: {issue}41885[#41885]) * Ensure flush happen before closing an index {pull}40184[#40184] (issue: {issue}36342[#36342]) Engine:: * Account soft deletes for committed segments {pull}43126[#43126] (issue: {issue}43103[#43103]) * Fix assertion error when caching the result of a search in a read-only index {pull}41900[#41900] (issue: {issue}41795[#41795]) * Close and acquire commit during reset engine fix {pull}41584[#41584] (issue: {issue}38561[#38561]) Features/ILM:: * Make ILM force merging best effort {pull}43246[#43246] (issues: {issue}42824[#42824], {issue}43245[#43245]) * Narrow period of Shrink action in which ILM prevents stopping {pull}43254[#43254] (issue: {issue}43253[#43253]) Features/Indices APIs:: * Add pre-upgrade check to test cluster routing allocation is enabled {pull}39340[#39340] (issue: {issue}39339[#39339]) Features/Ingest:: * Build local year inside DateFormat lambda {pull}42120[#42120] Features/Java High Level REST Client:: * Fixes a bug in AnalyzeRequest.toXContent() {pull}42795[#42795] (issues: {issue}39670[#39670], {issue}42197[#42197]) * StackOverflowError when calling BulkRequest#add {pull}41672[#41672] * HLRC: Convert xpack methods to client side objects {pull}40705[#40705] (issue: {issue}40511[#40511]) * Rest-High-Level-Client:fix uri encode bug when url path start with '/' {pull}34436[#34436] (issue: {issue}34433[#34433]) Features/Watcher:: * NullPointerException when creating a watch with Jira action (#41922) {pull}42081[#42081] * Fix minor watcher bug, unmute test, add additional debug logging {pull}41765[#41765] (issues: {issue}29893[#29893], {issue}30777[#30777], {issue}33291[#33291], {issue}35361[#35361]) * Fix Watcher deadlock that can cause in-abilty to index documents. {pull}41418[#41418] (issue: {issue}41390[#41390]) Geo:: * Improve error message when polygons contains twice the same point in no-consecutive position {pull}41051[#41051] (issue: {issue}40998[#40998]) Highlighting:: * Bug fix for AnnotatedTextHighlighter - port of 39525 {pull}39749[#39749] (issue: {issue}39525[#39525]) Infra/Core:: * Fix roundUp parsing with composite patterns {pull}43080[#43080] (issue: {issue}42835[#42835]) * scheduleAtFixedRate would hang {pull}42993[#42993] (issue: {issue}38441[#38441]) * Only ignore IOException when fsyncing on dirs {pull}42972[#42972] (issue: {issue}42950[#42950]) * Fix node close stopwatch usage {pull}41918[#41918] * Make ISO8601 date parser accept timezone when time does not have seconds {pull}41896[#41896] * Allow unknown task time in QueueResizingEsTPE {pull}41810[#41810] (issue: {issue}41448[#41448]) * Parse composite patterns using ClassicFormat.parseObject {pull}40100[#40100] (issue: {issue}39916[#39916]) Infra/Packaging:: * Don't create tempdir for cli scripts {pull}41913[#41913] (issue: {issue}34445[#34445]) * Cleanup plugin bin directories {pull}41907[#41907] (issue: {issue}18109[#18109]) * Update lintian overrides {pull}41561[#41561] (issue: {issue}17185[#17185]) * Resolve JAVA_HOME at windows service install time {pull}39714[#39714] (issue: {issue}30720[#30720]) Infra/Settings:: * Handle UTF-8 values in the keystore {pull}39496[#39496] * Handle empty input in AddStringKeyStoreCommand {pull}39490[#39490] (issue: {issue}39413[#39413]) Machine Learning:: * Fix possible race condition when closing an opening job {pull}42506[#42506] * Exclude analysis fields with core field names from anomaly results {pull}41093[#41093] (issue: {issue}39406[#39406]) Mapping:: * Fix possible NPE in put mapping validators {pull}43000[#43000] (issue: {issue}37675[#37675]) * Fix merging of text field mappers {pull}40627[#40627] * Fix an off-by-one error in the vector field dimension limit. {pull}40489[#40489] * Fix not Recognizing Disabled Object Mapper {pull}39862[#39862] (issue: {issue}39456[#39456]) * Avoid copying the field alias lookup structure unnecessarily. {pull}39726[#39726] * Handle NaNs when detrending seasonal components {ml-pull}408[#408] Network:: * Don't require TLS for single node clusters {pull}42826[#42826] * Handle WRAP ops during SSL read {pull}41611[#41611] * SSLDriver can transition to CLOSED in handshake {pull}41458[#41458] * Handle Bulk Requests on Write Threadpool {pull}40866[#40866] (issues: {issue}39128[#39128], {issue}39658[#39658]) Percolator:: * Fixed ignoring name parameter for percolator queries {pull}42598[#42598] (issue: {issue}40405[#40405]) Recovery:: * Use translog to estimate number of operations in recovery {pull}42211[#42211] (issue: {issue}38904[#38904]) * Recovery with syncId should verify seqno infos {pull}41265[#41265] * Retain history for peer recovery using leases {pull}39133[#39133] Reindex:: * Remote reindex failure parse fix {pull}42928[#42928] * Fix concurrent search and index delete {pull}42621[#42621] (issue: {issue}28053[#28053]) * Propogate version in reindex from remote search {pull}42412[#42412] (issue: {issue}31908[#31908]) Rollup:: * Fix max boundary for rollup jobs that use a delay {pull}42158[#42158] * Cleanup exceptions thrown during RollupSearch {pull}41272[#41272] (issue: {issue}38015[#38015]) * Validate timezones based on rules not string comparision {pull}36237[#36237] (issue: {issue}36229[#36229]) SQL:: * Fix wrong results when sorting on aggregate {pull}43154[#43154] (issue: {issue}42851[#42851]) * Cover the Integer type when extracting values from _source {pull}42859[#42859] (issue: {issue}42858[#42858]) * Fix precedence of `::` psql like CAST operator {pull}40665[#40665] Search:: * Fix IntervalBuilder#analyzeText to never return `null` {pull}42750[#42750] (issue: {issue}42587[#42587]) * Fix sorting on nested field with unmapped {pull}42451[#42451] (issue: {issue}33644[#33644]) * Always set terminated_early if terminate_after is set in the search request {pull}40839[#40839] (issue: {issue}33949[#33949]) * more_like_this query to throw an error if the like fields is not provided {pull}40632[#40632] * Fixing 503 Service Unavailable errors during fetch phase {pull}39086[#39086] * Fix IndexSearcherWrapper visibility {pull}39071[#39071] (issue: {issue}30758[#30758]) Snapshot/Restore:: * Fix Azure List by Prefix Bug {pull}42713[#42713] * Remove Harmful Exists Check from BlobStoreFormat {pull}41898[#41898] (issue: {issue}41882[#41882]) * Restricts naming for repositories {pull}41008[#41008] (issue: {issue}40817[#40817]) * SNAPSHOT: More Resilient Writes to Blob Stores {pull}36927[#36927] (issue: {issue}25281[#25281]) Suggesters:: * Handle min_doc_freq in suggesters {pull}40840[#40840] (issue: {issue}16764[#16764]) [[upgrade-7.2.0]] [float] === Upgrades Features/Watcher:: * Replace javax activation with jakarta activation {pull}40247[#40247] * Replace java mail with jakarta mail {pull}40088[#40088] Infra/Core:: * Update to joda time 2.10.2 {pull}42199[#42199] Network:: * Upgrade to Netty 4.1.35 {pull}41499[#41499] ",12249,True,2999.9345468020333,median "= v1beta1.ValidatingWebhookConfiguration {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] ValidatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and object without changing it. == Object Schema Expand or mouse-over a field for more information about it. ++++
apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
webhooks:
- clientConfig:
- caBundle:
service:
name:
namespace:
path:
url:
failurePolicy:
name:
namespaceSelector:
matchExpressions:
- key:
operator:
values:
- [string]:
matchLabels:
[string]:
rules:
- apiGroups:
- - [string]:
apiVersions:
- [string]:
operations:
- [string]:
resources:
- [string]:
++++ == Operations [[Post-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations]] === Create a ValidatingWebhookConfiguration Create a ValidatingWebhookConfiguration ==== HTTP request ---- POST /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ValidatingWebhookConfiguration"", ""apiVersion"": ""admissionregistration.k8s.io/v1beta1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations <<'EOF' { ""kind"": ""ValidatingWebhookConfiguration"", ""apiVersion"": ""admissionregistration.k8s.io/v1beta1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta1.ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta1.ValidatingWebhookConfiguration |201 Created|v1beta1.ValidatingWebhookConfiguration |202 Accepted|v1beta1.ValidatingWebhookConfiguration |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations-name]] === Get a ValidatingWebhookConfiguration Read the specified ValidatingWebhookConfiguration ==== HTTP request ---- GET /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. |export|Should this value be exported. Export strips fields that a user can not specify. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta1.ValidatingWebhookConfiguration |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations]] === Get all ValidatingWebhookConfigurations List or watch objects of kind ValidatingWebhookConfiguration ==== HTTP request ---- GET /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta1.ValidatingWebhookConfigurationList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-admissionregistration.k8s.io-v1beta1-watch-validatingwebhookconfigurations-name]] === Watch a ValidatingWebhookConfiguration Watch changes to an object of kind ValidatingWebhookConfiguration ==== HTTP request ---- GET /apis/admissionregistration.k8s.io/v1beta1/watch/validatingwebhookconfigurations/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/watch/validatingwebhookconfigurations/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-admissionregistration.k8s.io-v1beta1-watch-validatingwebhookconfigurations]] === Watch all ValidatingWebhookConfigurations Watch individual changes to a list of ValidatingWebhookConfiguration ==== HTTP request ---- GET /apis/admissionregistration.k8s.io/v1beta1/watch/validatingwebhookconfigurations HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/watch/validatingwebhookconfigurations ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations-name]] === Update a ValidatingWebhookConfiguration Replace the specified ValidatingWebhookConfiguration ==== HTTP request ---- PUT /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ValidatingWebhookConfiguration"", ""apiVersion"": ""admissionregistration.k8s.io/v1beta1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME <<'EOF' { ""kind"": ""ValidatingWebhookConfiguration"", ""apiVersion"": ""admissionregistration.k8s.io/v1beta1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta1.ValidatingWebhookConfiguration |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta1.ValidatingWebhookConfiguration |201 Created|v1beta1.ValidatingWebhookConfiguration |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations-name]] === Patch a ValidatingWebhookConfiguration Partially update the specified ValidatingWebhookConfiguration ==== HTTP request ---- PATCH /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta1.ValidatingWebhookConfiguration |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations-name]] === Delete a ValidatingWebhookConfiguration Delete a ValidatingWebhookConfiguration ==== HTTP request ---- DELETE /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations]] === Delete all ValidatingWebhookConfigurations Delete collection of ValidatingWebhookConfiguration ==== HTTP request ---- DELETE /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",12061,False,2048.201555320845,median "/*========================================================================= Program: Visualization Toolkit Module: vtkImageData.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include ""vtkImageData.h"" #include ""vtkCellData.h"" #include ""vtkDataArray.h"" #include ""vtkGenericCell.h"" #include ""vtkInformation.h"" #include ""vtkInformationIntegerKey.h"" #include ""vtkInformationVector.h"" #include ""vtkLargeInteger.h"" #include ""vtkLine.h"" #include ""vtkMath.h"" #include ""vtkObjectFactory.h"" #include ""vtkPixel.h"" #include ""vtkPointData.h"" #include ""vtkPoints.h"" #include ""vtkVertex.h"" #include ""vtkVoxel.h"" vtkStandardNewMacro(vtkImageData); //---------------------------------------------------------------------------- vtkImageData::vtkImageData() { int idx; this->Vertex = 0; this->Line = 0; this->Pixel = 0; this->Voxel = 0; this->DataDescription = VTK_EMPTY; for (idx = 0; idx < 3; ++idx) { this->Dimensions[idx] = 0; this->Increments[idx] = 0; this->Origin[idx] = 0.0; this->Spacing[idx] = 1.0; } int extent[6] = {0, -1, 0, -1, 0, -1}; memcpy(this->Extent, extent, 6*sizeof(int)); this->Information->Set(vtkDataObject::DATA_EXTENT_TYPE(), VTK_3D_EXTENT); this->Information->Set(vtkDataObject::DATA_EXTENT(), this->Extent, 6); } //---------------------------------------------------------------------------- vtkImageData::~vtkImageData() { if (this->Vertex) { this->Vertex->Delete(); } if (this->Line) { this->Line->Delete(); } if (this->Pixel) { this->Pixel->Delete(); } if (this->Voxel) { this->Voxel->Delete(); } } //---------------------------------------------------------------------------- // Copy the geometric and topological structure of an input structured points // object. void vtkImageData::CopyStructure(vtkDataSet *ds) { vtkImageData *sPts=static_cast(ds); this->Initialize(); int i; for (i=0; i<3; i++) { this->Dimensions[i] = sPts->Dimensions[i]; this->Spacing[i] = sPts->Spacing[i]; this->Origin[i] = sPts->Origin[i]; } this->SetExtent(sPts->GetExtent()); } //---------------------------------------------------------------------------- void vtkImageData::Initialize() { this->Superclass::Initialize(); if(this->Information) { this->SetDimensions(0,0,0); } } //---------------------------------------------------------------------------- void vtkImageData::CopyInformationFromPipeline(vtkInformation* information) { // Let the superclass copy whatever it wants. this->Superclass::CopyInformationFromPipeline(information); this->CopyOriginAndSpacingFromPipeline(information); } //---------------------------------------------------------------------------- // Graphics filters reallocate every execute. Image filters try to reuse // the scalars. void vtkImageData::PrepareForNewData() { // free everything but the scalars vtkDataArray *scalars = this->GetPointData()->GetScalars(); if (scalars) { scalars->Register(this); } this->Initialize(); if (scalars) { this->GetPointData()->SetScalars(scalars); scalars->UnRegister(this); } } //---------------------------------------------------------------------------- // The input data object must be of type vtkImageData or a subclass! void vtkImageData::CopyTypeSpecificInformation( vtkDataObject *data ) { vtkImageData *image = static_cast(data); // Now do the specific stuff this->SetOrigin( image->GetOrigin() ); this->SetSpacing( image->GetSpacing() ); //this->SetScalarType( image->GetScalarType() ); //this->SetNumberOfScalarComponents( //image->GetNumberOfScalarComponents() ); } //---------------------------------------------------------------------------- template unsigned long vtkImageDataGetTypeSize(T*) { return sizeof(T); } //---------------------------------------------------------------------------- vtkCell *vtkImageData::GetCell(vtkIdType cellId) { vtkCell *cell = NULL; int loc[3]; vtkIdType idx, npts; int iMin, iMax, jMin, jMax, kMin, kMax; double x[3]; const double *origin = this->Origin; const double *spacing = this->Spacing; const int* extent = this->Extent; // Use vtkIdType to avoid overflow on large images vtkIdType dims[3]; dims[0] = extent[1] - extent[0] + 1; dims[1] = extent[3] - extent[2] + 1; dims[2] = extent[5] - extent[4] + 1; vtkIdType d01 = dims[0]*dims[1]; iMin = iMax = jMin = jMax = kMin = kMax = 0; if (dims[0] == 0 || dims[1] == 0 || dims[2] == 0) { vtkErrorMacro(""Requesting a cell from an empty image.""); return NULL; } switch (this->DataDescription) { case VTK_EMPTY: //cell = this->EmptyCell; return NULL; case VTK_SINGLE_POINT: // cellId can only be = 0 cell = this->Vertex; break; case VTK_X_LINE: iMin = cellId; iMax = cellId + 1; cell = this->Line; break; case VTK_Y_LINE: jMin = cellId; jMax = cellId + 1; cell = this->Line; break; case VTK_Z_LINE: kMin = cellId; kMax = cellId + 1; cell = this->Line; break; case VTK_XY_PLANE: iMin = cellId % (dims[0]-1); iMax = iMin + 1; jMin = cellId / (dims[0]-1); jMax = jMin + 1; cell = this->Pixel; break; case VTK_YZ_PLANE: jMin = cellId % (dims[1]-1); jMax = jMin + 1; kMin = cellId / (dims[1]-1); kMax = kMin + 1; cell = this->Pixel; break; case VTK_XZ_PLANE: iMin = cellId % (dims[0]-1); iMax = iMin + 1; kMin = cellId / (dims[0]-1); kMax = kMin + 1; cell = this->Pixel; break; case VTK_XYZ_GRID: iMin = cellId % (dims[0] - 1); iMax = iMin + 1; jMin = (cellId / (dims[0] - 1)) % (dims[1] - 1); jMax = jMin + 1; kMin = cellId / ((dims[0] - 1) * (dims[1] - 1)); kMax = kMin + 1; cell = this->Voxel; break; } // Extract point coordinates and point ids // Ids are relative to extent min. npts = 0; for (loc[2]=kMin; loc[2]<=kMax; loc[2]++) { x[2] = origin[2] + (loc[2]+extent[4]) * spacing[2]; for (loc[1]=jMin; loc[1]<=jMax; loc[1]++) { x[1] = origin[1] + (loc[1]+extent[2]) * spacing[1]; for (loc[0]=iMin; loc[0]<=iMax; loc[0]++) { x[0] = origin[0] + (loc[0]+extent[0]) * spacing[0]; idx = loc[0] + loc[1]*dims[0] + loc[2]*d01; cell->PointIds->SetId(npts,idx); cell->Points->SetPoint(npts++,x); } } } return cell; } //---------------------------------------------------------------------------- void vtkImageData::GetCell(vtkIdType cellId, vtkGenericCell *cell) { vtkIdType npts, idx; int loc[3]; int iMin, iMax, jMin, jMax, kMin, kMax; const double *origin = this->Origin; const double *spacing = this->Spacing; double x[3]; const int* extent = this->Extent; vtkIdType dims[3]; dims[0] = extent[1] - extent[0] + 1; dims[1] = extent[3] - extent[2] + 1; dims[2] = extent[5] - extent[4] + 1; vtkIdType d01 = dims[0]*dims[1]; iMin = iMax = jMin = jMax = kMin = kMax = 0; if (dims[0] == 0 || dims[1] == 0 || dims[2] == 0) { vtkErrorMacro(""Requesting a cell from an empty image.""); cell->SetCellTypeToEmptyCell(); return; } switch (this->DataDescription) { case VTK_EMPTY: cell->SetCellTypeToEmptyCell(); return; case VTK_SINGLE_POINT: // cellId can only be = 0 cell->SetCellTypeToVertex(); break; case VTK_X_LINE: iMin = cellId; iMax = cellId + 1; cell->SetCellTypeToLine(); break; case VTK_Y_LINE: jMin = cellId; jMax = cellId + 1; cell->SetCellTypeToLine(); break; case VTK_Z_LINE: kMin = cellId; kMax = cellId + 1; cell->SetCellTypeToLine(); break; case VTK_XY_PLANE: iMin = cellId % (dims[0]-1); iMax = iMin + 1; jMin = cellId / (dims[0]-1); jMax = jMin + 1; cell->SetCellTypeToPixel(); break; case VTK_YZ_PLANE: jMin = cellId % (dims[1]-1); jMax = jMin + 1; kMin = cellId / (dims[1]-1); kMax = kMin + 1; cell->SetCellTypeToPixel(); break; case VTK_XZ_PLANE: iMin = cellId % (dims[0]-1); iMax = iMin + 1; kMin = cellId / (dims[0]-1); kMax = kMin + 1; cell->SetCellTypeToPixel(); break; case VTK_XYZ_GRID: iMin = cellId % (dims[0] - 1); iMax = iMin + 1; jMin = (cellId / (dims[0] - 1)) % (dims[1] - 1); jMax = jMin + 1; kMin = cellId / ((dims[0] - 1) * (dims[1] - 1)); kMax = kMin + 1; cell->SetCellTypeToVoxel(); break; } // Extract point coordinates and point ids for (npts=0,loc[2]=kMin; loc[2]<=kMax; loc[2]++) { x[2] = origin[2] + (loc[2]+extent[4]) * spacing[2]; for (loc[1]=jMin; loc[1]<=jMax; loc[1]++) { x[1] = origin[1] + (loc[1]+extent[2]) * spacing[1]; for (loc[0]=iMin; loc[0]<=iMax; loc[0]++) { x[0] = origin[0] + (loc[0]+extent[0]) * spacing[0]; idx = loc[0] + loc[1]*dims[0] + loc[2]*d01; cell->PointIds->SetId(npts,idx); cell->Points->SetPoint(npts++,x); } } } } //---------------------------------------------------------------------------- // Fast implementation of GetCellBounds(). Bounds are calculated without // constructing a cell. void vtkImageData::GetCellBounds(vtkIdType cellId, double bounds[6]) { int loc[3], iMin, iMax, jMin, jMax, kMin, kMax; double x[3]; const double *origin = this->Origin; const double *spacing = this->Spacing; const int* extent = this->Extent; vtkIdType dims[3]; dims[0] = extent[1] - extent[0] + 1; dims[1] = extent[3] - extent[2] + 1; dims[2] = extent[5] - extent[4] + 1; iMin = iMax = jMin = jMax = kMin = kMax = 0; if (dims[0] == 0 || dims[1] == 0 || dims[2] == 0) { vtkErrorMacro(""Requesting cell bounds from an empty image.""); bounds[0] = bounds[1] = bounds[2] = bounds[3] = bounds[4] = bounds[5] = 0.0; return; } switch (this->DataDescription) { case VTK_EMPTY: return; case VTK_SINGLE_POINT: // cellId can only be = 0 break; case VTK_X_LINE: iMin = cellId; iMax = cellId + 1; break; case VTK_Y_LINE: jMin = cellId; jMax = cellId + 1; break; case VTK_Z_LINE: kMin = cellId; kMax = cellId + 1; break; case VTK_XY_PLANE: iMin = cellId % (dims[0]-1); iMax = iMin + 1; jMin = cellId / (dims[0]-1); jMax = jMin + 1; break; case VTK_YZ_PLANE: jMin = cellId % (dims[1]-1); jMax = jMin + 1; kMin = cellId / (dims[1]-1); kMax = kMin + 1; break; case VTK_XZ_PLANE: iMin = cellId % (dims[0]-1); iMax = iMin + 1; kMin = cellId / (dims[0]-1); kMax = kMin + 1; break; case VTK_XYZ_GRID: iMin = cellId % (dims[0] - 1); iMax = iMin + 1; jMin = (cellId / (dims[0] - 1)) % (dims[1] - 1); jMax = jMin + 1; kMin = cellId / ((dims[0] - 1) * (dims[1] - 1)); kMax = kMin + 1; break; } // carefully compute the bounds if (kMax >= kMin && jMax >= jMin && iMax >= iMin) { bounds[0] = bounds[2] = bounds[4] = VTK_DOUBLE_MAX; bounds[1] = bounds[3] = bounds[5] = VTK_DOUBLE_MIN; // Extract point coordinates for (loc[2]=kMin; loc[2]<=kMax; loc[2]++) { x[2] = origin[2] + (loc[2]+extent[4]) * spacing[2]; bounds[4] = (x[2] < bounds[4] ? x[2] : bounds[4]); bounds[5] = (x[2] > bounds[5] ? x[2] : bounds[5]); } for (loc[1]=jMin; loc[1]<=jMax; loc[1]++) { x[1] = origin[1] + (loc[1]+extent[2]) * spacing[1]; bounds[2] = (x[1] < bounds[2] ? x[1] : bounds[2]); bounds[3] = (x[1] > bounds[3] ? x[1] : bounds[3]); } for (loc[0]=iMin; loc[0]<=iMax; loc[0]++) { x[0] = origin[0] + (loc[0]+extent[0]) * spacing[0]; bounds[0] = (x[0] < bounds[0] ? x[0] : bounds[0]); bounds[1] = (x[0] > bounds[1] ? x[0] : bounds[1]); } } else { vtkMath::UninitializeBounds(bounds); } } //---------------------------------------------------------------------------- double *vtkImageData::GetPoint(vtkIdType ptId) { static double x[3]; int i, loc[3]; const double *origin = this->Origin; const double *spacing = this->Spacing; const int* extent = this->Extent; vtkIdType dims[3]; dims[0] = extent[1] - extent[0] + 1; dims[1] = extent[3] - extent[2] + 1; dims[2] = extent[5] - extent[4] + 1; x[0] = x[1] = x[2] = 0.0; if (dims[0] == 0 || dims[1] == 0 || dims[2] == 0) { vtkErrorMacro(""Requesting a point from an empty image.""); return x; } // ""loc"" holds the point x,y,z indices loc[0] = loc[1] = loc[2] = 0; switch (this->DataDescription) { case VTK_EMPTY: return x; case VTK_SINGLE_POINT: break; case VTK_X_LINE: loc[0] = ptId; break; case VTK_Y_LINE: loc[1] = ptId; break; case VTK_Z_LINE: loc[2] = ptId; break; case VTK_XY_PLANE: loc[0] = ptId % dims[0]; loc[1] = ptId / dims[0]; break; case VTK_YZ_PLANE: loc[1] = ptId % dims[1]; loc[2] = ptId / dims[1]; break; case VTK_XZ_PLANE: loc[0] = ptId % dims[0]; loc[2] = ptId / dims[0]; break; case VTK_XYZ_GRID: loc[0] = ptId % dims[0]; loc[1] = (ptId / dims[0]) % dims[1]; loc[2] = ptId / (dims[0]*dims[1]); break; } for (i=0; i<3; i++) { x[i] = origin[i] + (loc[i]+extent[i*2]) * spacing[i]; } return x; } //---------------------------------------------------------------------------- vtkIdType vtkImageData::FindPoint(double x[3]) { int i, loc[3]; double d; const double *origin = this->Origin; const double *spacing = this->Spacing; const int* extent = this->Extent; vtkIdType dims[3]; dims[0] = extent[1] - extent[0] + 1; dims[1] = extent[3] - extent[2] + 1; dims[2] = extent[5] - extent[4] + 1; // // Compute the ijk location // for (i=0; i<3; i++) { d = x[i] - origin[i]; loc[i] = vtkMath::Floor((d / spacing[i]) + 0.5); if ( loc[i] < extent[i*2] || loc[i] > extent[i*2+1] ) { return -1; } // since point id is relative to the first point actually stored loc[i] -= extent[i*2]; } // // From this location get the point id // return loc[2]*dims[0]*dims[1] + loc[1]*dims[0] + loc[0]; } //---------------------------------------------------------------------------- vtkIdType vtkImageData::FindCell(double x[3], vtkCell *vtkNotUsed(cell), vtkGenericCell *vtkNotUsed(gencell), vtkIdType vtkNotUsed(cellId), double tol2, int& subId, double pcoords[3], double *weights) { return this->FindCell( x, NULL, 0, tol2, subId, pcoords, weights ); } //---------------------------------------------------------------------------- vtkIdType vtkImageData::FindCell(double x[3], vtkCell *vtkNotUsed(cell), vtkIdType vtkNotUsed(cellId), double tol2, int& subId, double pcoords[3], double *weights) { int idx[3]; // Compute the voxel index if ( this->ComputeStructuredCoordinates(x, idx, pcoords) == 0 ) { // If voxel index is out of bounds, check point ""x"" against the // bounds to see if within tolerance of the bounds. const int* extent = this->Extent; const double* spacing = this->Spacing; const double* bounds = this->Bounds; // Compute squared distance of point x from the boundary double dist2 = 0.0; for (int i=0; i<3; i++) { int minIdx = extent[i*2]; int maxIdx = extent[i*2+1]; int negSpacing = (spacing[i] < 0); double minBound = bounds[i*2 + negSpacing]; double maxBound = bounds[i*2 + (1-negSpacing)]; if ( idx[i] < minIdx ) { idx[i] = minIdx; pcoords[i] = 0.0; double dist = x[i] - minBound; dist2 += dist*dist; } else if ( idx[i] >= maxIdx ) { if (maxIdx == minIdx) { idx[i] = minIdx; pcoords[i] = 0.0; } else { idx[i] = maxIdx-1; pcoords[i] = 1.0; } double dist = x[i] - maxBound; dist2 += dist*dist; } } // Check squared distance against the tolerance if (dist2 > tol2) { return -1; } } if (weights) { // Shift parametric coordinates for XZ/YZ planes if( this->DataDescription == VTK_XZ_PLANE ) { pcoords[1] = pcoords[2]; pcoords[2] = 0.0; } else if( this->DataDescription == VTK_YZ_PLANE ) { pcoords[0] = pcoords[1]; pcoords[1] = pcoords[2]; pcoords[2] = 0.0; } else if( this->DataDescription == VTK_XY_PLANE ) { pcoords[2] = 0.0; } vtkVoxel::InterpolationFunctions( pcoords, weights ); } // // From this location get the cell id // subId = 0; return this->ComputeCellId(idx); } //---------------------------------------------------------------------------- vtkCell *vtkImageData::FindAndGetCell(double x[3], vtkCell *vtkNotUsed(cell), vtkIdType vtkNotUsed(cellId), double tol2, int& subId, double pcoords[3], double *weights) { vtkIdType cellId = this->FindCell(x, 0, 0, tol2, subId, pcoords, 0); if (cellId < 0) { return NULL; } vtkCell *cell = this->GetCell(cellId); cell->InterpolateFunctions(pcoords, weights); return cell; } //---------------------------------------------------------------------------- int vtkImageData::GetCellType(vtkIdType vtkNotUsed(cellId)) { switch (this->DataDescription) { case VTK_EMPTY: return VTK_EMPTY_CELL; case VTK_SINGLE_POINT: return VTK_VERTEX; case VTK_X_LINE: case VTK_Y_LINE: case VTK_Z_LINE: return VTK_LINE; case VTK_XY_PLANE: case VTK_YZ_PLANE: case VTK_XZ_PLANE: return VTK_PIXEL; case VTK_XYZ_GRID: return VTK_VOXEL; default: vtkErrorMacro(<<""Bad data description!""); return VTK_EMPTY_CELL; } } //---------------------------------------------------------------------------- void vtkImageData::ComputeBounds() { if ( this->GetMTime() <= this->ComputeTime ) { return; } const double *origin = this->Origin; const double *spacing = this->Spacing; const int* extent = this->Extent; if ( extent[0] > extent[1] || extent[2] > extent[3] || extent[4] > extent[5] ) { vtkMath::UninitializeBounds(this->Bounds); } else { int swapXBounds = (spacing[0] < 0); // 1 if true, 0 if false int swapYBounds = (spacing[1] < 0); // 1 if true, 0 if false int swapZBounds = (spacing[2] < 0); // 1 if true, 0 if false this->Bounds[0] = origin[0] + (extent[0+swapXBounds] * spacing[0]); this->Bounds[2] = origin[1] + (extent[2+swapYBounds] * spacing[1]); this->Bounds[4] = origin[2] + (extent[4+swapZBounds] * spacing[2]); this->Bounds[1] = origin[0] + (extent[1-swapXBounds] * spacing[0]); this->Bounds[3] = origin[1] + (extent[3-swapYBounds] * spacing[1]); this->Bounds[5] = origin[2] + (extent[5-swapZBounds] * spacing[2]); } this->ComputeTime.Modified(); } //---------------------------------------------------------------------------- // Given structured coordinates (i,j,k) for a voxel cell, compute the eight // gradient values for the voxel corners. The order in which the gradient // vectors are arranged corresponds to the ordering of the voxel points. // Gradient vector is computed by central differences (except on edges of // volume where forward difference is used). The scalars s are the scalars // from which the gradient is to be computed. This method will treat // only 3D structured point datasets (i.e., volumes). void vtkImageData::GetVoxelGradient(int i, int j, int k, vtkDataArray *s, vtkDataArray *g) { double gv[3]; int ii, jj, kk, idx=0; for ( kk=0; kk < 2; kk++) { for ( jj=0; jj < 2; jj++) { for ( ii=0; ii < 2; ii++) { this->GetPointGradient(i+ii, j+jj, k+kk, s, gv); g->SetTuple(idx++, gv); } } } } //---------------------------------------------------------------------------- // Given structured coordinates (i,j,k) for a point in a structured point // dataset, compute the gradient vector from the scalar data at that point. // The scalars s are the scalars from which the gradient is to be computed. // This method will treat structured point datasets of any dimension. void vtkImageData::GetPointGradient(int i, int j, int k, vtkDataArray *s, double g[3]) { const double *ar = this->Spacing; double sp, sm; const int *extent = this->Extent; vtkIdType dims[3]; dims[0] = extent[1] - extent[0] + 1; dims[1] = extent[3] - extent[2] + 1; dims[2] = extent[5] - extent[4] + 1; vtkIdType ijsize=dims[0]*dims[1]; // Adjust i,j,k to the start of the extent i -= extent[0]; j -= extent[2]; k -= extent[4]; // Check for out-of-bounds if (i < 0 || i >= dims[0] || j < 0 || j >= dims[1] || k < 0 || k >= dims[2]) { g[0] = g[1] = g[2] = 0.0; return; } // x-direction if ( dims[0] == 1 ) { g[0] = 0.0; } else if ( i == 0 ) { sp = s->GetComponent(i+1 + j*dims[0] + k*ijsize, 0); sm = s->GetComponent(i + j*dims[0] + k*ijsize, 0); g[0] = (sm - sp) / ar[0]; } else if ( i == (dims[0]-1) ) { sp = s->GetComponent(i + j*dims[0] + k*ijsize,0); sm = s->GetComponent(i-1 + j*dims[0] + k*ijsize,0); g[0] = (sm - sp) / ar[0]; } else { sp = s->GetComponent(i+1 + j*dims[0] + k*ijsize,0); sm = s->GetComponent(i-1 + j*dims[0] + k*ijsize,0); g[0] = 0.5 * (sm - sp) / ar[0]; } // y-direction if ( dims[1] == 1 ) { g[1] = 0.0; } else if ( j == 0 ) { sp = s->GetComponent(i + (j+1)*dims[0] + k*ijsize,0); sm = s->GetComponent(i + j*dims[0] + k*ijsize,0); g[1] = (sm - sp) / ar[1]; } else if ( j == (dims[1]-1) ) { sp = s->GetComponent(i + j*dims[0] + k*ijsize,0); sm = s->GetComponent(i + (j-1)*dims[0] + k*ijsize,0); g[1] = (sm - sp) / ar[1]; } else { sp = s->GetComponent(i + (j+1)*dims[0] + k*ijsize,0); sm = s->GetComponent(i + (j-1)*dims[0] + k*ijsize,0); g[1] = 0.5 * (sm - sp) / ar[1]; } // z-direction if ( dims[2] == 1 ) { g[2] = 0.0; } else if ( k == 0 ) { sp = s->GetComponent(i + j*dims[0] + (k+1)*ijsize,0); sm = s->GetComponent(i + j*dims[0] + k*ijsize,0); g[2] = (sm - sp) / ar[2]; } else if ( k == (dims[2]-1) ) { sp = s->GetComponent(i + j*dims[0] + k*ijsize,0); sm = s->GetComponent(i + j*dims[0] + (k-1)*ijsize,0); g[2] = (sm - sp) / ar[2]; } else { sp = s->GetComponent(i + j*dims[0] + (k+1)*ijsize,0); sm = s->GetComponent(i + j*dims[0] + (k-1)*ijsize,0); g[2] = 0.5 * (sm - sp) / ar[2]; } } //---------------------------------------------------------------------------- // Set dimensions of structured points dataset. void vtkImageData::SetDimensions(int i, int j, int k) { this->SetExtent(0, i-1, 0, j-1, 0, k-1); } //---------------------------------------------------------------------------- // Set dimensions of structured points dataset. void vtkImageData::SetDimensions(const int dim[3]) { this->SetExtent(0, dim[0]-1, 0, dim[1]-1, 0, dim[2]-1); } //---------------------------------------------------------------------------- // Convenience function computes the structured coordinates for a point x[3]. // The voxel is specified by the array ijk[3], and the parametric coordinates // in the cell are specified with pcoords[3]. The function returns a 0 if the // point x is outside of the volume, and a 1 if inside the volume. int vtkImageData::ComputeStructuredCoordinates(double x[3], int ijk[3], double pcoords[3]) { // tolerance is needed for 2D data (this is squared tolerance) const double tol2 = 1e-12; const int* extent = this->Extent; const double* spacing = this->Spacing; const double* origin = this->Origin; const double* bounds = NULL; // // Compute the ijk location // int isInBounds = 1; for (int i = 0; i < 3; i++) { double d = x[i] - origin[i]; double doubleLoc = d / spacing[i]; // Floor for negative indexes. ijk[i] = vtkMath::Floor(doubleLoc); pcoords[i] = doubleLoc - static_cast(ijk[i]); int tmpInBounds = 0; int minExt = extent[i*2]; int maxExt = extent[i*2 + 1]; // check if data is one pixel thick if ( minExt == maxExt ) { if (!bounds) { bounds = this->GetBounds(); } double dist = x[i] - bounds[2*i]; if (dist*dist <= spacing[i]*spacing[i]*tol2) { pcoords[i] = 0.0; ijk[i] = minExt; tmpInBounds = 1; } } // low boundary check else if ( ijk[i] < minExt) { if (!bounds) { bounds = this->GetBounds(); } if ( (spacing[i] >= 0 && x[i] >= bounds[i*2]) || (spacing[i] < 0 && x[i] <= bounds[i*2 + 1]) ) { pcoords[i] = 0.0; ijk[i] = minExt; tmpInBounds = 1; } } // high boundary check else if ( ijk[i] >= maxExt ) { if (!bounds) { bounds = this->GetBounds(); } if ( (spacing[i] >= 0 && x[i] <= bounds[i*2 + 1]) || (spacing[i] < 0 && x[i] >= bounds[i*2]) ) { // make sure index is within the allowed cell index range pcoords[i] = 1.0; ijk[i] = maxExt - 1; tmpInBounds = 1; } } // else index is definitely within bounds else { tmpInBounds = 1; } // clear isInBounds if out of bounds for this dimension isInBounds = (isInBounds & tmpInBounds); } return isInBounds; } //---------------------------------------------------------------------------- void vtkImageData::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); int idx; const int *dims = this->GetDimensions(); const int* extent = this->Extent; os << indent << ""Spacing: ("" << this->Spacing[0] << "", "" << this->Spacing[1] << "", "" << this->Spacing[2] << "")\\n""; os << indent << ""Origin: ("" << this->Origin[0] << "", "" << this->Origin[1] << "", "" << this->Origin[2] << "")\\n""; os << indent << ""Dimensions: ("" << dims[0] << "", "" << dims[1] << "", "" << dims[2] << "")\\n""; os << indent << ""Increments: ("" << this->Increments[0] << "", "" << this->Increments[1] << "", "" << this->Increments[2] << "")\\n""; os << indent << ""Extent: ("" << extent[0]; for (idx = 1; idx < 6; ++idx) { os << "", "" << extent[idx]; } os << "")\\n""; } //---------------------------------------------------------------------------- void vtkImageData::SetNumberOfScalarComponents(int num, vtkInformation* meta_data) { vtkDataObject::SetPointDataActiveScalarInfo(meta_data, -1, num); } //---------------------------------------------------------------------------- bool vtkImageData::HasNumberOfScalarComponents(vtkInformation* meta_data) { vtkInformation *scalarInfo = vtkDataObject::GetActiveFieldInformation( meta_data, FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS); if (!scalarInfo) { return false; } return scalarInfo->Has(FIELD_NUMBER_OF_COMPONENTS()) != 0; } //---------------------------------------------------------------------------- int vtkImageData::GetNumberOfScalarComponents(vtkInformation* meta_data) { vtkInformation *scalarInfo = vtkDataObject::GetActiveFieldInformation( meta_data, FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS); if (scalarInfo && scalarInfo->Has(FIELD_NUMBER_OF_COMPONENTS())) { return scalarInfo->Get( FIELD_NUMBER_OF_COMPONENTS() ); } return 1; } //---------------------------------------------------------------------------- int vtkImageData::GetNumberOfScalarComponents() { vtkDataArray* scalars = this->GetPointData()->GetScalars(); if (scalars) { return scalars->GetNumberOfComponents(); } return 1; } //---------------------------------------------------------------------------- vtkIdType *vtkImageData::GetIncrements() { // Make sure the increments are up to date. The filter bypass and update // mechanism make it tricky to update the increments anywhere other than here this->ComputeIncrements(); return this->Increments; } //---------------------------------------------------------------------------- vtkIdType *vtkImageData::GetIncrements(vtkDataArray *scalars) { // Make sure the increments are up to date. The filter bypass and update // mechanism make it tricky to update the increments anywhere other than here this->ComputeIncrements(scalars); return this->Increments; } //---------------------------------------------------------------------------- void vtkImageData::GetIncrements(vtkIdType &incX, vtkIdType &incY, vtkIdType &incZ) { vtkIdType inc[3]; this->ComputeIncrements(inc); incX = inc[0]; incY = inc[1]; incZ = inc[2]; } //---------------------------------------------------------------------------- void vtkImageData::GetIncrements(vtkDataArray *scalars, vtkIdType &incX, vtkIdType &incY, vtkIdType &incZ) { vtkIdType inc[3]; this->ComputeIncrements(scalars, inc); incX = inc[0]; incY = inc[1]; incZ = inc[2]; } //---------------------------------------------------------------------------- void vtkImageData::GetIncrements(vtkIdType inc[3]) { this->ComputeIncrements(inc); } //---------------------------------------------------------------------------- void vtkImageData::GetIncrements(vtkDataArray* vtkNotUsed(scalars), vtkIdType inc[3]) { this->ComputeIncrements(inc); } //---------------------------------------------------------------------------- void vtkImageData::GetContinuousIncrements(int extent[6], vtkIdType &incX, vtkIdType &incY, vtkIdType &incZ) { this->GetContinuousIncrements(this->GetPointData()->GetScalars(), extent, incX, incY, incZ); } //---------------------------------------------------------------------------- void vtkImageData::GetContinuousIncrements(vtkDataArray *scalars, int extent[6], vtkIdType &incX, vtkIdType &incY, vtkIdType &incZ) { int e0, e1, e2, e3; incX = 0; const int* selfExtent = this->Extent; e0 = extent[0]; if (e0 < selfExtent[0]) { e0 = selfExtent[0]; } e1 = extent[1]; if (e1 > selfExtent[1]) { e1 = selfExtent[1]; } e2 = extent[2]; if (e2 < selfExtent[2]) { e2 = selfExtent[2]; } e3 = extent[3]; if (e3 > selfExtent[3]) { e3 = selfExtent[3]; } // Make sure the increments are up to date vtkIdType inc[3]; this->ComputeIncrements(scalars, inc); incY = inc[1] - (e1 - e0 + 1)*inc[0]; incZ = inc[2] - (e3 - e2 + 1)*inc[1]; } //---------------------------------------------------------------------------- // This method computes the increments from the MemoryOrder and the extent. // This version assumes we are using the Active Scalars void vtkImageData::ComputeIncrements(vtkIdType inc[3]) { this->ComputeIncrements(this->GetPointData()->GetScalars(), inc); } //---------------------------------------------------------------------------- // This method computes the increments from the MemoryOrder and the extent. void vtkImageData::ComputeIncrements(vtkDataArray *scalars, vtkIdType inc[3]) { if (!scalars) { vtkErrorMacro(""No Scalar Field has been specified - assuming 1 component!""); this->ComputeIncrements(1, inc); } else { this->ComputeIncrements(scalars->GetNumberOfComponents(), inc); } } //---------------------------------------------------------------------------- // This method computes the increments from the MemoryOrder and the extent. void vtkImageData::ComputeIncrements(int numberOfComponents, vtkIdType inc[3]) { int idx; vtkIdType incr = numberOfComponents; const int* extent = this->Extent; for (idx = 0; idx < 3; ++idx) { inc[idx] = incr; incr *= (extent[idx*2+1] - extent[idx*2] + 1); } } //---------------------------------------------------------------------------- void vtkImageData::CopyOriginAndSpacingFromPipeline(vtkInformation* info) { // Copy origin and spacing from pipeline information to the internal // copies. if(info->Has(SPACING())) { this->SetSpacing(info->Get(SPACING())); } if(info->Has(ORIGIN())) { this->SetOrigin(info->Get(ORIGIN())); } } //---------------------------------------------------------------------------- template void vtkImageDataConvertScalar(TIn* in, TOut* out) { *out = static_cast(*in); } //---------------------------------------------------------------------------- double vtkImageData::GetScalarComponentAsDouble(int x, int y, int z, int comp) { // Check the component index. if(comp < 0 || comp >= this->GetNumberOfScalarComponents()) { vtkErrorMacro(""Bad component index "" << comp); return 0.0; } // Get a pointer to the scalar tuple. void* ptr = this->GetScalarPointer(x, y, z); if(!ptr) { // An error message was already generated by GetScalarPointer. return 0.0; } double result = 0.0; // Convert the scalar type. int scalarType = this->GetPointData()->GetScalars()->GetDataType(); switch (scalarType) { vtkTemplateMacro(vtkImageDataConvertScalar(static_cast(ptr)+comp, &result)); default: { vtkErrorMacro(""Unknown Scalar type "" << scalarType); } } return result; } //---------------------------------------------------------------------------- void vtkImageData::SetScalarComponentFromDouble(int x, int y, int z, int comp, double value) { // Check the component index. if(comp < 0 || comp >= this->GetNumberOfScalarComponents()) { vtkErrorMacro(""Bad component index "" << comp); return; } // Get a pointer to the scalar tuple. void* ptr = this->GetScalarPointer(x, y, z); if(!ptr) { // An error message was already generated by GetScalarPointer. return; } // Convert the scalar type. int scalarType = this->GetPointData()->GetScalars()->GetDataType(); switch (scalarType) { vtkTemplateMacro(vtkImageDataConvertScalar( &value, static_cast(ptr)+comp)); default: { vtkErrorMacro(""Unknown Scalar type "" << scalarType); } } } //---------------------------------------------------------------------------- float vtkImageData::GetScalarComponentAsFloat(int x, int y, int z, int comp) { return this->GetScalarComponentAsDouble(x, y, z, comp); } //---------------------------------------------------------------------------- void vtkImageData::SetScalarComponentFromFloat(int x, int y, int z, int comp, float value) { this->SetScalarComponentFromDouble(x, y, z, comp, value); } //---------------------------------------------------------------------------- // This Method returns a pointer to a location in the vtkImageData. // Coordinates are in pixel units and are relative to the whole // image origin. void *vtkImageData::GetScalarPointer(int x, int y, int z) { int tmp[3]; tmp[0] = x; tmp[1] = y; tmp[2] = z; return this->GetScalarPointer(tmp); } //---------------------------------------------------------------------------- // This Method returns a pointer to a location in the vtkImageData. // Coordinates are in pixel units and are relative to the whole // image origin. void *vtkImageData::GetScalarPointerForExtent(int extent[6]) { int tmp[3]; tmp[0] = extent[0]; tmp[1] = extent[2]; tmp[2] = extent[4]; return this->GetScalarPointer(tmp); } //---------------------------------------------------------------------------- void *vtkImageData::GetScalarPointer(int coordinate[3]) { vtkDataArray *scalars = this->GetPointData()->GetScalars(); // Make sure the array has been allocated. if (scalars == NULL) { //vtkDebugMacro(""Allocating scalars in ImageData""); //abort(); //this->AllocateScalars(); //scalars = this->PointData->GetScalars(); return NULL; } const int* extent = this->Extent; // error checking: since most access will be from pointer arithmetic. // this should not waste much time. for (int idx = 0; idx < 3; ++idx) { if (coordinate[idx] < extent[idx*2] || coordinate[idx] > extent[idx*2+1]) { vtkErrorMacro(<< ""GetScalarPointer: Pixel ("" << coordinate[0] << "", "" << coordinate[1] << "", "" << coordinate[2] << "") not in memory.\\n Current extent= ("" << extent[0] << "", "" << extent[1] << "", "" << extent[2] << "", "" << extent[3] << "", "" << extent[4] << "", "" << extent[5] << "")""); return NULL; } } return this->GetArrayPointer(scalars, coordinate); } //---------------------------------------------------------------------------- // This method returns a pointer to the origin of the vtkImageData. void *vtkImageData::GetScalarPointer() { if (this->PointData->GetScalars() == NULL) { vtkDebugMacro(""Allocating scalars in ImageData""); abort(); //this->AllocateScalars(); } return this->PointData->GetScalars()->GetVoidPointer(0); } //---------------------------------------------------------------------------- void vtkImageData::SetScalarType(int type, vtkInformation* meta_data) { vtkDataObject::SetPointDataActiveScalarInfo(meta_data, type, -1); } //---------------------------------------------------------------------------- int vtkImageData::GetScalarType() { vtkDataArray* scalars = this->GetPointData()->GetScalars(); if (!scalars) { return VTK_DOUBLE; } return scalars->GetDataType(); } //---------------------------------------------------------------------------- bool vtkImageData::HasScalarType(vtkInformation* meta_data) { vtkInformation *scalarInfo = vtkDataObject::GetActiveFieldInformation( meta_data, FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS); if (!scalarInfo) { return false; } return scalarInfo->Has( FIELD_ARRAY_TYPE() ) != 0; } //---------------------------------------------------------------------------- int vtkImageData::GetScalarType(vtkInformation* meta_data) { vtkInformation *scalarInfo = vtkDataObject::GetActiveFieldInformation( meta_data, FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS); if (scalarInfo) { return scalarInfo->Get( FIELD_ARRAY_TYPE() ); } return VTK_DOUBLE; } //---------------------------------------------------------------------------- void vtkImageData::AllocateScalars(vtkInformation* pipeline_info) { int newType = VTK_DOUBLE; int newNumComp = 1; if(pipeline_info) { vtkInformation *scalarInfo = vtkDataObject::GetActiveFieldInformation( pipeline_info, FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS); if (scalarInfo) { newType = scalarInfo->Get( FIELD_ARRAY_TYPE() ); if ( scalarInfo->Has(FIELD_NUMBER_OF_COMPONENTS()) ) { newNumComp = scalarInfo->Get( FIELD_NUMBER_OF_COMPONENTS() ); } } } this->AllocateScalars(newType, newNumComp); } //---------------------------------------------------------------------------- void vtkImageData::AllocateScalars(int dataType, int numComponents) { vtkDataArray *scalars; // if the scalar type has not been set then we have a problem if (dataType == VTK_VOID) { vtkErrorMacro(""Attempt to allocate scalars before scalar type was set!.""); return; } const int* extent = this->Extent; // Use vtkIdType to avoid overflow on large images vtkIdType dims[3]; dims[0] = extent[1] - extent[0] + 1; dims[1] = extent[3] - extent[2] + 1; dims[2] = extent[5] - extent[4] + 1; vtkIdType imageSize = dims[0]*dims[1]*dims[2]; // if we currently have scalars then just adjust the size scalars = this->PointData->GetScalars(); if (scalars && scalars->GetDataType() == dataType && scalars->GetReferenceCount() == 1) { scalars->SetNumberOfComponents(numComponents); scalars->SetNumberOfTuples(imageSize); // Since the execute method will be modifying the scalars // directly. scalars->Modified(); return; } // allocate the new scalars scalars = vtkDataArray::CreateDataArray(dataType); scalars->SetNumberOfComponents(numComponents); scalars->SetName(""ImageScalars""); // allocate enough memory scalars->SetNumberOfTuples(imageSize); this->PointData->SetScalars(scalars); scalars->Delete(); } //---------------------------------------------------------------------------- int vtkImageData::GetScalarSize(vtkInformation* meta_data) { return vtkDataArray::GetDataTypeSize(this->GetScalarType(meta_data)); } int vtkImageData::GetScalarSize() { vtkDataArray* scalars = this->GetPointData()->GetScalars(); if (!scalars) { return vtkDataArray::GetDataTypeSize(VTK_DOUBLE); } return vtkDataArray::GetDataTypeSize(scalars->GetDataType()); } //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. template void vtkImageDataCastExecute(vtkImageData *inData, IT *inPtr, vtkImageData *outData, OT *outPtr, int outExt[6]) { int idxR, idxY, idxZ; int maxY, maxZ; vtkIdType inIncX, inIncY, inIncZ; vtkIdType outIncX, outIncY, outIncZ; int rowLength; // find the region to loop over rowLength = (outExt[1] - outExt[0]+1)*inData->GetNumberOfScalarComponents(); maxY = outExt[3] - outExt[2]; maxZ = outExt[5] - outExt[4]; // Get increments to march through data inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ); // Loop through ouput pixels for (idxZ = 0; idxZ <= maxZ; idxZ++) { for (idxY = 0; idxY <= maxY; idxY++) { for (idxR = 0; idxR < rowLength; idxR++) { // Pixel operation *outPtr = static_cast(*inPtr); outPtr++; inPtr++; } outPtr += outIncY; inPtr += inIncY; } outPtr += outIncZ; inPtr += inIncZ; } } //---------------------------------------------------------------------------- template void vtkImageDataCastExecute(vtkImageData *inData, T *inPtr, vtkImageData *outData, int outExt[6]) { void *outPtr = outData->GetScalarPointerForExtent(outExt); if (outPtr == NULL) { vtkGenericWarningMacro(""Scalars not allocated.""); return; } int scalarType = outData->GetPointData()->GetScalars()->GetDataType(); switch (scalarType) { vtkTemplateMacro( vtkImageDataCastExecute(inData, static_cast(inPtr), outData, static_cast(outPtr), outExt) ); default: vtkGenericWarningMacro(""Execute: Unknown output ScalarType""); return; } } //---------------------------------------------------------------------------- // This method is passed a input and output region, and executes the filter // algorithm to fill the output from the input. // It just executes a switch statement to call the correct function for // the regions data types. void vtkImageData::CopyAndCastFrom(vtkImageData *inData, int extent[6]) { void *inPtr = inData->GetScalarPointerForExtent(extent); if (inPtr == NULL) { vtkErrorMacro(""Scalars not allocated.""); return; } int scalarType = inData->GetPointData()->GetScalars()->GetDataType(); switch (scalarType) { vtkTemplateMacro(vtkImageDataCastExecute(inData, static_cast(inPtr), this, extent) ); default: vtkErrorMacro(<< ""Execute: Unknown input ScalarType""); return; } } //---------------------------------------------------------------------------- void vtkImageData::Crop(const int* updateExtent) { int nExt[6]; int idxX, idxY, idxZ; int maxX, maxY, maxZ; vtkIdType outId, inId, inIdY, inIdZ, incZ, incY; vtkImageData *newImage; vtkIdType numPts, numCells, tmp; const int* extent = this->Extent; // If extents already match, then we need to do nothing. if (extent[0] == updateExtent[0] && extent[1] == updateExtent[1] && extent[2] == updateExtent[2] && extent[3] == updateExtent[3] && extent[4] == updateExtent[4] && extent[5] == updateExtent[5]) { return; } // Take the intersection of the two extent so that // we are not asking for more than the extent. memcpy(nExt, updateExtent, 6*sizeof(int)); if (nExt[0] < extent[0]) { nExt[0] = extent[0];} if (nExt[1] > extent[1]) { nExt[1] = extent[1];} if (nExt[2] < extent[2]) { nExt[2] = extent[2];} if (nExt[3] > extent[3]) { nExt[3] = extent[3];} if (nExt[4] < extent[4]) { nExt[4] = extent[4];} if (nExt[5] > extent[5]) { nExt[5] = extent[5];} // If the extents are the same just return. if (extent[0] == nExt[0] && extent[1] == nExt[1] && extent[2] == nExt[2] && extent[3] == nExt[3] && extent[4] == nExt[4] && extent[5] == nExt[5]) { vtkDebugMacro(""Extents already match.""); return; } // How many point/cells. numPts = (nExt[1]-nExt[0]+1)*(nExt[3]-nExt[2]+1)*(nExt[5]-nExt[4]+1); // Conditional are to handle 3d, 2d, and even 1d images. tmp = nExt[1] - nExt[0]; if (tmp <= 0) { tmp = 1; } numCells = tmp; tmp = nExt[3] - nExt[2]; if (tmp <= 0) { tmp = 1; } numCells *= tmp; tmp = nExt[5] - nExt[4]; if (tmp <= 0) { tmp = 1; } numCells *= tmp; // Create a new temporary image. newImage = vtkImageData::New(); newImage->SetExtent(nExt); vtkPointData *npd = newImage->GetPointData(); vtkCellData *ncd = newImage->GetCellData(); npd->CopyAllocate(this->PointData, numPts); ncd->CopyAllocate(this->CellData, numCells); // Loop through outData points incY = extent[1]-extent[0]+1; incZ = (extent[3]-extent[2]+1)*incY; outId = 0; inIdZ = incZ * (nExt[4]-extent[4]) + incY * (nExt[2]-extent[2]) + (nExt[0]-extent[0]); for (idxZ = nExt[4]; idxZ <= nExt[5]; idxZ++) { inIdY = inIdZ; for (idxY = nExt[2]; idxY <= nExt[3]; idxY++) { inId = inIdY; for (idxX = nExt[0]; idxX <= nExt[1]; idxX++) { npd->CopyData( this->PointData, inId, outId); ++inId; ++outId; } inIdY += incY; } inIdZ += incZ; } // Loop through outData cells // Have to handle the 2d and 1d cases. maxX = nExt[1]; maxY = nExt[3]; maxZ = nExt[5]; if (maxX == nExt[0]) { ++maxX; } if (maxY == nExt[2]) { ++maxY; } if (maxZ == nExt[4]) { ++maxZ; } incY = extent[1]-extent[0]; incZ = (extent[3]-extent[2])*incY; outId = 0; inIdZ = incZ * (nExt[4]-extent[4]) + incY * (nExt[2]-extent[2]) + (nExt[0]-extent[0]); for (idxZ = nExt[4]; idxZ < maxZ; idxZ++) { inIdY = inIdZ; for (idxY = nExt[2]; idxY < maxY; idxY++) { inId = inIdY; for (idxX = nExt[0]; idxX < maxX; idxX++) { ncd->CopyData(this->CellData, inId, outId); ++inId; ++outId; } inIdY += incY; } inIdZ += incZ; } this->PointData->ShallowCopy(npd); this->CellData->ShallowCopy(ncd); this->SetExtent(nExt); newImage->Delete(); } //---------------------------------------------------------------------------- double vtkImageData::GetScalarTypeMin(vtkInformation* meta_data) { return vtkDataArray::GetDataTypeMin(this->GetScalarType(meta_data)); } //---------------------------------------------------------------------------- double vtkImageData::GetScalarTypeMin() { return vtkDataArray::GetDataTypeMin(this->GetScalarType()); } //---------------------------------------------------------------------------- double vtkImageData::GetScalarTypeMax(vtkInformation* meta_data) { return vtkDataArray::GetDataTypeMax(this->GetScalarType(meta_data)); } //---------------------------------------------------------------------------- double vtkImageData::GetScalarTypeMax() { return vtkDataArray::GetDataTypeMax(this->GetScalarType()); } //---------------------------------------------------------------------------- void vtkImageData::SetExtent(int x1, int x2, int y1, int y2, int z1, int z2) { int ext[6]; ext[0] = x1; ext[1] = x2; ext[2] = y1; ext[3] = y2; ext[4] = z1; ext[5] = z2; this->SetExtent(ext); } //---------------------------------------------------------------------------- void vtkImageData::SetDataDescription(int desc) { if (desc == this->DataDescription) { return; } this->DataDescription = desc; if (this->Vertex) { this->Vertex->Delete(); this->Vertex = 0; } if (this->Line) { this->Line->Delete(); this->Line = 0; } if (this->Pixel) { this->Pixel->Delete(); this->Pixel = 0; } if (this->Voxel) { this->Voxel->Delete(); this->Voxel = 0; } switch (this->DataDescription) { case VTK_SINGLE_POINT: this->Vertex = vtkVertex::New(); break; case VTK_X_LINE: case VTK_Y_LINE: case VTK_Z_LINE: this->Line = vtkLine::New(); break; case VTK_XY_PLANE: case VTK_YZ_PLANE: case VTK_XZ_PLANE: this->Pixel = vtkPixel::New(); break; case VTK_XYZ_GRID: this->Voxel = vtkVoxel::New();; break; } } //---------------------------------------------------------------------------- void vtkImageData::SetExtent(int *extent) { int description; description = vtkStructuredData::SetExtent(extent, this->Extent); if ( description < 0 ) //improperly specified { vtkErrorMacro (<< ""Bad Extent, retaining previous values""); } if (description == VTK_UNCHANGED) { return; } this->SetDataDescription(description); this->Modified(); } //---------------------------------------------------------------------------- int *vtkImageData::GetDimensions() { const int* extent = this->Extent; this->Dimensions[0] = extent[1] - extent[0] + 1; this->Dimensions[1] = extent[3] - extent[2] + 1; this->Dimensions[2] = extent[5] - extent[4] + 1; return this->Dimensions; } //---------------------------------------------------------------------------- void vtkImageData::GetDimensions(int *dOut) { int *dims = this->GetDimensions(); dOut[0] = dims[0]; dOut[1] = dims[1]; dOut[2] = dims[2]; } //---------------------------------------------------------------------------- void vtkImageData::SetAxisUpdateExtent(int idx, int min, int max, const int* updateExtent, int* axisUpdateExtent) { if (idx > 2) { vtkWarningMacro(""illegal axis!""); return; } memcpy(axisUpdateExtent, updateExtent, 6*sizeof(int)); if (axisUpdateExtent[idx*2] != min) { axisUpdateExtent[idx*2] = min; } if (axisUpdateExtent[idx*2+1] != max) { axisUpdateExtent[idx*2+1] = max; } } //---------------------------------------------------------------------------- void vtkImageData::GetAxisUpdateExtent(int idx, int &min, int &max, const int* updateExtent) { if (idx > 2) { vtkWarningMacro(""illegal axis!""); return; } min = updateExtent[idx*2]; max = updateExtent[idx*2+1]; } //---------------------------------------------------------------------------- unsigned long vtkImageData::GetActualMemorySize() { return this->vtkDataSet::GetActualMemorySize(); } //---------------------------------------------------------------------------- void vtkImageData::ShallowCopy(vtkDataObject *dataObject) { vtkImageData *imageData = vtkImageData::SafeDownCast(dataObject); if ( imageData != NULL ) { this->InternalImageDataCopy(imageData); } // Do superclass this->vtkDataSet::ShallowCopy(dataObject); } //---------------------------------------------------------------------------- void vtkImageData::DeepCopy(vtkDataObject *dataObject) { vtkImageData *imageData = vtkImageData::SafeDownCast(dataObject); if ( imageData != NULL ) { this->InternalImageDataCopy(imageData); } // Do superclass this->vtkDataSet::DeepCopy(dataObject); } //---------------------------------------------------------------------------- // This copies all the local variables (but not objects). void vtkImageData::InternalImageDataCopy(vtkImageData *src) { int idx; //this->SetScalarType(src->GetScalarType()); //this->SetNumberOfScalarComponents(src->GetNumberOfScalarComponents()); for (idx = 0; idx < 3; ++idx) { this->Dimensions[idx] = src->Dimensions[idx]; this->Increments[idx] = src->Increments[idx]; this->Origin[idx] = src->Origin[idx]; this->Spacing[idx] = src->Spacing[idx]; } this->SetExtent(src->GetExtent()); } //---------------------------------------------------------------------------- vtkIdType vtkImageData::GetNumberOfCells() { vtkIdType nCells=1; int i; const int* extent = this->Extent; vtkIdType dims[3]; dims[0] = extent[1] - extent[0] + 1; dims[1] = extent[3] - extent[2] + 1; dims[2] = extent[5] - extent[4] + 1; for (i=0; i<3; i++) { if (dims[i] == 0) { return 0; } if (dims[i] > 1) { nCells *= (dims[i]-1); } } return nCells; } //============================================================================ // Starting to make some more general methods that deal with any array // (not just scalars). //============================================================================ //---------------------------------------------------------------------------- // This Method returns a pointer to a location in the vtkImageData. // Coordinates are in pixel units and are relative to the whole // image origin. void vtkImageData::GetArrayIncrements(vtkDataArray* array, vtkIdType increments[3]) { const int* extent = this->Extent; // We could store tuple increments and just // multiply by the number of components... increments[0] = array->GetNumberOfComponents(); increments[1] = increments[0] * (extent[1]-extent[0]+1); increments[2] = increments[1] * (extent[3]-extent[2]+1); } //---------------------------------------------------------------------------- void *vtkImageData::GetArrayPointerForExtent(vtkDataArray* array, int extent[6]) { int tmp[3]; tmp[0] = extent[0]; tmp[1] = extent[2]; tmp[2] = extent[4]; return this->GetArrayPointer(array, tmp); } //---------------------------------------------------------------------------- // This Method returns a pointer to a location in the vtkImageData. // Coordinates are in pixel units and are relative to the whole // image origin. void *vtkImageData::GetArrayPointer(vtkDataArray* array, int coordinate[3]) { vtkIdType incs[3]; vtkIdType idx; if (array == NULL) { return NULL; } const int* extent = this->Extent; // error checking: since most acceses will be from pointer arithmetic. // this should not waste much time. for (idx = 0; idx < 3; ++idx) { if (coordinate[idx] < extent[idx*2] || coordinate[idx] > extent[idx*2+1]) { vtkErrorMacro(<< ""GetPointer: Pixel ("" << coordinate[0] << "", "" << coordinate[1] << "", "" << coordinate[2] << "") not in current extent: ("" << extent[0] << "", "" << extent[1] << "", "" << extent[2] << "", "" << extent[3] << "", "" << extent[4] << "", "" << extent[5] << "")""); return NULL; } } // compute the index of the vector. this->GetArrayIncrements(array, incs); idx = ((coordinate[0] - extent[0]) * incs[0] + (coordinate[1] - extent[2]) * incs[1] + (coordinate[2] - extent[4]) * incs[2]); // I could check to see if the array has the correct number // of tuples for the extent, but that would be an extra multiply. if (idx < 0 || idx > array->GetMaxId()) { vtkErrorMacro(""Coordinate ("" << coordinate[0] << "", "" << coordinate[1] << "", "" << coordinate[2] << "") out side of array (max = "" << array->GetMaxId()); return NULL; } return array->GetVoidPointer(idx); } //---------------------------------------------------------------------------- void vtkImageData::ComputeInternalExtent(int *intExt, int *tgtExt, int *bnds) { int i; const int* extent = this->Extent; for (i = 0; i < 3; ++i) { intExt[i*2] = tgtExt[i*2]; if (intExt[i*2] - bnds[i*2] < extent[i*2]) { intExt[i*2] = extent[i*2] + bnds[i*2]; } intExt[i*2+1] = tgtExt[i*2+1]; if (intExt[i*2+1] + bnds[i*2+1] > extent[i*2+1]) { intExt[i*2+1] = extent[i*2+1] - bnds[i*2+1]; } } } //---------------------------------------------------------------------------- vtkImageData* vtkImageData::GetData(vtkInformation* info) { return info? vtkImageData::SafeDownCast(info->Get(DATA_OBJECT())) : 0; } //---------------------------------------------------------------------------- vtkImageData* vtkImageData::GetData(vtkInformationVector* v, int i) { return vtkImageData::GetData(v->GetInformationObject(i)); } ",16332,True,2987.1148255268126,median "#include ""llvm/Pass.h"" #include ""llvm/ADT/DenseMap.h"" #include ""llvm/ADT/iterator_range.h"" #include ""llvm/ADT/Optional.h"" #include ""llvm/IR/Module.h"" #include ""llvm/IR/Function.h"" #include ""llvm/IR/CFG.h"" #include ""llvm/IR/InstVisitor.h"" #include ""llvm/IR/IntrinsicInst.h"" #include ""llvm/IR/InstIterator.h"" #include ""llvm/IR/IRBuilder.h"" #include ""llvm/IR/DataLayout.h"" #include ""llvm/Transforms/Utils/UnifyFunctionExitNodes.h"" #include ""llvm/Analysis/TargetLibraryInfo.h"" #include ""llvm/Analysis/CFG.h"" #include ""llvm/Analysis/CallGraph.h"" #include ""llvm/Support/ErrorHandling.h"" #include ""llvm/Support/CommandLine.h"" #include ""llvm/Support/raw_ostream.h"" #include ""llvm/Support/Debug.h"" #include ""clam/config.h"" #include ""clam/AbstractDomain.hh"" #include ""clam/Clam.hh"" #include ""clam/CfgBuilder.hh"" #include ""clam/Support/Debug.hh"" #include ""clam/Support/NameValues.hh"" /** Wrappers for pointer analyses **/ #include ""clam/DummyHeapAbstraction.hh"" #include ""clam/LlvmDsaHeapAbstraction.hh"" #include ""clam/SeaDsaHeapAbstraction.hh"" #ifdef HAVE_DSA #include ""dsa/Steensgaard.hh"" #endif #include ""sea_dsa/AllocWrapInfo.hh"" #include ""sea_dsa/ShadowMem.hh"" #include ""crab/common/debug.hpp"" #include ""crab/common/stats.hpp"" #include ""crab/analysis/fwd_analyzer.hpp"" #include ""crab/analysis/bwd_analyzer.hpp"" #ifdef TOP_DOWN_INTER_ANALYSIS #include ""crab/analysis/inter/top_down_inter_analyzer.hpp"" #else #include ""crab/analysis/inter/bottom_up_inter_analyzer.hpp"" #endif #include ""crab/analysis/dataflow/liveness.hpp"" #include ""crab/analysis/dataflow/assumptions.hpp"" #include ""crab/checkers/assertion.hpp"" //#include ""crab/checkers/null.hpp"" #include ""crab/checkers/checker.hpp"" #include ""crab/cg/cg.hpp"" #include ""crab/cg/cg_bgl.hpp"" #include ""./crab/path_analyzer.hpp"" #include #include #include #include #include using namespace llvm; using namespace clam; using namespace crab::cfg; using namespace crab::cg; using namespace crab::analyzer; using namespace crab::checker; #include ""ClamOptions.def"" // In C++11 we need to pass to std::bind ""this"" (if class member // functions are called) as well as all placeholders for each // argument. This is wrapper to avoid that and improve readability. template static std::function bind_this(C* c, Ret(C::*m)(Ts...)) { return [=](Ts&&... args) { return (c->*m)(std::forward(args)...); }; } namespace clam { /** Begin typedefs **/ typedef crab::analyzer::liveness liveness_t; typedef crab::cg::call_graph call_graph_t; typedef crab::cg::call_graph_ref call_graph_ref_t; typedef std::unordered_map liveness_map_t; typedef typename IntraClam::wrapper_dom_ptr wrapper_dom_ptr; typedef typename IntraClam::checks_db_t checks_db_t; typedef typename IntraClam::abs_dom_map_t abs_dom_map_t; typedef typename IntraClam::lin_csts_map_t lin_csts_map_t; //typedef typename IntraClam::assumption_map_t assumption_map_t; /** End typedefs **/ #if 0 /** Begin global counters **/ static unsigned num_invars; // some measure for the size of invariants static unsigned num_nontrivial_blocks; /** End global counters **/ #endif static bool isRelationalDomain(CrabDomain dom) { return (dom == ZONES_SPLIT_DBM || dom == OCT || dom == PK || dom == TERMS_ZONES); } static bool isTrackable(const Function &fun) { return !fun.isDeclaration() && !fun.empty() && !fun.isVarArg(); } /** convenient wrapper for the analysis datastructures **/ struct AnalysisResults { // invariants that hold at the entry of a block abs_dom_map_t &premap; // invariants that hold at the exit of a block abs_dom_map_t &postmap; // infeasible edges edges_set &infeasible_edges; // database with all the checks checks_db_t &checksdb; AnalysisResults(abs_dom_map_t &pre, abs_dom_map_t &post, edges_set& false_edges, checks_db_t &db) : premap(pre) , postmap(post) , infeasible_edges(false_edges) , checksdb(db) {} }; /** return invariant for block in table but filtering out shadow_varnames **/ static wrapper_dom_ptr lookup(const abs_dom_map_t &table, const llvm::BasicBlock &block, const std::vector &shadow_varnames) { auto it = table.find(&block); if (it == table.end()) { return nullptr; } if (shadow_varnames.empty()) { return it->second; } else { std::vector shadow_vars; shadow_vars.reserve(shadow_varnames.size()); for(unsigned i=0; isecond->clone(); invs->forget(shadow_vars); return invs; } } /** update table with pre or post invariants **/ static bool update(abs_dom_map_t &table, const llvm::BasicBlock &block, wrapper_dom_ptr absval) { bool already = false; auto it = table.find(&block); if (it == table.end()) { table.insert(std::make_pair(&block, absval)); } else { it->second = absval; already = true; } return already; } /** Pretty-printer utilities **/ namespace pretty_printer_impl { /** Generic class for a block annotation **/ class block_annotation { public: typedef typename cfg_ref_t::statement_t statement_t; block_annotation() {} virtual ~block_annotation() {} virtual std::string name() const = 0; virtual void print_begin(basic_block_label_t bbl, crab::crab_os &o) const {} virtual void print_end(basic_block_label_t bbl, crab::crab_os &o) const {} virtual void print_begin(const statement_t &s, crab::crab_os &o) const {} virtual void print_end(const statement_t &s, crab::crab_os &o) const {} }; /** Annotation for invariants **/ class invariant_annotation: public block_annotation { private: const abs_dom_map_t &m_premap; const abs_dom_map_t &m_postmap; std::vector m_shadow_vars; public: invariant_annotation(const llvm_variable_factory &vfac, const abs_dom_map_t &premap, const abs_dom_map_t &postmap, const bool keep_shadows) : block_annotation(), m_premap(premap), m_postmap(postmap) { if (keep_shadows) { m_shadow_vars.reserve(std::distance(vfac.get_shadow_vars().begin(), vfac.get_shadow_vars().end())); m_shadow_vars.insert(m_shadow_vars.begin(), vfac.get_shadow_vars().begin(), vfac.get_shadow_vars().end()); } } std::string name() const { return ""INVARIANTS"";} void print_begin(basic_block_label_t bbl, crab::crab_os &o) const { if (const llvm::BasicBlock *bb = bbl.get_basic_block()) { wrapper_dom_ptr pre = lookup(m_premap, *bb, m_shadow_vars); o << "" "" << name() << "": ""; if (pre){ o << pre << ""\\n""; } else { o << ""null\\n""; } } } void print_end(basic_block_label_t bbl, crab::crab_os &o) const { if (const llvm::BasicBlock *bb = bbl.get_basic_block()) { wrapper_dom_ptr post = lookup(m_postmap, *bb, m_shadow_vars); o << "" "" << name() << "": ""; if (post) { o << post << ""\\n""; } else { o << ""null\\n""; } } } }; /** Annotation for unjustified assumptions done by the analysis **/ class unjust_assumption_annotation: public block_annotation { private: typedef typename assumption_analysis::assumption_ptr assumption_ptr; public: typedef assumption_analysis unjust_assumption_analysis_t; private: typedef typename cfg_ref_t::statement_t statement_t; cfg_ref_t m_cfg; unjust_assumption_analysis_t *m_analyzer; public: unjust_assumption_annotation(cfg_ref_t cfg, unjust_assumption_analysis_t *analyzer) : block_annotation(), m_cfg(cfg), m_analyzer(analyzer) { } std::string name() const { return ""UNJUSTIFIED ASSUMPTIONS"";} void print_begin(const statement_t &s, crab::crab_os &o) const { std::vector assumes; if (s.is_assert()) { typedef typename cfg_ref_t::basic_block_t::assert_t assert_t; m_analyzer->get_assumptions(static_cast(&s), assumes); if (!assumes.empty()) { o << "" /** assert verified as ""; for (std::vector::iterator it = assumes.begin(), et = assumes.end(); it!=et;) { o << (*it)->get_id_str(); ++it; if (it != et) o << "",""; else o << "";""; } o << ""**/\\n""; } } else { m_analyzer->get_originated_assumptions(&s, assumes); for (auto assume_ptr: assumes) { o << "" /** ""; assume_ptr->write(o); o << ""**/\\n""; } } } }; /** Print a block together with its annotations **/ class print_block { cfg_ref_t m_cfg; crab::crab_os &m_o; const std::vector> &m_annotations; public: print_block(cfg_ref_t cfg, crab::crab_os &o, const std::vector> &annotations) : m_cfg(cfg), m_o(o), m_annotations(annotations) {} void operator()(basic_block_label_t bbl) const { // do not print block if no annotations if (m_annotations.empty()) return; m_o << bbl.get_name() << "":\\n""; crab::crab_string_os o; for (auto& p: m_annotations) { p->print_begin(bbl,o); } if (o.str() != """") { m_o << ""/**\\n"" << o.str() << ""**/\\n""; } const basic_block_t &bb = m_cfg.get_node(bbl); bool empty_block = (std::distance(bb.begin(), bb.end()) == 0); for (auto const &s: bb) { for (auto& p: m_annotations) { p->print_begin(s, m_o); } m_o << "" "" << s << "";\\n""; for (auto& p: m_annotations) { p->print_end(s, m_o); } } if (!empty_block) { crab::crab_string_os o; for (auto& p: m_annotations) { p->print_end(bbl, o); } if (o.str() != """") { m_o << ""/**\\n"" << o.str() << ""**/\\n""; } } std::pair p = bb.next_blocks(); cfg_ref_t::const_succ_iterator it = p.first; cfg_ref_t::const_succ_iterator et = p.second; if (it != et) { m_o << "" "" << ""goto ""; for (; it != et; ) { m_o << crab::cfg_impl::get_label_str(*it); ++it; if (it == et) { m_o << "";""; } else { m_o << "",""; } } } m_o << ""\\n""; } }; typedef std::unordered_set visited_t; template void dfs_rec(cfg_ref_t cfg, basic_block_label_t curId, visited_t &visited, T f) { if (visited.find(curId) != visited.end()) return; visited.insert(curId); const basic_block_t &cur = cfg.get_node(curId); f(curId); for (auto const n : llvm::make_range(cur.next_blocks())) { dfs_rec(cfg, n, visited, f); } } template void dfs(cfg_ref_t cfg, T f) { visited_t visited; dfs_rec(cfg, cfg.entry(), visited, f); } void print_annotations(cfg_ref_t cfg, const std::vector> &annotations) { print_block f(cfg, crab::outs(), annotations); dfs(cfg, f); } } //end namespace static std::string dom_to_str(CrabDomain dom) { switch (dom) { case INTERVALS: return interval_domain_t::getDomainName(); case INTERVALS_CONGRUENCES: return ric_domain_t::getDomainName(); case BOXES: return boxes_domain_t::getDomainName(); case DIS_INTERVALS: return dis_interval_domain_t::getDomainName(); case ZONES_SPLIT_DBM: return split_dbm_domain_t::getDomainName(); case TERMS_DIS_INTERVALS: return term_dis_int_domain_t::getDomainName(); case TERMS_ZONES: return num_domain_t::getDomainName(); case OCT: return oct_domain_t::getDomainName(); case PK: return pk_domain_t::getDomainName(); case WRAPPED_INTERVALS: return wrapped_interval_domain_t::getDomainName(); default: return ""none""; } } std::string AnalysisParams::abs_dom_to_str() const { return dom_to_str(dom); } #ifndef TOP_DOWN_INTER_ANALYSIS std::string AnalysisParams::sum_abs_dom_to_str() const { return dom_to_str(sum_dom); } #endif /** * Internal implementation of the intra-procedural analysis **/ class IntraClam_Impl { public: IntraClam_Impl(const Function &fun, CrabBuilderManager &man) : m_cfg_builder(nullptr), m_fun(fun), m_vfac(man.get_var_factory()) { if (isTrackable(m_fun)) { if (!man.has_cfg(m_fun)) { CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Started Crab CFG construction for "" << fun.getName() << ""\\n""); m_cfg_builder = man.mk_cfg_builder(m_fun); CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Finished Crab CFG construction for "" << fun.getName() << ""\\n""); } else { m_cfg_builder = man.get_cfg_builder(m_fun); } } else { CRAB_VERBOSE_IF(1, llvm::outs() << ""Cannot build CFG for "" << fun.getName() << ""\\n""); } } void Analyze(AnalysisParams ¶ms, const llvm::BasicBlock *entry, // assumptions can be provided in abs_dom format or // as linear constraints. const abs_dom_map_t &abs_dom_assumptions, const lin_csts_map_t &lin_csts_assumptions, AnalysisResults &results) { if (!m_cfg_builder) { CRAB_VERBOSE_IF(1, llvm::outs() << ""Skipped analysis for "" << m_fun.getName() << ""\\n""); return; } const liveness_t* live = nullptr; if (params.run_liveness || isRelationalDomain(params.dom)) { // -- run liveness m_cfg_builder->compute_live_symbols(); if (isRelationalDomain(params.dom)) { live = m_cfg_builder->get_live_symbols(); assert(live); unsigned total_live, avg_live_per_blk, max_live_per_blk; live->get_stats(total_live, max_live_per_blk, avg_live_per_blk); CRAB_VERBOSE_IF(1, crab::outs() << ""Max live per block: "" << max_live_per_blk << ""\\n"" << ""Threshold: "" << params.relational_threshold << ""\\n""); #ifdef HAVE_ALL_DOMAINS if (max_live_per_blk > params.relational_threshold) { // default domain params.dom = INTERVALS; } #endif } } if (CrabBuildOnlyCFG) { return; } if (intra_analyses.count(params.dom)) { intra_analyses.at(params.dom).analyze(params, entry, abs_dom_assumptions, lin_csts_assumptions, (params.run_liveness)? live : nullptr, results); } else { crab::outs() << ""Warning: abstract domain not found or enabled.\\n"" << ""Compile with -DALL_DOMAINS=ON.\\n""; // crab::outs() << ""Running "" << intra_analyses.at(INTERVALS).name << "" ...\\n""; // intra_analyses.at(INTERVALS).analyze(params, entry, assumptions, // (params.run_liveness)? live : nullptr, // results); } } template void runClamPrintFunction(AbsDomain inv, basic_block_t& bb, const LLVMContext &ctx){ typedef crab::analyzer::intra_abs_transformer abs_tr_t; abs_tr_t vis(inv); bb.dump(); //This is the crab basic block for(auto &s: bb){ AbsDomain next_inv = std::move(vis.get_abs_value()); //next_inv is the invariant that holds just before executing s if(s.is_clam_print()){ // std::stringstream ss; // ss << s.out_stream_buff().rdbuf(); // llvm::outs << ""Call statement :: "" << ss.str() << std::endl; llvm::outs() << ""Invariants as linear constraints\\n""; auto csts = next_inv.to_linear_constraint_system(); //Now we print out the linear constraints here csts.dump(); llvm::outs() << ""\\n""; } else{ s.accept(&vis); //propagate invariant one step forward } } } template void runClamVarTags(AbsDomain inv, basic_block_t& bb, const LLVMContext &ctx){ typedef crab::analyzer::intra_abs_transformer abs_tr_t; abs_tr_t vis(inv); bb.dump(); //This is the crab basic block where the print_var_tags for(auto &s: bb){ AbsDomain next_inv = std::move(vis.get_abs_value()); //next_inv is the invariant that holds just before executing s if(s.is_clam_var_tags()){ llvm::outs() << ""Invariants projected to certain variables\\n""; auto &s1 = dynamic_cast&>(s); next_inv.project(s1.get_args()); //Now we print out the projected constraints here auto csts = next_inv.to_linear_constraint_system(); csts.dump(); llvm::outs() << ""\\n""; } else{ s.accept(&vis); //propagate invariant one step forward } } } bool pathAnalyze(const AnalysisParams& params, const std::vector& blocks, bool layered_solving, std::vector& core, bool populate_inv_map, abs_dom_map_t& post) const { assert(m_cfg_builder); // build the full path (included internal basic blocks added // during the translation to Crab) std::vector path; path.reserve(blocks.size()); for(unsigned i=0; i < blocks.size(); ++i) { path.push_back(m_cfg_builder->get_crab_basic_block(blocks[i])); if (i < blocks.size() - 1) { if (const basic_block_label_t* edge_bb = m_cfg_builder->get_crab_basic_block(blocks[i], blocks[i+1])) { path.push_back(*edge_bb); } } } bool res; if (path_analyses.count(params.dom)) { path_analyses.at(params.dom).analyze(path, core, layered_solving , populate_inv_map, post, res); } else { crab::outs() << ""Warning: abstract domain not found or enabled.\\n"" << ""Compile with -DALL_DOMAINS=ON.\\n""; // crab::outs() << ""Running "" << path_analyses.at(INTERVALS).name << "" ...\\n""; // path_analyses.at(INTERVALS).analyze(path, core, layered_solving, populate_inv_map, // post, res); } return res; } private: CrabBuilderManager::CfgBuilderPtr m_cfg_builder; const Function &m_fun; llvm_variable_factory &m_vfac; // helper to get a reference to a crab cfg from the builder cfg_t& get_cfg() { return m_cfg_builder->get_cfg(); } template void analyzeCfg(const AnalysisParams ¶ms, const BasicBlock *entry, const abs_dom_map_t &abs_dom_assumptions, const lin_csts_map_t &lin_csts_assumptions, const liveness_t *live, AnalysisResults &results) { // -- we use the combined forward/backward analyzer typedef intra_forward_backward_analyzer intra_analyzer_t; // -- checkers for assertions and nullity typedef intra_checker intra_checker_t; typedef assert_property_checker assert_prop_t; //typedef null_property_checker null_prop_t; CRAB_VERBOSE_IF(1, auto fdecl = get_cfg().get_func_decl(); crab::get_msg_stream() << ""Running intra-procedural analysis with "" << ""\\"""" << Dom::getDomainName() << ""\\"""" << "" for "" << fdecl.get_func_name() << "" ... \\n"";); // -- run intra-procedural analysis intra_analyzer_t analyzer(get_cfg()); typename intra_analyzer_t::assumption_map_t crab_assumptions; // Reconstruct a crab assumption map from an abs_dom_map_t for (auto &kv: abs_dom_assumptions) { Dom absval; getAbsDomWrappee(kv.second, absval); crab_assumptions.insert({m_cfg_builder->get_crab_basic_block(kv.first), absval}); } // Reconstruct a crab assumption map from a lin_csts_map_t for (auto &kv: lin_csts_assumptions) { Dom absval; absval += kv.second; crab_assumptions.insert({m_cfg_builder->get_crab_basic_block(kv.first), absval}); } // We use as initial state an assumption if exists Dom entry_dom = Dom::top(); auto it = crab_assumptions.find(m_cfg_builder->get_crab_basic_block(entry)); if (it != crab_assumptions.end()) { entry_dom = it->second; } analyzer.run(m_cfg_builder->get_crab_basic_block(entry), entry_dom, !params.run_backward, crab_assumptions, live, params.widening_delay, params.narrowing_iters, params.widening_jumpset); CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Finished intra-procedural analysis.\\n""); // -- store invariants if (params.store_invariants || params.print_invars) { CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Storing invariants.\\n""); for (basic_block_label_t bl: llvm::make_range(get_cfg().label_begin(), get_cfg().label_end())) { if (bl.is_edge()) { // Note that we use get_post instead of get_pre: // the crab block (bl) has an assume statement corresponding // to the branch condition in the predecessor of the // LLVM edge. We want the invariant *after* the // evaluation of the assume. if (analyzer.get_post(bl).is_bottom()) { results.infeasible_edges.insert({bl.get_edge().first, bl.get_edge().second}); } } else if (const BasicBlock *B = bl.get_basic_block()) { // --- invariants that hold at the entry of the blocks auto pre = analyzer.get_pre(bl); update(results.premap, *B, mkGenericAbsDomWrapper(pre)); // --- invariants that hold at the exit of the blocks auto post = analyzer.get_post(bl); update(results.postmap, *B, mkGenericAbsDomWrapper(post)); #if 0 if (params.stats) { unsigned num_block_invars = 0; // XXX: for boxes it would be more useful to get a measure // from to_disjunctive_linear_constraint_system() but it // can be really slow. num_block_invars += pre.to_linear_constraint_system().size(); num_invars += num_block_invars; if (num_block_invars > 0) num_nontrivial_blocks++; } #endif } else { // this should be unreachable assert(false && ""A Crab block should correspond to either an LLVM edge or block""); } } CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""All invariants stored.\\n""); } // -- print all cfg annotations (if any) if (params.print_invars || params.print_unjustified_assumptions) { typedef pretty_printer_impl::block_annotation block_annotation_t; typedef pretty_printer_impl::invariant_annotation inv_annotation_t; typedef pretty_printer_impl::unjust_assumption_annotation unjust_assume_annotation_t; std::vector> pool_annotations; if (get_cfg().has_func_decl()) { auto fdecl = get_cfg().get_func_decl(); crab::outs() << ""\\n"" << fdecl << ""\\n""; } else { llvm::outs() << ""\\n"" << ""function "" << m_fun.getName() << ""\\n""; } if (params.print_invars) { pool_annotations.emplace_back( make_unique(m_vfac, results.premap, results.postmap, params.keep_shadow_vars)); } // XXX: it must be alive when print_annotations is called. #if 0 assumption_naive_analysis unjust_assumption_analyzer(get_cfg()); #else assumption_dataflow_analysis unjust_assumption_analyzer(get_cfg()); #endif if (params.print_unjustified_assumptions) { // -- run first the analysis unjust_assumption_analyzer.exec(); pool_annotations.emplace_back( make_unique(get_cfg(), &unjust_assumption_analyzer)); } pretty_printer_impl::print_annotations(get_cfg(), pool_annotations); } if (params.check) { // --- checking assertions and collecting data CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Checking assertions ... \\n""); typename intra_checker_t::prop_checker_ptr prop(new assert_prop_t(params.check_verbose)); // if (params.check == NULLITY) // prop.reset(new null_prop_t(params.check_verbose)); intra_checker_t checker(analyzer, {prop}); checker.run(); CRAB_VERBOSE_IF(1, llvm::outs() << ""Function "" << m_fun.getName() << ""\\n""; checker.show(crab::outs())); results.checksdb += checker.get_all_checks(); CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Finished assert checking.\\n""); } llvm::outs() << ""\\n********* STARTING CUSTOM ANALYSIS **********\\n""; //After everything is done, we will do out printing business const Function *F = entry->getParent(); for(const_inst_iterator It = inst_begin(F), E = inst_end(F); It != E; ++It){ if(It->getOpcode() == 54){ //This is a call instruction if(cast(*It).getCalledFunction()->getName() == ""__CLAM_print_lin_cst""){ //This is our required instruction check const llvm::BasicBlock *llvm_bb = It->getParent(); basic_block_label_t bb_label = m_cfg_builder->get_crab_basic_block(llvm_bb); auto pre = analyzer.get_pre(bb_label); //pre condition for the entry of basic block basic_block_t &bb = get_cfg().get_node(bb_label); Dom inv; runClamPrintFunction(pre, bb, llvm_bb->getContext()); } else if(cast(*It).getCalledFunction()->getName() == ""__CLAM_print_var_tags""){ const llvm::BasicBlock *llvm_bb = It->getParent(); basic_block_label_t bb_label = m_cfg_builder->get_crab_basic_block(llvm_bb); auto pre = analyzer.get_pre(bb_label); //pre condition for the entry of basic block basic_block_t &bb = get_cfg().get_node(bb_label); Dom inv; runClamVarTags(pre, bb, llvm_bb->getContext()); } } } llvm::outs() << ""\\n********* ENDING CUSTOM ANALYSIS **********\\n""; return; } template void wrapperPathAnalyze(const std::vector& path, std::vector& core, bool layered_solving, bool populate_inv_map, abs_dom_map_t& post, bool &res) { using path_analyzer_t = path_analyzer; AbsDom init; path_analyzer_t path_analyzer(get_cfg(), init); res = path_analyzer.solve(path, layered_solving); if (populate_inv_map) { for(auto n: path) { if (const llvm::BasicBlock* bb = n.get_basic_block()) { AbsDom abs_val = path_analyzer.get_fwd_constraints(n); post.insert({bb, mkGenericAbsDomWrapper(abs_val)}); if (abs_val.is_bottom()) { // the rest of blocks must be also bottom so we don't // bother storing them. break; } } } } if (!res) { path_analyzer.get_unsat_core(core); } } struct intra_analysis { std::function analyze; std::string name; }; struct path_analysis { std::function&, std::vector&, bool, bool, abs_dom_map_t&,bool&)> analyze; std::string name; }; // Domains used for intra-procedural analysis const std::map intra_analyses { { ZONES_SPLIT_DBM , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""zones"" }} #ifdef HAVE_ALL_DOMAINS , { INTERVALS_CONGRUENCES , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""reduced product of intervals and congruences"" }} , { DIS_INTERVALS , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""disjunctive intervals"" }} , { TERMS_INTERVALS , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""terms with intervals"" }} , { WRAPPED_INTERVALS , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""wrapped intervals"" }} , { TERMS_ZONES , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""terms with zones"" }} , { TERMS_DIS_INTERVALS , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""terms with disjunctive intervals"" }} , { OCT , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""octagons"" }} , { BOXES , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""boxes"" }} , { PK , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""polyhedra"" }} , { INTERVALS , { bind_this(this, &IntraClam_Impl::analyzeCfg), ""classical intervals"" }} #endif }; // Domains used for path-based analysis const std::map path_analyses { { ZONES_SPLIT_DBM , { bind_this(this, &IntraClam_Impl::wrapperPathAnalyze), ""zones"" }} #ifdef HAVE_ALL_DOMAINS , { INTERVALS , { bind_this(this, &IntraClam_Impl::wrapperPathAnalyze), ""classical intervals"" }} , { TERMS_INTERVALS , { bind_this(this, &IntraClam_Impl::wrapperPathAnalyze), ""terms with intervals"" }} , { WRAPPED_INTERVALS , { bind_this(this, &IntraClam_Impl::wrapperPathAnalyze), ""wrapped intervals"" }} , { TERMS_ZONES , { bind_this(this, &IntraClam_Impl::wrapperPathAnalyze), ""terms with zones"" }} , { BOXES , { bind_this(this, &IntraClam_Impl::wrapperPathAnalyze), ""boxes"" }} #endif /* To add new domains here make sure you add an explicit instantiation in crab/path_analyzer.cc */ //, { TERMS_DIS_INTERVALS , { bind_this(this, &IntraClam_Impl::wrapperPathAnalyze), ""terms with disjunctive intervals"" }} }; }; // end class /** * Begin IntraClam methods **/ IntraClam::IntraClam(const Function &fun, CrabBuilderManager &man) : m_impl(nullptr), m_fun(fun), m_builder_man(man) { m_impl = make_unique(m_fun, m_builder_man); } IntraClam::~IntraClam() {} void IntraClam::clear() { m_pre_map.clear(); m_post_map.clear(); m_checks_db.clear(); } CrabBuilderManager& IntraClam::get_cfg_builder_man() { return m_builder_man; } void IntraClam::analyze(AnalysisParams ¶ms, const abs_dom_map_t &assumptions) { AnalysisResults results = { m_pre_map, m_post_map, m_infeasible_edges, m_checks_db}; lin_csts_map_t lin_csts_assumptions; m_impl->Analyze(params, &(m_fun.getEntryBlock()), assumptions, lin_csts_assumptions, results); } void IntraClam::analyze(AnalysisParams ¶ms, const llvm::BasicBlock *entry, const abs_dom_map_t &assumptions) { AnalysisResults results = { m_pre_map, m_post_map, m_infeasible_edges, m_checks_db}; lin_csts_map_t lin_csts_assumptions; m_impl->Analyze(params, entry, assumptions, lin_csts_assumptions, results); } void IntraClam::analyze(AnalysisParams ¶ms, const lin_csts_map_t &assumptions) { AnalysisResults results = { m_pre_map, m_post_map, m_infeasible_edges, m_checks_db}; abs_dom_map_t abs_dom_assumptions; m_impl->Analyze(params, &(m_fun.getEntryBlock()), abs_dom_assumptions, assumptions, results); } void IntraClam::analyze(AnalysisParams ¶ms, const llvm::BasicBlock *entry, const lin_csts_map_t &assumptions) { AnalysisResults results = { m_pre_map, m_post_map, m_infeasible_edges, m_checks_db}; abs_dom_map_t abs_dom_assumptions; m_impl->Analyze(params, entry, abs_dom_assumptions, assumptions, results); } template<> bool IntraClam::path_analyze(const AnalysisParams& params, const std::vector& path, bool layered_solving, std::vector& core) const { abs_dom_map_t post_conditions; return m_impl->pathAnalyze(params, path, layered_solving, core, false, post_conditions); } template<> bool IntraClam::path_analyze(const AnalysisParams& params, const std::vector& path, bool layered_solving, std::vector& core, abs_dom_map_t& post_conditions) const { return m_impl->pathAnalyze(params, path, layered_solving, core, true, post_conditions); } wrapper_dom_ptr IntraClam::get_pre(const llvm::BasicBlock *block, bool keep_shadows) const { std::vector shadows; auto &vfac = m_builder_man.get_var_factory(); if (!keep_shadows) shadows = std::vector(vfac.get_shadow_vars().begin(), vfac.get_shadow_vars().end()); return lookup(m_pre_map, *block, shadows); } wrapper_dom_ptr IntraClam::get_post(const llvm::BasicBlock *block, bool keep_shadows) const { std::vector shadows; auto &vfac = m_builder_man.get_var_factory(); if (!keep_shadows) shadows = std::vector(vfac.get_shadow_vars().begin(), vfac.get_shadow_vars().end()); return lookup(m_post_map, *block, shadows); } bool IntraClam::has_feasible_edge(const llvm::BasicBlock *b1, const llvm::BasicBlock* b2) const { return !(m_infeasible_edges.count({b1, b2}) > 0); } const checks_db_t& IntraClam::get_checks_db() const { return m_checks_db;} /** * End IntraClam methods **/ /** * Internal implementation of the inter-procedural analysis **/ class InterClam_Impl { public: InterClam_Impl(const Module& M, CrabBuilderManager &man) : m_cg(nullptr), m_crab_builder_man(man), m_M(M) { std::vector cfg_ref_vector; for (auto const &F : m_M) { if (isTrackable(F)) { // -- build cfg's if (!man.has_cfg(F)) { m_crab_builder_man.mk_cfg_builder(F); } cfg_t* cfg = &(m_crab_builder_man.get_cfg(F)); cfg_ref_vector.push_back(*cfg); CRAB_VERBOSE_IF(1, llvm::outs() << ""Built Crab CFG for "" << F.getName() << ""\\n""); } else { CRAB_VERBOSE_IF(1, llvm::outs() << ""Cannot build CFG for "" << F.getName() << ""\\n""); } } // build call graph m_cg = make_unique(cfg_ref_vector.begin(), cfg_ref_vector.end()); } void Analyze(AnalysisParams ¶ms, // assumptions can be provided in abs_dom format or // as linear constraints. const abs_dom_map_t &abs_dom_assumptions /*unused*/, const lin_csts_map_t &lin_csts_assumptions /*unused*/, AnalysisResults &results) { // If the number of live variables per block is too high we // switch to a cheap domain regardless what the user wants. CrabDomain absdom = params.dom; /* Compute liveness information and choose statically the abstract domain */ if (params.run_liveness || isRelationalDomain(absdom)) { unsigned max_live_per_blk = 0; for (auto cg_node: llvm::make_range(vertices(*m_cg))) { const liveness_t* live = nullptr; // Get the cfg builder to run liveness if (const Function *fun = m_M.getFunction(cg_node.name())) { auto cfg_builder = m_crab_builder_man.get_cfg_builder(*fun); assert(cfg_builder); // run liveness cfg_builder->compute_live_symbols(); live = cfg_builder->get_live_symbols(); // update max number of live variables for whole cg unsigned total_live, max_live_per_blk_, avg_live_per_blk; live->get_stats(total_live, max_live_per_blk_, avg_live_per_blk); max_live_per_blk = std::max(max_live_per_blk, max_live_per_blk_); } if (isRelationalDomain(absdom)) { // FIXME: the selection of the final domain is fixed for the // whole program. That is, if there is one function that // exceeds the threshold then the cheaper domain will be // used for all functions. We should be able to change // from one function to another. CRAB_VERBOSE_IF(1, crab::outs() << ""Max live per block: "" << max_live_per_blk << ""\\n"" << ""Threshold: "" << params.relational_threshold << ""\\n""); #ifdef HAVE_ALL_DOMAINS if (max_live_per_blk > params.relational_threshold) { // default domain absdom = INTERVALS; } #endif } if (params.run_liveness) { m_live_map.insert({cg_node.get_cfg(), live}); } } // end for } // -- run the interprocedural analysis if (!CrabBuildOnlyCFG) { //// // TODO: pass assumptions to the inter-procedural analysis ///// #ifndef TOP_DOWN_INTER_ANALYSIS if (inter_analyses.count({params.sum_dom, params.dom})) { inter_analyses.at({params.sum_dom, params.dom}).analyze(params, results); } else { if (inter_analyses.count({ZONES_SPLIT_DBM, ZONES_SPLIT_DBM})) { crab::outs() << ""Warning: abstract domains not found or enabled.\\n"" << ""Compile with -DALL_DOMAINS=ON.\\n""; // crab::outs() << ""Running "" << inter_analyses.at({ZONES_SPLIT_DBM, INTERVALS}).name // << ""\\n""; // inter_analyses.at({ZONES_SPLIT_DBM, INTERVALS}).analyze(params, results); } else { crab::outs() << ""Warning: inter-procedural analysis is not enabled.\\n"" << ""Compile with -DENABLE_INTER=ON or do not use --crab-inter\\n""; } } #else if (inter_analyses.count(params.dom)) { inter_analyses.at(params.dom).analyze(params, results); } else { if (inter_analyses.count(ZONES_SPLIT_DBM)) { crab::outs() << ""Warning: abstract domains not found or enabled.\\n"" << ""Compile with -DALL_DOMAINS=ON.\\n""; } else { crab::outs() << ""Warning: inter-procedural analysis is not enabled.\\n"" << ""Compile with -DENABLE_INTER=ON or do not use --crab-inter\\n""; } } #endif } } private: // crab call graph std::unique_ptr m_cg; // crab cfg builder manager CrabBuilderManager& m_crab_builder_man; // the LLVM module const Module& m_M; // live symbols liveness_map_t m_live_map; basic_block_label_t get_crab_basic_block(const BasicBlock* bb) const { const Function*f = bb->getParent(); auto builder = m_crab_builder_man.get_cfg_builder(*f); return builder->get_crab_basic_block(bb); } /** Run inter-procedural analysis on the whole call graph **/ #ifdef TOP_DOWN_INTER_ANALYSIS template #else template #endif void analyzeCg(const AnalysisParams ¶ms, AnalysisResults &results) { #ifdef TOP_DOWN_INTER_ANALYSIS CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Running top-down inter-procedural analysis "" << ""with domain:"" << ""\\"""" << Dom::getDomainName() << ""\\"""" << "" ...\\n"";); typedef top_down_inter_analyzer inter_analyzer_t; typedef top_down_inter_analyzer_parameters inter_params_t; inter_params_t inter_params; inter_params.run_checker = params.check; inter_params.checker_verbosity = params.check_verbose; inter_params.minimize_invariants = true; inter_params.max_call_contexts = params.max_calling_contexts; inter_params.live_map = (params.run_liveness ? &m_live_map : nullptr); inter_params.widening_delay = params.widening_delay; inter_params.descending_iters = params.narrowing_iters; inter_params.thresholds_size = params.widening_jumpset; inter_analyzer_t analyzer(*m_cg, inter_params); analyzer.run(Dom::top()); if (inter_params.run_checker) { results.checksdb += analyzer.get_all_checks(); } #else typedef bottom_up_inter_analyzer inter_analyzer_t; typedef inter_checker inter_checker_t; typedef assert_property_checker assert_prop_t; //typedef null_property_checker null_prop_t; CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Running inter-procedural analysis with "" << ""forward domain:"" << ""\\"""" << TDDom::getDomainName() << ""\\"""" << "" and bottom-up domain:"" << ""\\"""" << BUDom::getDomainName() << ""\\"""" << "" ...\\n"";); inter_analyzer_t analyzer(*m_cg, (params.run_liveness ? &m_live_map : nullptr), params.widening_delay, params.narrowing_iters, params.widening_jumpset); analyzer.run(TDDom::top()); #endif CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Finished inter-procedural analysis.\\n""); // -- store invariants if (params.store_invariants || params.print_invars) { CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Storing invariants.\\n""); } for (auto &n: llvm::make_range(vertices(*m_cg))) { cfg_ref_t cfg = n.get_cfg(); if (const Function *F = m_M.getFunction(n.name())) { if (params.store_invariants || params.print_invars) { for (basic_block_label_t bl: llvm::make_range(cfg.label_begin(),cfg.label_end())) { if (bl.is_edge()) { // Note that we use get_post instead of get_pre: // the crab block (bl) has an assume statement corresponding // to the branch condition in the predecessor of the // LLVM edge. We want the invariant *after* the // evaluation of the assume. if (analyzer.get_post(cfg, bl).is_bottom()) { results.infeasible_edges.insert({bl.get_edge().first, bl.get_edge().second}); } } else if (const BasicBlock *B = bl.get_basic_block()) { // --- invariants that hold at the entry of the blocks auto pre = analyzer.get_pre(cfg, get_crab_basic_block(B)); update(results.premap, *B, mkGenericAbsDomWrapper(pre)); // --- invariants that hold at the exit of the blocks auto post = analyzer.get_post(cfg, get_crab_basic_block(B)); update(results.postmap, *B, mkGenericAbsDomWrapper(post)); #if 0 if (params.stats) { unsigned num_block_invars = 0; // XXX: for boxes we should use // to_disjunctive_linear_constraint_system() but it // can be very expensive. num_block_invars += pre.to_linear_constraint_system().size(); num_invars += num_block_invars; if (num_block_invars > 0) num_nontrivial_blocks++; } #endif } else { // this should be unreachable assert(false && ""A Crab block should correspond to either an LLVM edge or block""); } } // --- print invariants and summaries if (params.print_invars && isTrackable(*F)) { if (cfg.has_func_decl()) { auto fdecl = cfg.get_func_decl(); crab::outs() << ""\\n"" << fdecl << ""\\n""; } else { llvm::outs() << ""\\n"" << ""function "" << F->getName() << ""\\n""; } std::vector> annotations; annotations.emplace_back(make_unique (m_crab_builder_man.get_var_factory(), results.premap, results.postmap, params.keep_shadow_vars)); pretty_printer_impl::print_annotations(cfg, annotations); } } #ifndef TOP_DOWN_INTER_ANALYSIS // Summaries are not currently stored but it would be easy to do so. if (params.print_summaries && analyzer.has_summary(cfg)) { auto summ = analyzer.get_summary(cfg); crab::outs() << ""SUMMARY "" << *summ << ""\\n""; } #endif } } if (params.store_invariants || params.print_invars) { CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""All invariants stored.\\n""); } #ifndef TOP_DOWN_INTER_ANALYSIS // --- checking assertions and collecting data if (params.check) { CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Checking assertions ... \\n""); typename inter_checker_t::prop_checker_ptr prop(new assert_prop_t(params.check_verbose)); // if (params.check == NULLITY) // prop.reset(new null_prop_t(params.check_verbose)); inter_checker_t checker(analyzer, {prop}); checker.run(); //CRAB_VERBOSE_IF(1, checker.show(crab::outs())); results.checksdb += checker.get_all_checks(); CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Finished assert checking.\\n""); } #endif return; } // Domains used for inter-procedural analysis struct inter_analysis { std::function analyze; std::string name; }; // Domains used for intra-procedural analysis #ifdef TOP_DOWN_INTER_ANALYSIS const std::map inter_analyses { #ifdef HAVE_INTER { ZONES_SPLIT_DBM, { bind_this(this, &InterClam_Impl::analyzeCg), ""zones"" }} #ifdef HAVE_ALL_DOMAINS , { INTERVALS, { bind_this(this, &InterClam_Impl::analyzeCg), ""intervals"" }} , { WRAPPED_INTERVALS, { bind_this(this, &InterClam_Impl::analyzeCg), ""wrapped intervals"" }} , { OCT, { bind_this(this, &InterClam_Impl::analyzeCg), ""oct"" }} , { TERMS_ZONES, { bind_this(this, &InterClam_Impl::analyzeCg), ""terms+zones"" }} , { TERMS_DIS_INTERVALS, { bind_this(this, &InterClam_Impl::analyzeCg), ""terms+dis_intervals"" }} , { BOXES, { bind_this(this, &InterClam_Impl::analyzeCg), ""boxes"" }} , { PK, { bind_this(this, &InterClam_Impl::analyzeCg), ""pk"" }} #endif #endif }; }; #else const std::map, inter_analysis> inter_analyses { #ifdef HAVE_INTER {{ZONES_SPLIT_DBM, ZONES_SPLIT_DBM}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:zones, top-down:zones"" }} #ifdef HAVE_ALL_DOMAINS , {{ZONES_SPLIT_DBM, INTERVALS}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:zones, top-down:intervals"" }} , {{ZONES_SPLIT_DBM, WRAPPED_INTERVALS}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:zones, top-down:wrapped intervals"" }} , {{ZONES_SPLIT_DBM, OCT}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:zones, top-down:oct"" }} , {{ZONES_SPLIT_DBM, TERMS_ZONES}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:zones, top-down:terms+zones"" }} , {{ZONES_SPLIT_DBM, TERMS_DIS_INTERVALS}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:zones, top-down:terms+dis_intervals"" }} , {{ZONES_SPLIT_DBM, BOXES}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:zones, top-down:boxes"" }} , {{ZONES_SPLIT_DBM, PK}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:zones, top-down:pk"" }} , {{OCT, INTERVALS}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:oct, top-down:intervals"" }} , {{OCT, WRAPPED_INTERVALS}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:oct, top-down:wrapped intervals"" }} , {{OCT, ZONES_SPLIT_DBM}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:oct, top-down:zones"" }} , {{OCT, BOXES}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:oct, top-down:boxes"" }} , {{OCT, OCT}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:oct, top-down:oct"" }} , {{OCT, PK}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:oct, top-down:pk"" }} , {{OCT, TERMS_ZONES}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:oct, top-down:terms+zones"" }} , {{OCT, TERMS_DIS_INTERVALS}, { bind_this(this, &InterClam_Impl::analyzeCg), ""bottom-up:oct, top-down:terms+dis_intervals"" }} #endif #endif }; }; #endif /** * Begin InterClam methods **/ InterClam::InterClam(const Module &module, CrabBuilderManager &man) : m_impl(nullptr), m_builder_man(man) { m_impl = make_unique(module, m_builder_man); } InterClam::~InterClam() {} void InterClam::clear() { m_pre_map.clear(); m_post_map.clear(); m_checks_db.clear(); } CrabBuilderManager& InterClam::get_cfg_builder_man() { return m_builder_man; } void InterClam::analyze(AnalysisParams ¶ms, const abs_dom_map_t &assumptions) { AnalysisResults results = { m_pre_map, m_post_map, m_infeasible_edges, m_checks_db}; lin_csts_map_t lin_csts_assumptions; m_impl->Analyze(params, assumptions, lin_csts_assumptions, results); } void InterClam::analyze(AnalysisParams ¶ms, const lin_csts_map_t &assumptions) { AnalysisResults results = { m_pre_map, m_post_map, m_infeasible_edges, m_checks_db}; abs_dom_map_t abs_dom_assumptions; m_impl->Analyze(params, abs_dom_assumptions, assumptions, results); } wrapper_dom_ptr InterClam::get_pre(const llvm::BasicBlock *block, bool keep_shadows) const { std::vector shadows; if (!keep_shadows) shadows = std::vector(m_builder_man.get_var_factory(). get_shadow_vars().begin(), m_builder_man.get_var_factory(). get_shadow_vars().end()); return lookup(m_pre_map, *block, shadows); } wrapper_dom_ptr InterClam::get_post(const llvm::BasicBlock *block, bool keep_shadows) const { std::vector shadows; if (!keep_shadows) shadows = std::vector(m_builder_man.get_var_factory(). get_shadow_vars().begin(), m_builder_man.get_var_factory(). get_shadow_vars().end()); return lookup(m_post_map, *block, shadows); } bool InterClam::has_feasible_edge(const llvm::BasicBlock *b1, const llvm::BasicBlock* b2) const { return !(m_infeasible_edges.count({b1, b2}) > 0); } const checks_db_t& InterClam::get_checks_db() const { return m_checks_db;} /** * End InterClam methods **/ /** * Begin ClamPass methods **/ ClamPass::ClamPass(): llvm::ModulePass(ID), m_cfg_builder_man(nullptr) {} void ClamPass::releaseMemory() { m_pre_map.clear(); m_post_map.clear(); m_checks_db.clear(); } bool ClamPass::runOnModule(Module &M) { /// Translate the module to Crab CFGs CrabBuilderParams params(CrabTrackLev, CrabCFGSimplify, true, CrabEnableUniqueScalars, CrabMemShadows, CrabIncludeHavoc, CrabUseArraySmashing, CrabEnableBignums, CrabPrintCFG); auto &tli = getAnalysis().getTLI(); /// Create the CFG builder manager if (!CrabMemShadows) { std::unique_ptr mem(new DummyHeapAbstraction()); // If CrabMemShadows is enabled then we don't run any heap // analysis. switch(CrabHeapAnalysis) { case heap_analysis_t::LLVM_DSA: #ifdef HAVE_DSA CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Started llvm-dsa analysis\\n"";); mem.reset (new LlvmDsaHeapAbstraction(M,&getAnalysis(), CrabDsaDisambiguateUnknown, CrabDsaDisambiguatePtrCast, CrabDsaDisambiguateExternal)); CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Finished llvm-dsa analysis\\n"";); break; #else CLAM_WARNING(""llvm-dsa heap analysis is not available. Running sea-dsa""); // execute CI_SEA_DSA #endif case heap_analysis_t::CI_SEA_DSA: case heap_analysis_t::CS_SEA_DSA: { CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Started sea-dsa analysis\\n"";); CallGraph& cg = getAnalysis().getCallGraph(); const DataLayout& dl = M.getDataLayout(); sea_dsa::AllocWrapInfo* allocWrapInfo = &getAnalysis(); mem.reset (new LegacySeaDsaHeapAbstraction(M, cg, dl, tli, *allocWrapInfo, (CrabHeapAnalysis == heap_analysis_t::CS_SEA_DSA), CrabUseArraySmashing, CrabDsaDisambiguateUnknown, CrabDsaDisambiguatePtrCast, CrabDsaDisambiguateExternal)); CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Finished sea-dsa analysis\\n"";); break; } case heap_analysis_t::NONE: default: CLAM_WARNING(""running clam without heap analysis""); } m_cfg_builder_man.reset(new CrabBuilderManager(params, tli, std::move(mem))); } else { if (auto smp = getAnalysisIfAvailable()) { m_cfg_builder_man.reset(new CrabBuilderManager(params, tli, smp->getShadowMem())); } else { std::unique_ptr mem(new DummyHeapAbstraction()); m_cfg_builder_man.reset(new CrabBuilderManager(params, tli, std::move(mem))); if (CrabMemShadows) CLAM_WARNING(""getAnalysisIfAvailable returned null""); } } /// Run the analysis m_params.dom = ClamDomain; #ifndef TOP_DOWN_INTER_ANALYSIS m_params.sum_dom = CrabSummDomain; #endif m_params.run_backward = CrabBackward; m_params.run_inter = CrabInter; #ifdef TOP_DOWN_INTER_ANALYSIS m_params.max_calling_contexts = CrabInterMaxSummaries; #endif m_params.run_liveness = CrabLive; m_params.relational_threshold = CrabRelationalThreshold; m_params.widening_delay = CrabWideningDelay; m_params.narrowing_iters = CrabNarrowingIters; m_params.widening_jumpset = CrabWideningJumpSet; m_params.stats = CrabStats; m_params.print_invars = CrabPrintAns; m_params.print_unjustified_assumptions = CrabPrintUnjustifiedAssumptions; m_params.print_summaries = CrabPrintSumm; m_params.store_invariants = CrabStoreInvariants; m_params.keep_shadow_vars = CrabKeepShadows; m_params.check = CrabCheck; m_params.check_verbose = CrabCheckVerbose; unsigned num_analyzed_funcs = 0; for (auto &F : M) { if (!isTrackable(F)) continue; num_analyzed_funcs++; } CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""Started clam\\n""; crab::get_msg_stream() << ""Total number of analyzed functions:"" << num_analyzed_funcs << ""\\n"";); if (CrabInter){ InterClam_Impl inter_crab(M, *m_cfg_builder_man); AnalysisResults results = { m_pre_map, m_post_map, m_infeasible_edges, m_checks_db}; /* -- empty assumptions */ abs_dom_map_t abs_dom_assumptions; lin_csts_map_t lin_csts_assumptions; inter_crab.Analyze(m_params, abs_dom_assumptions, lin_csts_assumptions, results); } else { unsigned fun_counter = 1; for (auto &F : M) { if (!CrabInter && isTrackable(F)) { CRAB_VERBOSE_IF(1, crab::get_msg_stream() << ""###Function "" << fun_counter << ""/"" << num_analyzed_funcs << ""###\\n"";); ++fun_counter; runOnFunction(F); } } } if (CrabStats) { crab::CrabStats::PrintBrunch(crab::outs()); } if (CrabCheck) { llvm::outs() << ""\\n************** ANALYSIS RESULTS ****************\\n""; print_checks(llvm::outs()); llvm::outs() << ""************** ANALYSIS RESULTS END*************\\n""; if (CrabStats) { llvm::outs() << ""\\n************** BRUNCH STATS ********************\\n""; if (get_total_checks() == 0) { llvm::outs() << ""BRUNCH_STAT Result NOCHECKS\\n""; } else if (get_total_error_checks() > 0) { llvm::outs() << ""BRUNCH_STAT Result FALSE\\n""; } else if (get_total_warning_checks() == 0) { llvm::outs() << ""BRUNCH_STAT Result TRUE\\n""; } else { llvm::outs() << ""BRUNCH_STAT Result INCONCLUSIVE\\n""; } #if 0 llvm::outs() << ""BRUNCH_STAT NumOfBlocksWithInvariants "" << num_nontrivial_blocks << ""\\n""; llvm::outs() << ""BRUNCH_STAT SizeOfInvariants "" << num_invars << ""\\n""; #endif llvm::outs() << ""************** BRUNCH STATS END *****************\\n\\n""; } } return false; } bool ClamPass::runOnFunction(Function &F) { IntraClam_Impl intra_crab(F, *m_cfg_builder_man); AnalysisResults results = { m_pre_map, m_post_map, m_infeasible_edges, m_checks_db}; /* -- empty assumptions */ abs_dom_map_t abs_dom_assumptions; lin_csts_map_t lin_csts_assumptions; intra_crab.Analyze(m_params, &F.getEntryBlock(), abs_dom_assumptions, lin_csts_assumptions, results); return false; } void ClamPass::getAnalysisUsage(AnalysisUsage &AU) const { bool runSeaDsa = false; AU.setPreservesAll(); if (!CrabMemShadows && CrabHeapAnalysis == heap_analysis_t::LLVM_DSA) { #ifdef HAVE_DSA AU.addRequiredTransitive(); #else runSeaDsa = true; #endif } AU.addRequired(); if (!runSeaDsa) { runSeaDsa = (CrabHeapAnalysis == heap_analysis_t::CI_SEA_DSA || CrabHeapAnalysis == heap_analysis_t::CS_SEA_DSA); } if (!CrabMemShadows && runSeaDsa) { AU.addRequired(); } if (CrabMemShadows) { AU.addRequired(); } AU.addRequired(); AU.addRequired(); AU.addRequired(); } /** * For clam clients **/ bool ClamPass::has_cfg(llvm::Function &F) { return m_cfg_builder_man->has_cfg(F); } cfg_ref_t ClamPass::get_cfg(llvm::Function &F) { assert(m_cfg_builder_man->has_cfg(F)); return m_cfg_builder_man->get_cfg(F); } CrabBuilderManager& ClamPass::get_cfg_builder_man() { return *m_cfg_builder_man; } // return invariants that hold at the entry of block wrapper_dom_ptr ClamPass::get_pre(const llvm::BasicBlock *block, bool keep_shadows) const { std::vector shadows; auto &vfac = m_cfg_builder_man->get_var_factory(); if (!keep_shadows) shadows = std::vector(vfac.get_shadow_vars().begin(), vfac.get_shadow_vars().end()); return lookup(m_pre_map, *block, shadows); } // return invariants that hold at the exit of block wrapper_dom_ptr ClamPass::get_post(const llvm::BasicBlock *block, bool keep_shadows) const { std::vector shadows; auto &vfac = m_cfg_builder_man->get_var_factory(); if (!keep_shadows) shadows = std::vector(vfac.get_shadow_vars().begin(), vfac.get_shadow_vars().end()); return lookup(m_post_map, *block, shadows); } bool ClamPass::has_feasible_edge(const llvm::BasicBlock *b1, const llvm::BasicBlock* b2) const { return !(m_infeasible_edges.count({b1, b2}) > 0); } /** * For assertion checking **/ unsigned ClamPass::get_total_checks() const { return get_total_safe_checks() + get_total_error_checks() + get_total_warning_checks(); } unsigned ClamPass::get_total_safe_checks() const { return m_checks_db.get_total_safe(); } unsigned ClamPass::get_total_error_checks() const { return m_checks_db.get_total_error(); } unsigned ClamPass::get_total_warning_checks() const { return m_checks_db.get_total_warning(); } void ClamPass::print_checks(raw_ostream &o) const { unsigned safe = get_total_safe_checks(); unsigned unsafe = get_total_error_checks(); unsigned warning = get_total_warning_checks(); std::vector cnts = { safe, unsafe, warning}; unsigned MaxValLen = 0; for (auto c: cnts) MaxValLen = std::max(MaxValLen, (unsigned)std::to_string(c).size()); o << std::string((int) MaxValLen - std::to_string(safe).size(), ' ') << safe << std::string(2, ' ') << ""Number of total safe checks\\n"" << std::string((int) MaxValLen - std::to_string(unsafe).size(), ' ') << unsafe << std::string(2, ' ') << ""Number of total error checks\\n"" << std::string((int) MaxValLen - std::to_string(warning).size(), ' ') << warning << std::string(2, ' ') << ""Number of total warning checks\\n""; } char clam::ClamPass::ID = 0; } // end namespace static RegisterPass X(""clam"", ""Infer invariants using Crab"", false, false); ",16278,True,3219.186189364869,median "// This file is auto-generated. Do not edit! #include ""precomp.hpp"" #include ""opencl_kernels_objdetect.hpp"" namespace cv { namespace ocl { namespace objdetect { const struct ProgramEntry cascadedetect={""cascadedetect"", ""#ifdef HAAR\\n"" ""typedef struct __attribute__((aligned(4))) OptHaarFeature\\n"" ""{\\n"" ""int4 ofs[3] __attribute__((aligned (4)));\\n"" ""float4 weight __attribute__((aligned (4)));\\n"" ""}\\n"" ""OptHaarFeature;\\n"" ""#endif\\n"" ""#ifdef LBP\\n"" ""typedef struct __attribute__((aligned(4))) OptLBPFeature\\n"" ""{\\n"" ""int16 ofs __attribute__((aligned (4)));\\n"" ""}\\n"" ""OptLBPFeature;\\n"" ""#endif\\n"" ""typedef struct __attribute__((aligned(4))) Stump\\n"" ""{\\n"" ""float4 st __attribute__((aligned (4)));\\n"" ""}\\n"" ""Stump;\\n"" ""typedef struct __attribute__((aligned(4))) Node\\n"" ""{\\n"" ""int4 n __attribute__((aligned (4)));\\n"" ""}\\n"" ""Node;\\n"" ""typedef struct __attribute__((aligned (4))) Stage\\n"" ""{\\n"" ""int first __attribute__((aligned (4)));\\n"" ""int ntrees __attribute__((aligned (4)));\\n"" ""float threshold __attribute__((aligned (4)));\\n"" ""}\\n"" ""Stage;\\n"" ""typedef struct __attribute__((aligned (4))) ScaleData\\n"" ""{\\n"" ""float scale __attribute__((aligned (4)));\\n"" ""int szi_width __attribute__((aligned (4)));\\n"" ""int szi_height __attribute__((aligned (4)));\\n"" ""int layer_ofs __attribute__((aligned (4)));\\n"" ""int ystep __attribute__((aligned (4)));\\n"" ""}\\n"" ""ScaleData;\\n"" ""#ifndef SUM_BUF_SIZE\\n"" ""#define SUM_BUF_SIZE 0\\n"" ""#endif\\n"" ""#ifndef NODE_COUNT\\n"" ""#define NODE_COUNT 1\\n"" ""#endif\\n"" ""#ifdef HAAR\\n"" ""__kernel __attribute__((reqd_work_group_size(LOCAL_SIZE_X,LOCAL_SIZE_Y,1)))\\n"" ""void runHaarClassifier(\\n"" ""int nscales, __global const ScaleData* scaleData,\\n"" ""__global const int* sum,\\n"" ""int _sumstep, int sumoffset,\\n"" ""__global const OptHaarFeature* optfeatures,\\n"" ""__global const Stage* stages,\\n"" ""__global const Node* nodes,\\n"" ""__global const float* leaves0,\\n"" ""volatile __global int* facepos,\\n"" ""int4 normrect, int sqofs, int2 windowsize)\\n"" ""{\\n"" ""int lx = get_local_id(0);\\n"" ""int ly = get_local_id(1);\\n"" ""int groupIdx = get_group_id(0);\\n"" ""int i, ngroups = get_global_size(0)/LOCAL_SIZE_X;\\n"" ""int scaleIdx, tileIdx, stageIdx;\\n"" ""int sumstep = (int)(_sumstep/sizeof(int));\\n"" ""int4 nofs0 = (int4)(mad24(normrect.y, sumstep, normrect.x),\\n"" ""mad24(normrect.y, sumstep, normrect.x + normrect.z),\\n"" ""mad24(normrect.y + normrect.w, sumstep, normrect.x),\\n"" ""mad24(normrect.y + normrect.w, sumstep, normrect.x + normrect.z));\\n"" ""int normarea = normrect.z * normrect.w;\\n"" ""float invarea = 1.f/normarea;\\n"" ""int lidx = ly*LOCAL_SIZE_X + lx;\\n"" ""#if SUM_BUF_SIZE > 0\\n"" ""int4 nofs = (int4)(mad24(normrect.y, SUM_BUF_STEP, normrect.x),\\n"" ""mad24(normrect.y, SUM_BUF_STEP, normrect.x + normrect.z),\\n"" ""mad24(normrect.y + normrect.w, SUM_BUF_STEP, normrect.x),\\n"" ""mad24(normrect.y + normrect.w, SUM_BUF_STEP, normrect.x + normrect.z));\\n"" ""#else\\n"" ""int4 nofs = nofs0;\\n"" ""#endif\\n"" ""#define LOCAL_SIZE (LOCAL_SIZE_X*LOCAL_SIZE_Y)\\n"" ""__local int lstore[SUM_BUF_SIZE + LOCAL_SIZE*5/2+1];\\n"" ""#if SUM_BUF_SIZE > 0\\n"" ""__local int* ibuf = lstore;\\n"" ""__local int* lcount = ibuf + SUM_BUF_SIZE;\\n"" ""#else\\n"" ""__local int* lcount = lstore;\\n"" ""#endif\\n"" ""__local float* lnf = (__local float*)(lcount + 1);\\n"" ""__local float* lpartsum = lnf + LOCAL_SIZE;\\n"" ""__local short* lbuf = (__local short*)(lpartsum + LOCAL_SIZE);\\n"" ""for( scaleIdx = nscales-1; scaleIdx >= 0; scaleIdx-- )\\n"" ""{\\n"" ""__global const ScaleData* s = scaleData + scaleIdx;\\n"" ""int ystep = s->ystep;\\n"" ""int2 worksize = (int2)(max(s->szi_width - windowsize.x, 0), max(s->szi_height - windowsize.y, 0));\\n"" ""int2 ntiles = (int2)((worksize.x + LOCAL_SIZE_X-1)/LOCAL_SIZE_X,\\n"" ""(worksize.y + LOCAL_SIZE_Y-1)/LOCAL_SIZE_Y);\\n"" ""int totalTiles = ntiles.x*ntiles.y;\\n"" ""for( tileIdx = groupIdx; tileIdx < totalTiles; tileIdx += ngroups )\\n"" ""{\\n"" ""int ix0 = (tileIdx % ntiles.x)*LOCAL_SIZE_X;\\n"" ""int iy0 = (tileIdx / ntiles.x)*LOCAL_SIZE_Y;\\n"" ""int ix = lx, iy = ly;\\n"" ""__global const int* psum0 = sum + mad24(iy0, sumstep, ix0) + s->layer_ofs;\\n"" ""__global const int* psum1 = psum0 + mad24(iy, sumstep, ix);\\n"" ""if( ix0 >= worksize.x || iy0 >= worksize.y )\\n"" ""continue;\\n"" ""#if SUM_BUF_SIZE > 0\\n"" ""for( i = lidx*4; i < SUM_BUF_SIZE; i += LOCAL_SIZE_X*LOCAL_SIZE_Y*4 )\\n"" ""{\\n"" ""int dy = i/SUM_BUF_STEP, dx = i - dy*SUM_BUF_STEP;\\n"" ""vstore4(vload4(0, psum0 + mad24(dy, sumstep, dx)), 0, ibuf+i);\\n"" ""}\\n"" ""#endif\\n"" ""if( lidx == 0 )\\n"" ""lcount[0] = 0;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if( ix0 + ix < worksize.x && iy0 + iy < worksize.y )\\n"" ""{\\n"" ""#if NODE_COUNT==1\\n"" ""__global const Stump* stump = (__global const Stump*)nodes;\\n"" ""#else\\n"" ""__global const Node* node = nodes;\\n"" ""__global const float* leaves = leaves0;\\n"" ""#endif\\n"" ""#if SUM_BUF_SIZE > 0\\n"" ""__local const int* psum = ibuf + mad24(iy, SUM_BUF_STEP, ix);\\n"" ""#else\\n"" ""__global const int* psum = psum1;\\n"" ""#endif\\n"" ""__global const int* psqsum = (__global const int*)(psum1 + sqofs);\\n"" ""float sval = (psum[nofs.x] - psum[nofs.y] - psum[nofs.z] + psum[nofs.w])*invarea;\\n"" ""float sqval = (psqsum[nofs0.x] - psqsum[nofs0.y] - psqsum[nofs0.z] + psqsum[nofs0.w])*invarea;\\n"" ""float nf = (float)normarea * sqrt(max(sqval - sval * sval, 0.f));\\n"" ""nf = nf > 0 ? nf : 1.f;\\n"" ""for( stageIdx = 0; stageIdx < SPLIT_STAGE; stageIdx++ )\\n"" ""{\\n"" ""int ntrees = stages[stageIdx].ntrees;\\n"" ""float s = 0.f;\\n"" ""#if NODE_COUNT==1\\n"" ""for( i = 0; i < ntrees; i++ )\\n"" ""{\\n"" ""float4 st = stump[i].st;\\n"" ""__global const OptHaarFeature* f = optfeatures + as_int(st.x);\\n"" ""float4 weight = f->weight;\\n"" ""int4 ofs = f->ofs[0];\\n"" ""sval = (psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w])*weight.x;\\n"" ""ofs = f->ofs[1];\\n"" ""sval = mad((psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w]), weight.y, sval);\\n"" ""if( weight.z > 0 )\\n"" ""{\\n"" ""ofs = f->ofs[2];\\n"" ""sval = mad((psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w]), weight.z, sval);\\n"" ""}\\n"" ""s += (sval < st.y*nf) ? st.z : st.w;\\n"" ""}\\n"" ""stump += ntrees;\\n"" ""#else\\n"" ""for( i = 0; i < ntrees; i++, node += NODE_COUNT, leaves += NODE_COUNT+1 )\\n"" ""{\\n"" ""int idx = 0;\\n"" ""do\\n"" ""{\\n"" ""int4 n = node[idx].n;\\n"" ""__global const OptHaarFeature* f = optfeatures + n.x;\\n"" ""float4 weight = f->weight;\\n"" ""int4 ofs = f->ofs[0];\\n"" ""sval = (psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w])*weight.x;\\n"" ""ofs = f->ofs[1];\\n"" ""sval = mad((psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w]), weight.y, sval);\\n"" ""if( weight.z > 0 )\\n"" ""{\\n"" ""ofs = f->ofs[2];\\n"" ""sval = mad((psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w]), weight.z, sval);\\n"" ""}\\n"" ""idx = (sval < as_float(n.y)*nf) ? n.z : n.w;\\n"" ""}\\n"" ""while(idx > 0);\\n"" ""s += leaves[-idx];\\n"" ""}\\n"" ""#endif\\n"" ""if( s < stages[stageIdx].threshold )\\n"" ""break;\\n"" ""}\\n"" ""if( stageIdx == SPLIT_STAGE && (ystep == 1 || ((ix | iy) & 1) == 0) )\\n"" ""{\\n"" ""int count = atomic_inc(lcount);\\n"" ""lbuf[count] = (int)(ix | (iy << 8));\\n"" ""lnf[count] = nf;\\n"" ""}\\n"" ""}\\n"" ""for( stageIdx = SPLIT_STAGE; stageIdx < N_STAGES; stageIdx++ )\\n"" ""{\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""int nrects = lcount[0];\\n"" ""if( nrects == 0 )\\n"" ""break;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if( lidx == 0 )\\n"" ""lcount[0] = 0;\\n"" ""{\\n"" ""#if NODE_COUNT == 1\\n"" ""__global const Stump* stump = (__global const Stump*)nodes + stages[stageIdx].first;\\n"" ""#else\\n"" ""__global const Node* node = nodes + stages[stageIdx].first*NODE_COUNT;\\n"" ""__global const float* leaves = leaves0 + stages[stageIdx].first*(NODE_COUNT+1);\\n"" ""#endif\\n"" ""int nparts = LOCAL_SIZE / nrects;\\n"" ""int ntrees = stages[stageIdx].ntrees;\\n"" ""int ntrees_p = (ntrees + nparts - 1)/nparts;\\n"" ""int nr = lidx / nparts;\\n"" ""int partidx = -1, idxval = 0;\\n"" ""float partsum = 0.f, nf = 0.f;\\n"" ""if( nr < nrects )\\n"" ""{\\n"" ""partidx = lidx % nparts;\\n"" ""idxval = lbuf[nr];\\n"" ""nf = lnf[nr];\\n"" ""{\\n"" ""int ntrees0 = ntrees_p*partidx;\\n"" ""int ntrees1 = min(ntrees0 + ntrees_p, ntrees);\\n"" ""int ix1 = idxval & 255, iy1 = idxval >> 8;\\n"" ""#if SUM_BUF_SIZE > 0\\n"" ""__local const int* psum = ibuf + mad24(iy1, SUM_BUF_STEP, ix1);\\n"" ""#else\\n"" ""__global const int* psum = psum0 + mad24(iy1, sumstep, ix1);\\n"" ""#endif\\n"" ""#if NODE_COUNT == 1\\n"" ""for( i = ntrees0; i < ntrees1; i++ )\\n"" ""{\\n"" ""float4 st = stump[i].st;\\n"" ""__global const OptHaarFeature* f = optfeatures + as_int(st.x);\\n"" ""float4 weight = f->weight;\\n"" ""int4 ofs = f->ofs[0];\\n"" ""float sval = (psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w])*weight.x;\\n"" ""ofs = f->ofs[1];\\n"" ""sval = mad((psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w]), weight.y, sval);\\n"" ""if( fabs(weight.z) > 0 )\\n"" ""{\\n"" ""ofs = f->ofs[2];\\n"" ""sval = mad((psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w]), weight.z, sval);\\n"" ""}\\n"" ""partsum += (sval < st.y*nf) ? st.z : st.w;\\n"" ""}\\n"" ""#else\\n"" ""for( i = ntrees0; i < ntrees1; i++ )\\n"" ""{\\n"" ""int idx = 0;\\n"" ""do\\n"" ""{\\n"" ""int4 n = node[i*2 + idx].n;\\n"" ""__global const OptHaarFeature* f = optfeatures + n.x;\\n"" ""float4 weight = f->weight;\\n"" ""int4 ofs = f->ofs[0];\\n"" ""float sval = (psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w])*weight.x;\\n"" ""ofs = f->ofs[1];\\n"" ""sval = mad((psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w]), weight.y, sval);\\n"" ""if( weight.z > 0 )\\n"" ""{\\n"" ""ofs = f->ofs[2];\\n"" ""sval = mad((psum[ofs.x] - psum[ofs.y] - psum[ofs.z] + psum[ofs.w]), weight.z, sval);\\n"" ""}\\n"" ""idx = (sval < as_float(n.y)*nf) ? n.z : n.w;\\n"" ""}\\n"" ""while(idx > 0);\\n"" ""partsum += leaves[i*3-idx];\\n"" ""}\\n"" ""#endif\\n"" ""}\\n"" ""}\\n"" ""lpartsum[lidx] = partsum;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if( partidx == 0 )\\n"" ""{\\n"" ""float s = lpartsum[nr*nparts];\\n"" ""for( i = 1; i < nparts; i++ )\\n"" ""s += lpartsum[i + nr*nparts];\\n"" ""if( s >= stages[stageIdx].threshold )\\n"" ""{\\n"" ""int count = atomic_inc(lcount);\\n"" ""lbuf[count] = idxval;\\n"" ""lnf[count] = nf;\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if( stageIdx == N_STAGES )\\n"" ""{\\n"" ""int nrects = lcount[0];\\n"" ""if( lidx < nrects )\\n"" ""{\\n"" ""int nfaces = atomic_inc(facepos);\\n"" ""if( nfaces < MAX_FACES )\\n"" ""{\\n"" ""volatile __global int* face = facepos + 1 + nfaces*3;\\n"" ""int val = lbuf[lidx];\\n"" ""face[0] = scaleIdx;\\n"" ""face[1] = ix0 + (val & 255);\\n"" ""face[2] = iy0 + (val >> 8);\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""#endif\\n"" ""#ifdef LBP\\n"" ""#undef CALC_SUM_OFS_\\n"" ""#define CALC_SUM_OFS_(p0, p1, p2, p3, ptr) \\\\\\n"" ""((ptr)[p0] - (ptr)[p1] - (ptr)[p2] + (ptr)[p3])\\n"" ""__kernel void runLBPClassifierStumpSimple(\\n"" ""int nscales, __global const ScaleData* scaleData,\\n"" ""__global const int* sum,\\n"" ""int _sumstep, int sumoffset,\\n"" ""__global const OptLBPFeature* optfeatures,\\n"" ""__global const Stage* stages,\\n"" ""__global const Stump* stumps,\\n"" ""__global const int* bitsets,\\n"" ""int bitsetSize,\\n"" ""volatile __global int* facepos,\\n"" ""int2 windowsize)\\n"" ""{\\n"" ""int lx = get_local_id(0);\\n"" ""int ly = get_local_id(1);\\n"" ""int local_size_x = get_local_size(0);\\n"" ""int local_size_y = get_local_size(1);\\n"" ""int groupIdx = get_group_id(1)*get_num_groups(0) + get_group_id(0);\\n"" ""int ngroups = get_num_groups(0)*get_num_groups(1);\\n"" ""int scaleIdx, tileIdx, stageIdx;\\n"" ""int sumstep = (int)(_sumstep/sizeof(int));\\n"" ""for( scaleIdx = nscales-1; scaleIdx >= 0; scaleIdx-- )\\n"" ""{\\n"" ""__global const ScaleData* s = scaleData + scaleIdx;\\n"" ""int ystep = s->ystep;\\n"" ""int2 worksize = (int2)(max(s->szi_width - windowsize.x, 0), max(s->szi_height - windowsize.y, 0));\\n"" ""int2 ntiles = (int2)((worksize.x/ystep + local_size_x-1)/local_size_x,\\n"" ""(worksize.y/ystep + local_size_y-1)/local_size_y);\\n"" ""int totalTiles = ntiles.x*ntiles.y;\\n"" ""for( tileIdx = groupIdx; tileIdx < totalTiles; tileIdx += ngroups )\\n"" ""{\\n"" ""int iy = mad24((tileIdx / ntiles.x), local_size_y, ly) * ystep;\\n"" ""int ix = mad24((tileIdx % ntiles.x), local_size_x, lx) * ystep;\\n"" ""if( ix < worksize.x && iy < worksize.y )\\n"" ""{\\n"" ""__global const int* p = sum + mad24(iy, sumstep, ix) + s->layer_ofs;\\n"" ""__global const Stump* stump = stumps;\\n"" ""__global const int* bitset = bitsets;\\n"" ""for( stageIdx = 0; stageIdx < N_STAGES; stageIdx++ )\\n"" ""{\\n"" ""int i, ntrees = stages[stageIdx].ntrees;\\n"" ""float s = 0.f;\\n"" ""for( i = 0; i < ntrees; i++, stump++, bitset += bitsetSize )\\n"" ""{\\n"" ""float4 st = stump->st;\\n"" ""__global const OptLBPFeature* f = optfeatures + as_int(st.x);\\n"" ""int16 ofs = f->ofs;\\n"" ""int cval = CALC_SUM_OFS_( ofs.s5, ofs.s6, ofs.s9, ofs.sa, p );\\n"" ""int mask, idx = (CALC_SUM_OFS_( ofs.s0, ofs.s1, ofs.s4, ofs.s5, p ) >= cval ? 4 : 0);\\n"" ""idx |= (CALC_SUM_OFS_( ofs.s1, ofs.s2, ofs.s5, ofs.s6, p ) >= cval ? 2 : 0);\\n"" ""idx |= (CALC_SUM_OFS_( ofs.s2, ofs.s3, ofs.s6, ofs.s7, p ) >= cval ? 1 : 0);\\n"" ""mask = (CALC_SUM_OFS_( ofs.s6, ofs.s7, ofs.sa, ofs.sb, p ) >= cval ? 16 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.sa, ofs.sb, ofs.se, ofs.sf, p ) >= cval ? 8 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.s9, ofs.sa, ofs.sd, ofs.se, p ) >= cval ? 4 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.s8, ofs.s9, ofs.sc, ofs.sd, p ) >= cval ? 2 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.s4, ofs.s5, ofs.s8, ofs.s9, p ) >= cval ? 1 : 0);\\n"" ""s += (bitset[idx] & (1 << mask)) ? st.z : st.w;\\n"" ""}\\n"" ""if( s < stages[stageIdx].threshold )\\n"" ""break;\\n"" ""}\\n"" ""if( stageIdx == N_STAGES )\\n"" ""{\\n"" ""int nfaces = atomic_inc(facepos);\\n"" ""if( nfaces < MAX_FACES )\\n"" ""{\\n"" ""volatile __global int* face = facepos + 1 + nfaces*3;\\n"" ""face[0] = scaleIdx;\\n"" ""face[1] = ix;\\n"" ""face[2] = iy;\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""__kernel __attribute__((reqd_work_group_size(LOCAL_SIZE_X,LOCAL_SIZE_Y,1)))\\n"" ""void runLBPClassifierStump(\\n"" ""int nscales, __global const ScaleData* scaleData,\\n"" ""__global const int* sum,\\n"" ""int _sumstep, int sumoffset,\\n"" ""__global const OptLBPFeature* optfeatures,\\n"" ""__global const Stage* stages,\\n"" ""__global const Stump* stumps,\\n"" ""__global const int* bitsets,\\n"" ""int bitsetSize,\\n"" ""volatile __global int* facepos,\\n"" ""int2 windowsize)\\n"" ""{\\n"" ""int lx = get_local_id(0);\\n"" ""int ly = get_local_id(1);\\n"" ""int groupIdx = get_group_id(0);\\n"" ""int i, ngroups = get_global_size(0)/LOCAL_SIZE_X;\\n"" ""int scaleIdx, tileIdx, stageIdx;\\n"" ""int sumstep = (int)(_sumstep/sizeof(int));\\n"" ""int lidx = ly*LOCAL_SIZE_X + lx;\\n"" ""#define LOCAL_SIZE (LOCAL_SIZE_X*LOCAL_SIZE_Y)\\n"" ""__local int lstore[SUM_BUF_SIZE + LOCAL_SIZE*3/2+1];\\n"" ""#if SUM_BUF_SIZE > 0\\n"" ""__local int* ibuf = lstore;\\n"" ""__local int* lcount = ibuf + SUM_BUF_SIZE;\\n"" ""#else\\n"" ""__local int* lcount = lstore;\\n"" ""#endif\\n"" ""__local float* lpartsum = (__local float*)(lcount + 1);\\n"" ""__local short* lbuf = (__local short*)(lpartsum + LOCAL_SIZE);\\n"" ""for( scaleIdx = nscales-1; scaleIdx >= 0; scaleIdx-- )\\n"" ""{\\n"" ""__global const ScaleData* s = scaleData + scaleIdx;\\n"" ""int ystep = s->ystep;\\n"" ""int2 worksize = (int2)(max(s->szi_width - windowsize.x, 0), max(s->szi_height - windowsize.y, 0));\\n"" ""int2 ntiles = (int2)((worksize.x + LOCAL_SIZE_X-1)/LOCAL_SIZE_X,\\n"" ""(worksize.y + LOCAL_SIZE_Y-1)/LOCAL_SIZE_Y);\\n"" ""int totalTiles = ntiles.x*ntiles.y;\\n"" ""for( tileIdx = groupIdx; tileIdx < totalTiles; tileIdx += ngroups )\\n"" ""{\\n"" ""int ix0 = (tileIdx % ntiles.x)*LOCAL_SIZE_X;\\n"" ""int iy0 = (tileIdx / ntiles.x)*LOCAL_SIZE_Y;\\n"" ""int ix = lx, iy = ly;\\n"" ""__global const int* psum0 = sum + mad24(iy0, sumstep, ix0) + s->layer_ofs;\\n"" ""if( ix0 >= worksize.x || iy0 >= worksize.y )\\n"" ""continue;\\n"" ""#if SUM_BUF_SIZE > 0\\n"" ""for( i = lidx*4; i < SUM_BUF_SIZE; i += LOCAL_SIZE_X*LOCAL_SIZE_Y*4 )\\n"" ""{\\n"" ""int dy = i/SUM_BUF_STEP, dx = i - dy*SUM_BUF_STEP;\\n"" ""vstore4(vload4(0, psum0 + mad24(dy, sumstep, dx)), 0, ibuf+i);\\n"" ""}\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""#endif\\n"" ""if( lidx == 0 )\\n"" ""lcount[0] = 0;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if( ix0 + ix < worksize.x && iy0 + iy < worksize.y )\\n"" ""{\\n"" ""__global const Stump* stump = stumps;\\n"" ""__global const int* bitset = bitsets;\\n"" ""#if SUM_BUF_SIZE > 0\\n"" ""__local const int* p = ibuf + mad24(iy, SUM_BUF_STEP, ix);\\n"" ""#else\\n"" ""__global const int* p = psum0 + mad24(iy, sumstep, ix);\\n"" ""#endif\\n"" ""for( stageIdx = 0; stageIdx < SPLIT_STAGE; stageIdx++ )\\n"" ""{\\n"" ""int ntrees = stages[stageIdx].ntrees;\\n"" ""float s = 0.f;\\n"" ""for( i = 0; i < ntrees; i++, stump++, bitset += bitsetSize )\\n"" ""{\\n"" ""float4 st = stump->st;\\n"" ""__global const OptLBPFeature* f = optfeatures + as_int(st.x);\\n"" ""int16 ofs = f->ofs;\\n"" ""int cval = CALC_SUM_OFS_( ofs.s5, ofs.s6, ofs.s9, ofs.sa, p );\\n"" ""int mask, idx = (CALC_SUM_OFS_( ofs.s0, ofs.s1, ofs.s4, ofs.s5, p ) >= cval ? 4 : 0);\\n"" ""idx |= (CALC_SUM_OFS_( ofs.s1, ofs.s2, ofs.s5, ofs.s6, p ) >= cval ? 2 : 0);\\n"" ""idx |= (CALC_SUM_OFS_( ofs.s2, ofs.s3, ofs.s6, ofs.s7, p ) >= cval ? 1 : 0);\\n"" ""mask = (CALC_SUM_OFS_( ofs.s6, ofs.s7, ofs.sa, ofs.sb, p ) >= cval ? 16 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.sa, ofs.sb, ofs.se, ofs.sf, p ) >= cval ? 8 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.s9, ofs.sa, ofs.sd, ofs.se, p ) >= cval ? 4 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.s8, ofs.s9, ofs.sc, ofs.sd, p ) >= cval ? 2 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.s4, ofs.s5, ofs.s8, ofs.s9, p ) >= cval ? 1 : 0);\\n"" ""s += (bitset[idx] & (1 << mask)) ? st.z : st.w;\\n"" ""}\\n"" ""if( s < stages[stageIdx].threshold )\\n"" ""break;\\n"" ""}\\n"" ""if( stageIdx == SPLIT_STAGE && (ystep == 1 || ((ix | iy) & 1) == 0) )\\n"" ""{\\n"" ""int count = atomic_inc(lcount);\\n"" ""lbuf[count] = (int)(ix | (iy << 8));\\n"" ""}\\n"" ""}\\n"" ""for( stageIdx = SPLIT_STAGE; stageIdx < N_STAGES; stageIdx++ )\\n"" ""{\\n"" ""int nrects = lcount[0];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if( nrects == 0 )\\n"" ""break;\\n"" ""if( lidx == 0 )\\n"" ""lcount[0] = 0;\\n"" ""{\\n"" ""__global const Stump* stump = stumps + stages[stageIdx].first;\\n"" ""__global const int* bitset = bitsets + stages[stageIdx].first*bitsetSize;\\n"" ""int nparts = LOCAL_SIZE / nrects;\\n"" ""int ntrees = stages[stageIdx].ntrees;\\n"" ""int ntrees_p = (ntrees + nparts - 1)/nparts;\\n"" ""int nr = lidx / nparts;\\n"" ""int partidx = -1, idxval = 0;\\n"" ""float partsum = 0.f, nf = 0.f;\\n"" ""if( nr < nrects )\\n"" ""{\\n"" ""partidx = lidx % nparts;\\n"" ""idxval = lbuf[nr];\\n"" ""{\\n"" ""int ntrees0 = ntrees_p*partidx;\\n"" ""int ntrees1 = min(ntrees0 + ntrees_p, ntrees);\\n"" ""int ix1 = idxval & 255, iy1 = idxval >> 8;\\n"" ""#if SUM_BUF_SIZE > 0\\n"" ""__local const int* p = ibuf + mad24(iy1, SUM_BUF_STEP, ix1);\\n"" ""#else\\n"" ""__global const int* p = psum0 + mad24(iy1, sumstep, ix1);\\n"" ""#endif\\n"" ""for( i = ntrees0; i < ntrees1; i++ )\\n"" ""{\\n"" ""float4 st = stump[i].st;\\n"" ""__global const OptLBPFeature* f = optfeatures + as_int(st.x);\\n"" ""int16 ofs = f->ofs;\\n"" ""#define CALC_SUM_OFS_(p0, p1, p2, p3, ptr) \\\\\\n"" ""((ptr)[p0] - (ptr)[p1] - (ptr)[p2] + (ptr)[p3])\\n"" ""int cval = CALC_SUM_OFS_( ofs.s5, ofs.s6, ofs.s9, ofs.sa, p );\\n"" ""int mask, idx = (CALC_SUM_OFS_( ofs.s0, ofs.s1, ofs.s4, ofs.s5, p ) >= cval ? 4 : 0);\\n"" ""idx |= (CALC_SUM_OFS_( ofs.s1, ofs.s2, ofs.s5, ofs.s6, p ) >= cval ? 2 : 0);\\n"" ""idx |= (CALC_SUM_OFS_( ofs.s2, ofs.s3, ofs.s6, ofs.s7, p ) >= cval ? 1 : 0);\\n"" ""mask = (CALC_SUM_OFS_( ofs.s6, ofs.s7, ofs.sa, ofs.sb, p ) >= cval ? 16 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.sa, ofs.sb, ofs.se, ofs.sf, p ) >= cval ? 8 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.s9, ofs.sa, ofs.sd, ofs.se, p ) >= cval ? 4 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.s8, ofs.s9, ofs.sc, ofs.sd, p ) >= cval ? 2 : 0);\\n"" ""mask |= (CALC_SUM_OFS_( ofs.s4, ofs.s5, ofs.s8, ofs.s9, p ) >= cval ? 1 : 0);\\n"" ""partsum += (bitset[i*bitsetSize + idx] & (1 << mask)) ? st.z : st.w;\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""lpartsum[lidx] = partsum;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if( partidx == 0 )\\n"" ""{\\n"" ""float s = lpartsum[nr*nparts];\\n"" ""for( i = 1; i < nparts; i++ )\\n"" ""s += lpartsum[i + nr*nparts];\\n"" ""if( s >= stages[stageIdx].threshold )\\n"" ""{\\n"" ""int count = atomic_inc(lcount);\\n"" ""lbuf[count] = idxval;\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if( stageIdx == N_STAGES )\\n"" ""{\\n"" ""int nrects = lcount[0];\\n"" ""if( lidx < nrects )\\n"" ""{\\n"" ""int nfaces = atomic_inc(facepos);\\n"" ""if( nfaces < MAX_FACES )\\n"" ""{\\n"" ""volatile __global int* face = facepos + 1 + nfaces*3;\\n"" ""int val = lbuf[lidx];\\n"" ""face[0] = scaleIdx;\\n"" ""face[1] = ix0 + (val & 255);\\n"" ""face[2] = iy0 + (val >> 8);\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""}\\n"" ""#endif\\n"" , ""06c037755dc15a7796c0f3bc7ff05233""}; ProgramSource cascadedetect_oclsrc(cascadedetect.programStr); const struct ProgramEntry objdetect_hog={""objdetect_hog"", ""#define CELL_WIDTH 8\\n"" ""#define CELL_HEIGHT 8\\n"" ""#define CELLS_PER_BLOCK_X 2\\n"" ""#define CELLS_PER_BLOCK_Y 2\\n"" ""#define NTHREADS 256\\n"" ""#define CV_PI_F M_PI_F\\n"" ""#ifdef INTEL_DEVICE\\n"" ""#define QANGLE_TYPE int\\n"" ""#define QANGLE_TYPE2 int2\\n"" ""#else\\n"" ""#define QANGLE_TYPE uchar\\n"" ""#define QANGLE_TYPE2 uchar2\\n"" ""#endif\\n"" ""__kernel void compute_hists_lut_kernel(\\n"" ""const int cblock_stride_x, const int cblock_stride_y,\\n"" ""const int cnbins, const int cblock_hist_size, const int img_block_width,\\n"" ""const int blocks_in_group, const int blocks_total,\\n"" ""const int grad_quadstep, const int qangle_step,\\n"" ""__global const float* grad, __global const QANGLE_TYPE* qangle,\\n"" ""__global const float* gauss_w_lut,\\n"" ""__global float* block_hists, __local float* smem)\\n"" ""{\\n"" ""const int lx = get_local_id(0);\\n"" ""const int lp = lx / 24; \\n"" ""const int gid = get_group_id(0) * blocks_in_group + lp;\\n"" ""const int gidY = gid / img_block_width;\\n"" ""const int gidX = gid - gidY * img_block_width;\\n"" ""const int lidX = lx - lp * 24;\\n"" ""const int lidY = get_local_id(1);\\n"" ""const int cell_x = lidX / 12;\\n"" ""const int cell_y = lidY;\\n"" ""const int cell_thread_x = lidX - cell_x * 12;\\n"" ""__local float* hists = smem + lp * cnbins * (CELLS_PER_BLOCK_X *\\n"" ""CELLS_PER_BLOCK_Y * 12 + CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y);\\n"" ""__local float* final_hist = hists + cnbins *\\n"" ""(CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y * 12);\\n"" ""const int offset_x = gidX * cblock_stride_x + (cell_x << 2) + cell_thread_x;\\n"" ""const int offset_y = gidY * cblock_stride_y + (cell_y << 2);\\n"" ""__global const float* grad_ptr = (gid < blocks_total) ?\\n"" ""grad + offset_y * grad_quadstep + (offset_x << 1) : grad;\\n"" ""__global const QANGLE_TYPE* qangle_ptr = (gid < blocks_total) ?\\n"" ""qangle + offset_y * qangle_step + (offset_x << 1) : qangle;\\n"" ""__local float* hist = hists + 12 * (cell_y * CELLS_PER_BLOCK_Y + cell_x) +\\n"" ""cell_thread_x;\\n"" ""for (int bin_id = 0; bin_id < cnbins; ++bin_id)\\n"" ""hist[bin_id * 48] = 0.f;\\n"" ""const int dist_x = -4 + cell_thread_x - 4 * cell_x;\\n"" ""const int dist_center_x = dist_x - 4 * (1 - 2 * cell_x);\\n"" ""const int dist_y_begin = -4 - 4 * lidY;\\n"" ""for (int dist_y = dist_y_begin; dist_y < dist_y_begin + 12; ++dist_y)\\n"" ""{\\n"" ""float2 vote = (float2) (grad_ptr[0], grad_ptr[1]);\\n"" ""QANGLE_TYPE2 bin = (QANGLE_TYPE2) (qangle_ptr[0], qangle_ptr[1]);\\n"" ""grad_ptr += grad_quadstep;\\n"" ""qangle_ptr += qangle_step;\\n"" ""int dist_center_y = dist_y - 4 * (1 - 2 * cell_y);\\n"" ""int idx = (dist_center_y + 8) * 16 + (dist_center_x + 8);\\n"" ""float gaussian = gauss_w_lut[idx];\\n"" ""idx = (dist_y + 8) * 16 + (dist_x + 8);\\n"" ""float interp_weight = gauss_w_lut[256+idx];\\n"" ""hist[bin.x * 48] += gaussian * interp_weight * vote.x;\\n"" ""hist[bin.y * 48] += gaussian * interp_weight * vote.y;\\n"" ""}\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""volatile __local float* hist_ = hist;\\n"" ""for (int bin_id = 0; bin_id < cnbins; ++bin_id, hist_ += 48)\\n"" ""{\\n"" ""if (cell_thread_x < 6)\\n"" ""hist_[0] += hist_[6];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (cell_thread_x < 3)\\n"" ""hist_[0] += hist_[3];\\n"" ""#ifdef CPU\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""#endif\\n"" ""if (cell_thread_x == 0)\\n"" ""final_hist[(cell_x * 2 + cell_y) * cnbins + bin_id] =\\n"" ""hist_[0] + hist_[1] + hist_[2];\\n"" ""}\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""int tid = (cell_y * CELLS_PER_BLOCK_Y + cell_x) * 12 + cell_thread_x;\\n"" ""if ((tid < cblock_hist_size) && (gid < blocks_total))\\n"" ""{\\n"" ""__global float* block_hist = block_hists +\\n"" ""(gidY * img_block_width + gidX) * cblock_hist_size;\\n"" ""block_hist[tid] = final_hist[tid];\\n"" ""}\\n"" ""}\\n"" ""__kernel void normalize_hists_36_kernel(__global float* block_hists,\\n"" ""const float threshold, __local float *squares)\\n"" ""{\\n"" ""const int tid = get_local_id(0);\\n"" ""const int gid = get_global_id(0);\\n"" ""const int bid = tid / 36; \\n"" ""const int boffset = bid * 36; \\n"" ""const int hid = tid - boffset; \\n"" ""float elem = block_hists[gid];\\n"" ""squares[tid] = elem * elem;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""__local float* smem = squares + boffset;\\n"" ""float sum = smem[hid];\\n"" ""if (hid < 18)\\n"" ""smem[hid] = sum = sum + smem[hid + 18];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (hid < 9)\\n"" ""smem[hid] = sum = sum + smem[hid + 9];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (hid < 4)\\n"" ""smem[hid] = sum + smem[hid + 4];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""sum = smem[0] + smem[1] + smem[2] + smem[3] + smem[8];\\n"" ""elem = elem / (sqrt(sum) + 3.6f);\\n"" ""elem = min(elem, threshold);\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""squares[tid] = elem * elem;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""sum = smem[hid];\\n"" ""if (hid < 18)\\n"" ""smem[hid] = sum = sum + smem[hid + 18];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (hid < 9)\\n"" ""smem[hid] = sum = sum + smem[hid + 9];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (hid < 4)\\n"" ""smem[hid] = sum + smem[hid + 4];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""sum = smem[0] + smem[1] + smem[2] + smem[3] + smem[8];\\n"" ""block_hists[gid] = elem / (sqrt(sum) + 1e-3f);\\n"" ""}\\n"" ""inline float reduce_smem(volatile __local float* smem, int size)\\n"" ""{\\n"" ""unsigned int tid = get_local_id(0);\\n"" ""float sum = smem[tid];\\n"" ""if (size >= 512) { if (tid < 256) smem[tid] = sum = sum + smem[tid + 256];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE); }\\n"" ""if (size >= 256) { if (tid < 128) smem[tid] = sum = sum + smem[tid + 128];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE); }\\n"" ""if (size >= 128) { if (tid < 64) smem[tid] = sum = sum + smem[tid + 64];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE); }\\n"" ""#ifdef CPU\\n"" ""if (size >= 64) { if (tid < 32) smem[tid] = sum = sum + smem[tid + 32];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE); }\\n"" ""if (size >= 32) { if (tid < 16) smem[tid] = sum = sum + smem[tid + 16];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE); }\\n"" ""if (size >= 16) { if (tid < 8) smem[tid] = sum = sum + smem[tid + 8];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE); }\\n"" ""if (size >= 8) { if (tid < 4) smem[tid] = sum = sum + smem[tid + 4];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE); }\\n"" ""if (size >= 4) { if (tid < 2) smem[tid] = sum = sum + smem[tid + 2];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE); }\\n"" ""if (size >= 2) { if (tid < 1) smem[tid] = sum = sum + smem[tid + 1];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE); }\\n"" ""#else\\n"" ""if (tid < 32)\\n"" ""{\\n"" ""if (size >= 64) smem[tid] = sum = sum + smem[tid + 32];\\n"" ""#if WAVE_SIZE < 32\\n"" ""} barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (tid < 16) {\\n"" ""#endif\\n"" ""if (size >= 32) smem[tid] = sum = sum + smem[tid + 16];\\n"" ""if (size >= 16) smem[tid] = sum = sum + smem[tid + 8];\\n"" ""if (size >= 8) smem[tid] = sum = sum + smem[tid + 4];\\n"" ""if (size >= 4) smem[tid] = sum = sum + smem[tid + 2];\\n"" ""if (size >= 2) smem[tid] = sum = sum + smem[tid + 1];\\n"" ""}\\n"" ""#endif\\n"" ""return sum;\\n"" ""}\\n"" ""__kernel void normalize_hists_kernel(\\n"" ""const int nthreads, const int block_hist_size, const int img_block_width,\\n"" ""__global float* block_hists, const float threshold, __local float *squares)\\n"" ""{\\n"" ""const int tid = get_local_id(0);\\n"" ""const int gidX = get_group_id(0);\\n"" ""const int gidY = get_group_id(1);\\n"" ""__global float* hist = block_hists + (gidY * img_block_width + gidX) *\\n"" ""block_hist_size + tid;\\n"" ""float elem = 0.f;\\n"" ""if (tid < block_hist_size)\\n"" ""elem = hist[0];\\n"" ""squares[tid] = elem * elem;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""float sum = reduce_smem(squares, nthreads);\\n"" ""float scale = 1.0f / (sqrt(sum) + 0.1f * block_hist_size);\\n"" ""elem = min(elem * scale, threshold);\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""squares[tid] = elem * elem;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""sum = reduce_smem(squares, nthreads);\\n"" ""scale = 1.0f / (sqrt(sum) + 1e-3f);\\n"" ""if (tid < block_hist_size)\\n"" ""hist[0] = elem * scale;\\n"" ""}\\n"" ""__kernel void classify_hists_180_kernel(\\n"" ""const int cdescr_width, const int cdescr_height, const int cblock_hist_size,\\n"" ""const int img_win_width, const int img_block_width,\\n"" ""const int win_block_stride_x, const int win_block_stride_y,\\n"" ""__global const float * block_hists, __global const float* coefs,\\n"" ""float free_coef, float threshold, __global uchar* labels)\\n"" ""{\\n"" ""const int tid = get_local_id(0);\\n"" ""const int gidX = get_group_id(0);\\n"" ""const int gidY = get_group_id(1);\\n"" ""__global const float* hist = block_hists + (gidY * win_block_stride_y *\\n"" ""img_block_width + gidX * win_block_stride_x) * cblock_hist_size;\\n"" ""float product = 0.f;\\n"" ""for (int i = 0; i < cdescr_height; i++)\\n"" ""{\\n"" ""product += coefs[i * cdescr_width + tid] *\\n"" ""hist[i * img_block_width * cblock_hist_size + tid];\\n"" ""}\\n"" ""__local float products[180];\\n"" ""products[tid] = product;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (tid < 90) products[tid] = product = product + products[tid + 90];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (tid < 45) products[tid] = product = product + products[tid + 45];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""volatile __local float* smem = products;\\n"" ""#ifdef CPU\\n"" ""if (tid < 13) smem[tid] = product = product + smem[tid + 32];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (tid < 16) smem[tid] = product = product + smem[tid + 16];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<8) smem[tid] = product = product + smem[tid + 8];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<4) smem[tid] = product = product + smem[tid + 4];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<2) smem[tid] = product = product + smem[tid + 2];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""#else\\n"" ""if (tid < 13)\\n"" ""{\\n"" ""smem[tid] = product = product + smem[tid + 32];\\n"" ""}\\n"" ""#if WAVE_SIZE < 32\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""#endif\\n"" ""if (tid < 16)\\n"" ""{\\n"" ""smem[tid] = product = product + smem[tid + 16];\\n"" ""smem[tid] = product = product + smem[tid + 8];\\n"" ""smem[tid] = product = product + smem[tid + 4];\\n"" ""smem[tid] = product = product + smem[tid + 2];\\n"" ""}\\n"" ""#endif\\n"" ""if (tid == 0){\\n"" ""product = product + smem[tid + 1];\\n"" ""labels[gidY * img_win_width + gidX] = (product + free_coef >= threshold);\\n"" ""}\\n"" ""}\\n"" ""__kernel void classify_hists_252_kernel(\\n"" ""const int cdescr_width, const int cdescr_height, const int cblock_hist_size,\\n"" ""const int img_win_width, const int img_block_width,\\n"" ""const int win_block_stride_x, const int win_block_stride_y,\\n"" ""__global const float * block_hists, __global const float* coefs,\\n"" ""float free_coef, float threshold, __global uchar* labels)\\n"" ""{\\n"" ""const int tid = get_local_id(0);\\n"" ""const int gidX = get_group_id(0);\\n"" ""const int gidY = get_group_id(1);\\n"" ""__global const float* hist = block_hists + (gidY * win_block_stride_y *\\n"" ""img_block_width + gidX * win_block_stride_x) * cblock_hist_size;\\n"" ""float product = 0.f;\\n"" ""if (tid < cdescr_width)\\n"" ""{\\n"" ""for (int i = 0; i < cdescr_height; i++)\\n"" ""product += coefs[i * cdescr_width + tid] *\\n"" ""hist[i * img_block_width * cblock_hist_size + tid];\\n"" ""}\\n"" ""__local float products[NTHREADS];\\n"" ""products[tid] = product;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (tid < 128) products[tid] = product = product + products[tid + 128];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (tid < 64) products[tid] = product = product + products[tid + 64];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""volatile __local float* smem = products;\\n"" ""#ifdef CPU\\n"" ""if(tid<32) smem[tid] = product = product + smem[tid + 32];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<16) smem[tid] = product = product + smem[tid + 16];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<8) smem[tid] = product = product + smem[tid + 8];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<4) smem[tid] = product = product + smem[tid + 4];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<2) smem[tid] = product = product + smem[tid + 2];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""#else\\n"" ""if (tid < 32)\\n"" ""{\\n"" ""smem[tid] = product = product + smem[tid + 32];\\n"" ""#if WAVE_SIZE < 32\\n"" ""} barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (tid < 16) {\\n"" ""#endif\\n"" ""smem[tid] = product = product + smem[tid + 16];\\n"" ""smem[tid] = product = product + smem[tid + 8];\\n"" ""smem[tid] = product = product + smem[tid + 4];\\n"" ""smem[tid] = product = product + smem[tid + 2];\\n"" ""}\\n"" ""#endif\\n"" ""if (tid == 0){\\n"" ""product = product + smem[tid + 1];\\n"" ""labels[gidY * img_win_width + gidX] = (product + free_coef >= threshold);\\n"" ""}\\n"" ""}\\n"" ""__kernel void classify_hists_kernel(\\n"" ""const int cdescr_size, const int cdescr_width, const int cblock_hist_size,\\n"" ""const int img_win_width, const int img_block_width,\\n"" ""const int win_block_stride_x, const int win_block_stride_y,\\n"" ""__global const float * block_hists, __global const float* coefs,\\n"" ""float free_coef, float threshold, __global uchar* labels)\\n"" ""{\\n"" ""const int tid = get_local_id(0);\\n"" ""const int gidX = get_group_id(0);\\n"" ""const int gidY = get_group_id(1);\\n"" ""__global const float* hist = block_hists + (gidY * win_block_stride_y *\\n"" ""img_block_width + gidX * win_block_stride_x) * cblock_hist_size;\\n"" ""float product = 0.f;\\n"" ""for (int i = tid; i < cdescr_size; i += NTHREADS)\\n"" ""{\\n"" ""int offset_y = i / cdescr_width;\\n"" ""int offset_x = i - offset_y * cdescr_width;\\n"" ""product += coefs[i] *\\n"" ""hist[offset_y * img_block_width * cblock_hist_size + offset_x];\\n"" ""}\\n"" ""__local float products[NTHREADS];\\n"" ""products[tid] = product;\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (tid < 128) products[tid] = product = product + products[tid + 128];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (tid < 64) products[tid] = product = product + products[tid + 64];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""volatile __local float* smem = products;\\n"" ""#ifdef CPU\\n"" ""if(tid<32) smem[tid] = product = product + smem[tid + 32];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<16) smem[tid] = product = product + smem[tid + 16];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<8) smem[tid] = product = product + smem[tid + 8];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<4) smem[tid] = product = product + smem[tid + 4];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if(tid<2) smem[tid] = product = product + smem[tid + 2];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""#else\\n"" ""if (tid < 32)\\n"" ""{\\n"" ""smem[tid] = product = product + smem[tid + 32];\\n"" ""#if WAVE_SIZE < 32\\n"" ""} barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (tid < 16) {\\n"" ""#endif\\n"" ""smem[tid] = product = product + smem[tid + 16];\\n"" ""smem[tid] = product = product + smem[tid + 8];\\n"" ""smem[tid] = product = product + smem[tid + 4];\\n"" ""smem[tid] = product = product + smem[tid + 2];\\n"" ""}\\n"" ""#endif\\n"" ""if (tid == 0){\\n"" ""smem[tid] = product = product + smem[tid + 1];\\n"" ""labels[gidY * img_win_width + gidX] = (product + free_coef >= threshold);\\n"" ""}\\n"" ""}\\n"" ""__kernel void extract_descrs_by_rows_kernel(\\n"" ""const int cblock_hist_size, const int descriptors_quadstep,\\n"" ""const int cdescr_size, const int cdescr_width, const int img_block_width,\\n"" ""const int win_block_stride_x, const int win_block_stride_y,\\n"" ""__global const float* block_hists, __global float* descriptors)\\n"" ""{\\n"" ""int tid = get_local_id(0);\\n"" ""int gidX = get_group_id(0);\\n"" ""int gidY = get_group_id(1);\\n"" ""__global const float* hist = block_hists + (gidY * win_block_stride_y *\\n"" ""img_block_width + gidX * win_block_stride_x) * cblock_hist_size;\\n"" ""__global float* descriptor = descriptors +\\n"" ""(gidY * get_num_groups(0) + gidX) * descriptors_quadstep;\\n"" ""for (int i = tid; i < cdescr_size; i += NTHREADS)\\n"" ""{\\n"" ""int offset_y = i / cdescr_width;\\n"" ""int offset_x = i - offset_y * cdescr_width;\\n"" ""descriptor[i] = hist[offset_y * img_block_width * cblock_hist_size + offset_x];\\n"" ""}\\n"" ""}\\n"" ""__kernel void extract_descrs_by_cols_kernel(\\n"" ""const int cblock_hist_size, const int descriptors_quadstep, const int cdescr_size,\\n"" ""const int cnblocks_win_x, const int cnblocks_win_y, const int img_block_width,\\n"" ""const int win_block_stride_x, const int win_block_stride_y,\\n"" ""__global const float* block_hists, __global float* descriptors)\\n"" ""{\\n"" ""int tid = get_local_id(0);\\n"" ""int gidX = get_group_id(0);\\n"" ""int gidY = get_group_id(1);\\n"" ""__global const float* hist = block_hists + (gidY * win_block_stride_y *\\n"" ""img_block_width + gidX * win_block_stride_x) * cblock_hist_size;\\n"" ""__global float* descriptor = descriptors +\\n"" ""(gidY * get_num_groups(0) + gidX) * descriptors_quadstep;\\n"" ""for (int i = tid; i < cdescr_size; i += NTHREADS)\\n"" ""{\\n"" ""int block_idx = i / cblock_hist_size;\\n"" ""int idx_in_block = i - block_idx * cblock_hist_size;\\n"" ""int y = block_idx / cnblocks_win_x;\\n"" ""int x = block_idx - y * cnblocks_win_x;\\n"" ""descriptor[(x * cnblocks_win_y + y) * cblock_hist_size + idx_in_block] =\\n"" ""hist[(y * img_block_width + x) * cblock_hist_size + idx_in_block];\\n"" ""}\\n"" ""}\\n"" ""__kernel void compute_gradients_8UC4_kernel(\\n"" ""const int height, const int width,\\n"" ""const int img_step, const int grad_quadstep, const int qangle_step,\\n"" ""const __global uchar4 * img, __global float * grad, __global QANGLE_TYPE * qangle,\\n"" ""const float angle_scale, const char correct_gamma, const int cnbins)\\n"" ""{\\n"" ""const int x = get_global_id(0);\\n"" ""const int tid = get_local_id(0);\\n"" ""const int gSizeX = get_local_size(0);\\n"" ""const int gidY = get_group_id(1);\\n"" ""__global const uchar4* row = img + gidY * img_step;\\n"" ""__local float sh_row[(NTHREADS + 2) * 3];\\n"" ""uchar4 val;\\n"" ""if (x < width)\\n"" ""val = row[x];\\n"" ""else\\n"" ""val = row[width - 2];\\n"" ""sh_row[tid + 1] = val.x;\\n"" ""sh_row[tid + 1 + (NTHREADS + 2)] = val.y;\\n"" ""sh_row[tid + 1 + 2 * (NTHREADS + 2)] = val.z;\\n"" ""if (tid == 0)\\n"" ""{\\n"" ""val = row[max(x - 1, 1)];\\n"" ""sh_row[0] = val.x;\\n"" ""sh_row[(NTHREADS + 2)] = val.y;\\n"" ""sh_row[2 * (NTHREADS + 2)] = val.z;\\n"" ""}\\n"" ""if (tid == gSizeX - 1)\\n"" ""{\\n"" ""val = row[min(x + 1, width - 2)];\\n"" ""sh_row[gSizeX + 1] = val.x;\\n"" ""sh_row[gSizeX + 1 + (NTHREADS + 2)] = val.y;\\n"" ""sh_row[gSizeX + 1 + 2 * (NTHREADS + 2)] = val.z;\\n"" ""}\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (x < width)\\n"" ""{\\n"" ""float4 a = (float4) (sh_row[tid], sh_row[tid + (NTHREADS + 2)],\\n"" ""sh_row[tid + 2 * (NTHREADS + 2)], 0);\\n"" ""float4 b = (float4) (sh_row[tid + 2], sh_row[tid + 2 + (NTHREADS + 2)],\\n"" ""sh_row[tid + 2 + 2 * (NTHREADS + 2)], 0);\\n"" ""float4 dx;\\n"" ""if (correct_gamma == 1)\\n"" ""dx = sqrt(b) - sqrt(a);\\n"" ""else\\n"" ""dx = b - a;\\n"" ""float4 dy = (float4) 0.f;\\n"" ""if (gidY > 0 && gidY < height - 1)\\n"" ""{\\n"" ""a = convert_float4(img[(gidY - 1) * img_step + x].xyzw);\\n"" ""b = convert_float4(img[(gidY + 1) * img_step + x].xyzw);\\n"" ""if (correct_gamma == 1)\\n"" ""dy = sqrt(b) - sqrt(a);\\n"" ""else\\n"" ""dy = b - a;\\n"" ""}\\n"" ""float4 mag = hypot(dx, dy);\\n"" ""float best_dx = dx.x;\\n"" ""float best_dy = dy.x;\\n"" ""float mag0 = mag.x;\\n"" ""if (mag0 < mag.y)\\n"" ""{\\n"" ""best_dx = dx.y;\\n"" ""best_dy = dy.y;\\n"" ""mag0 = mag.y;\\n"" ""}\\n"" ""if (mag0 < mag.z)\\n"" ""{\\n"" ""best_dx = dx.z;\\n"" ""best_dy = dy.z;\\n"" ""mag0 = mag.z;\\n"" ""}\\n"" ""float ang = (atan2(best_dy, best_dx) + CV_PI_F) * angle_scale - 0.5f;\\n"" ""int hidx = (int)floor(ang);\\n"" ""ang -= hidx;\\n"" ""hidx = (hidx + cnbins) % cnbins;\\n"" ""qangle[(gidY * qangle_step + x) << 1] = hidx;\\n"" ""qangle[((gidY * qangle_step + x) << 1) + 1] = (hidx + 1) % cnbins;\\n"" ""grad[(gidY * grad_quadstep + x) << 1] = mag0 * (1.f - ang);\\n"" ""grad[((gidY * grad_quadstep + x) << 1) + 1] = mag0 * ang;\\n"" ""}\\n"" ""}\\n"" ""__kernel void compute_gradients_8UC1_kernel(\\n"" ""const int height, const int width,\\n"" ""const int img_step, const int grad_quadstep, const int qangle_step,\\n"" ""__global const uchar * img, __global float * grad, __global QANGLE_TYPE * qangle,\\n"" ""const float angle_scale, const char correct_gamma, const int cnbins)\\n"" ""{\\n"" ""const int x = get_global_id(0);\\n"" ""const int tid = get_local_id(0);\\n"" ""const int gSizeX = get_local_size(0);\\n"" ""const int gidY = get_group_id(1);\\n"" ""__global const uchar* row = img + gidY * img_step;\\n"" ""__local float sh_row[NTHREADS + 2];\\n"" ""if (x < width)\\n"" ""sh_row[tid + 1] = row[x];\\n"" ""else\\n"" ""sh_row[tid + 1] = row[width - 2];\\n"" ""if (tid == 0)\\n"" ""sh_row[0] = row[max(x - 1, 1)];\\n"" ""if (tid == gSizeX - 1)\\n"" ""sh_row[gSizeX + 1] = row[min(x + 1, width - 2)];\\n"" ""barrier(CLK_LOCAL_MEM_FENCE);\\n"" ""if (x < width)\\n"" ""{\\n"" ""float dx;\\n"" ""if (correct_gamma == 1)\\n"" ""dx = sqrt(sh_row[tid + 2]) - sqrt(sh_row[tid]);\\n"" ""else\\n"" ""dx = sh_row[tid + 2] - sh_row[tid];\\n"" ""float dy = 0.f;\\n"" ""if (gidY > 0 && gidY < height - 1)\\n"" ""{\\n"" ""float a = (float) img[ (gidY + 1) * img_step + x ];\\n"" ""float b = (float) img[ (gidY - 1) * img_step + x ];\\n"" ""if (correct_gamma == 1)\\n"" ""dy = sqrt(a) - sqrt(b);\\n"" ""else\\n"" ""dy = a - b;\\n"" ""}\\n"" ""float mag = hypot(dx, dy);\\n"" ""float ang = (atan2(dy, dx) + CV_PI_F) * angle_scale - 0.5f;\\n"" ""int hidx = (int)floor(ang);\\n"" ""ang -= hidx;\\n"" ""hidx = (hidx + cnbins) % cnbins;\\n"" ""qangle[ (gidY * qangle_step + x) << 1 ] = hidx;\\n"" ""qangle[ ((gidY * qangle_step + x) << 1) + 1 ] = (hidx + 1) % cnbins;\\n"" ""grad[ (gidY * grad_quadstep + x) << 1 ] = mag * (1.f - ang);\\n"" ""grad[ ((gidY * grad_quadstep + x) << 1) + 1 ] = mag * ang;\\n"" ""}\\n"" ""}\\n"" , ""bc57f4f75fb81bae73bfe73cc4ca15e4""}; ProgramSource objdetect_hog_oclsrc(objdetect_hog.programStr); } }} ",16345,True,2864.4619615768374,median "[[netty-component]] = Netty Component :page-source: components/camel-netty/src/main/docs/netty-component.adoc *Available as of Camel version 2.14* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 6 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *maximumPoolSize* (advanced) | The thread pool size for the EventExecutorGroup if its in use. The default value is 16. | 16 | int | *configuration* (advanced) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *executorService* (advanced) | To use the given EventExecutorGroup. | | EventExecutorGroup | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol:host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (71 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this operation to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrap Factory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. | WARN | LoggingLevel | *serverClosedChannel ExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. | DEBUG | LoggingLevel | *serverExceptionCaughtLog Level* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializer Factory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializer Factory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelState CorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictable Idle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads x 2. User can use this operation to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel camel-netty-starter x.x.x ---- The component supports 78 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.netty.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.netty.configuration.allow-default-codec* | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | Boolean | *camel.component.netty.configuration.allow-serialized-headers* | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | Boolean | *camel.component.netty.configuration.auto-append-delimiter* | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | Boolean | *camel.component.netty.configuration.backlog* | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the ""accept"" queue can be If this option is not configured, then the backlog depends on OS setting. | | Integer | *camel.component.netty.configuration.boss-count* | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this operation to override the default bossCount from Netty | 1 | Integer | *camel.component.netty.configuration.boss-group* | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *camel.component.netty.configuration.broadcast* | Setting to choose Multicast over UDP | false | Boolean | *camel.component.netty.configuration.channel-group* | To use a explicit ChannelGroup. | | ChannelGroup | *camel.component.netty.configuration.client-initializer-factory* | To use a custom ClientInitializerFactory | | ClientInitializer Factory | *camel.component.netty.configuration.client-mode* | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | Boolean | *camel.component.netty.configuration.connect-timeout* | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | Integer | *camel.component.netty.configuration.correlation-manager* | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed.

We recommend extending the {@link TimeoutCorrelationManagerSupport} when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well.

See also the producerPoolEnabled option for more details. | | NettyCamelState CorrelationManager | *camel.component.netty.configuration.decoder* | A custom ChannelHandler class that can be used to perform special marshalling of inbound payloads. | | ChannelHandler | *camel.component.netty.configuration.decoder-max-line-length* | The max line length to use for the textline codec. | 1024 | Integer | *camel.component.netty.configuration.decoders* | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *camel.component.netty.configuration.delimiter* | The delimiter to use for the textline codec. Possible values are LINE and NULL. | | TextLineDelimiter | *camel.component.netty.configuration.disconnect* | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | Boolean | *camel.component.netty.configuration.disconnect-on-no-reply* | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | Boolean | *camel.component.netty.configuration.enabled-protocols* | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *camel.component.netty.configuration.encoder* | A custom ChannelHandler class that can be used to perform special marshalling of outbound payloads. | | ChannelHandler | *camel.component.netty.configuration.encoders* | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *camel.component.netty.configuration.encoding* | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *camel.component.netty.configuration.host* | The hostname.

For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *camel.component.netty.configuration.keep-alive* | Setting to ensure socket is not closed due to inactivity | true | Boolean | *camel.component.netty.configuration.key-store-format* | Keystore format to be used for payload encryption. Defaults to ""JKS"" if not set | | String | *camel.component.netty.configuration.key-store-resource* | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with ""classpath:"", ""file:"", or ""http:"" to load the resource from different systems. | | String | *camel.component.netty.configuration.lazy-channel-creation* | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | Boolean | *camel.component.netty.configuration.native-transport* | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | Boolean | *camel.component.netty.configuration.need-client-auth* | Configures whether the server needs client authentication when using SSL. | false | Boolean | *camel.component.netty.configuration.netty-server-bootstrap-factory* | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrap Factory | *camel.component.netty.configuration.network-interface* | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *camel.component.netty.configuration.no-reply-log-level* | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. | | LoggingLevel | *camel.component.netty.configuration.options* | Allows to configure additional netty options using ""option."" as prefix. For example ""option.child.keepAlive=false"" to set the netty option ""child.keepAlive=false"". See the Netty documentation for possible options that can be used. | | Map | *camel.component.netty.configuration.passphrase* | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *camel.component.netty.configuration.port* | The host port number | | Integer | *camel.component.netty.configuration.producer-pool-enabled* | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement {@link NettyCamelStateCorrelationManager} as correlation manager and configure it via the correlationManager option.

See also the correlationManager option for more details. | true | Boolean | *camel.component.netty.configuration.producer-pool-max-active* | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | Integer | *camel.component.netty.configuration.producer-pool-max-idle* | Sets the cap on the number of ""idle"" instances in the pool. | 100 | Integer | *camel.component.netty.configuration.producer-pool-min-evictable-idle* | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | Long | *camel.component.netty.configuration.producer-pool-min-idle* | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | Integer | *camel.component.netty.configuration.protocol* | The protocol to use which can be tcp or udp. | | String | *camel.component.netty.configuration.receive-buffer-size* | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | Integer | *camel.component.netty.configuration.receive-buffer-size-predictor* | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | Integer | *camel.component.netty.configuration.reconnect* | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | Boolean | *camel.component.netty.configuration.reconnect-interval* | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | Integer | *camel.component.netty.configuration.request-timeout* | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | Long | *camel.component.netty.configuration.reuse-address* | Setting to facilitate socket multiplexing | true | Boolean | *camel.component.netty.configuration.reuse-channel* | This option allows producers and consumers (in client mode) to reuse the same Netty {@link Channel} for the lifecycle of processing the {@link Exchange}. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the {@link Exchange} is done; or disconnected if the disconnect option is set to true.

The reused {@link Channel} is stored on the {@link Exchange} as an exchange property with the key {@link NettyConstants#NETTY_CHANNEL} which allows you to obtain the channel during routing and use it as well. | false | Boolean | *camel.component.netty.configuration.security-provider* | Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. | | String | *camel.component.netty.configuration.send-buffer-size* | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | Integer | *camel.component.netty.configuration.server-closed-channel-exception-caught-log-level* | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. | | LoggingLevel | *camel.component.netty.configuration.server-exception-caught-log-level* | If the server (NettyConsumer) catches an exception then its logged using this logging level. | | LoggingLevel | *camel.component.netty.configuration.server-initializer-factory* | To use a custom ServerInitializerFactory | | ServerInitializer Factory | *camel.component.netty.configuration.ssl* | Setting to specify whether SSL encryption is applied to this endpoint | false | Boolean | *camel.component.netty.configuration.ssl-client-cert-headers* | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | Boolean | *camel.component.netty.configuration.ssl-context-parameters* | To configure security using SSLContextParameters | | SSLContextParameters | *camel.component.netty.configuration.ssl-handler* | Reference to a class that could be used to return an SSL Handler | | SslHandler | *camel.component.netty.configuration.sync* | Setting to set endpoint as one-way or request-response | true | Boolean | *camel.component.netty.configuration.tcp-no-delay* | Setting to improve TCP protocol performance | true | Boolean | *camel.component.netty.configuration.textline* | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP. | false | Boolean | *camel.component.netty.configuration.transfer-exchange* | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | Boolean | *camel.component.netty.configuration.trust-store-resource* | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with ""classpath:"", ""file:"", or ""http:"" to load the resource from different systems. | | String | *camel.component.netty.configuration.udp-byte-array-codec* | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | Boolean | *camel.component.netty.configuration.udp-connectionless-sending* | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | Boolean | *camel.component.netty.configuration.use-byte-buf* | If the useByteBuf is true, netty producer will turn the message body into {@link ByteBuf} before sending it out. | false | Boolean | *camel.component.netty.configuration.using-executor-service* | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | Boolean | *camel.component.netty.configuration.worker-count* | When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads x 2. User can use this operation to override the default workerCount from Netty. | | Integer | *camel.component.netty.configuration.worker-group* | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *camel.component.netty.enabled* | Whether to enable auto configuration of the netty component. This is enabled by default. | | Boolean | *camel.component.netty.executor-service* | To use the given EventExecutorGroup. The option is a io.netty.util.concurrent.EventExecutorGroup type. | | String | *camel.component.netty.maximum-pool-size* | The thread pool size for the EventExecutorGroup if its in use. The default value is 16. | 16 | Integer | *camel.component.netty.ssl-context-parameters* | To configure security using SSLContextParameters. The option is a org.apache.camel.support.jsse.SSLContextParameters type. | | String | *camel.component.netty.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters. | false | Boolean | *camel.component.netty.configuration.client-pipeline-factory* | *Deprecated* | | ClientInitializer Factory | *camel.component.netty.configuration.key-store-file* | *Deprecated* Client side certificate keystore to be used for encryption | | File | *camel.component.netty.configuration.server-pipeline-factory* | *Deprecated* | | ServerInitializer Factory | *camel.component.netty.configuration.trust-store-file* | *Deprecated* Server side certificate keystore to be used for encryption | | File |=== // spring-boot-auto-configure options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== NOTE: Read below about using non shareable encoders/decoders. === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); poetry.setPoet(""Dr. Sarojini Naidu""); exchange.getOut().setBody(poetry); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSL/TLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. TIP: The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. NOTE: Read further above about using non shareable encoders/decoders. The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- TIP: For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. NOTE: We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. ",12488,False,2298.027364590081,median "//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2018 Pivotal, Inc. // // @filename: // CFilterCardinalityTest.cpp // // @doc: // Test for filter cardinality estimation //--------------------------------------------------------------------------- #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #include #include ""gpos/io/COstreamString.h"" #include ""gpos/string/CWStringDynamic.h"" #include ""naucrates/statistics/CStatisticsUtils.h"" #include ""naucrates/statistics/CFilterStatsProcessor.h"" #include ""naucrates/dxl/CDXLUtils.h"" #include ""unittest/base.h"" #include ""unittest/dxl/statistics/CCardinalityTestUtils.h"" #include ""unittest/dxl/statistics/CStatisticsTest.h"" #include ""unittest/dxl/statistics/CFilterCardinalityTest.h"" #include ""unittest/gpopt/CTestUtils.h"" using namespace gpopt; // DXL files const CHAR * szInputDXLFileName = ""../data/dxl/statistics/Basic-Statistics-Input.xml""; const CHAR * szOutputDXLFileName = ""../data/dxl/statistics/Basic-Statistics-Output.xml""; const CTestUtils::STestCase rgtcStatistics[] = { {""../data/dxl/statistics/Numeric-Input.xml"", ""../data/dxl/statistics/Numeric-Output-LT-MinBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input.xml"", ""../data/dxl/statistics/Numeric-Output-LTE-MinBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input.xml"", ""../data/dxl/statistics/Numeric-Output-E-MinBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input.xml"", ""../data/dxl/statistics/Numeric-Output-GT-MaxBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input.xml"", ""../data/dxl/statistics/Numeric-Output-GTE-MaxBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input.xml"", ""../data/dxl/statistics/Numeric-Output-E-MaxBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input2.xml"", ""../data/dxl/statistics/Numeric-Output-2-LT-MinBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input2.xml"", ""../data/dxl/statistics/Numeric-Output-2-LTE-MinBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input2.xml"", ""../data/dxl/statistics/Numeric-Output-2-E-MinBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input2.xml"", ""../data/dxl/statistics/Numeric-Output-2-GT-MinBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input2.xml"", ""../data/dxl/statistics/Numeric-Output-2-GTE-MinBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input2.xml"", ""../data/dxl/statistics/Numeric-Output-2-LT-MaxBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input2.xml"", ""../data/dxl/statistics/Numeric-Output-2-LTE-MaxBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input2.xml"", ""../data/dxl/statistics/Numeric-Output-2-GT-MaxBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input2.xml"", ""../data/dxl/statistics/Numeric-Output-2-GTE-MaxBoundary.xml""}, {""../data/dxl/statistics/Numeric-Input2.xml"", ""../data/dxl/statistics/Numeric-Output-2-E-MaxBoundary.xml""}, }; // unittest for statistics objects GPOS_RESULT CFilterCardinalityTest::EresUnittest() { // tests that use shared optimization context CUnittest rgutSharedOptCtxt[] = { GPOS_UNITTEST_FUNC(CFilterCardinalityTest::EresUnittest_CStatisticsBasicsFromDXLNumeric), GPOS_UNITTEST_FUNC(CFilterCardinalityTest::EresUnittest_CStatisticsFilter), GPOS_UNITTEST_FUNC(CFilterCardinalityTest::EresUnittest_CStatisticsFilterArrayCmpAny), GPOS_UNITTEST_FUNC(CFilterCardinalityTest::EresUnittest_CStatisticsFilterConj), GPOS_UNITTEST_FUNC(CFilterCardinalityTest::EresUnittest_CStatisticsFilterDisj), GPOS_UNITTEST_FUNC(CFilterCardinalityTest::EresUnittest_CStatisticsNestedPred), GPOS_UNITTEST_FUNC(CFilterCardinalityTest::EresUnittest_CStatisticsBasicsFromDXL), GPOS_UNITTEST_FUNC(CFilterCardinalityTest::EresUnittest_CStatisticsAccumulateCard) }; CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, NULL /* pceeval */, CTestUtils::GetCostModel(mp)); return CUnittest::EresExecute(rgutSharedOptCtxt, GPOS_ARRAY_SIZE(rgutSharedOptCtxt)); } // reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. GPOS_RESULT CFilterCardinalityTest::EresUnittest_CStatistics ( SStatsFilterSTestCase rgstatsdisjtc[], ULONG ulTestCases ) { // create memory pool CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); CWStringDynamic str(mp); COstreamString oss(&str); CMDAccessor *md_accessor = COptCtxt::PoctxtFromTLS()->Pmda(); for (ULONG ul = 0; ul < ulTestCases; ul++) { SStatsFilterSTestCase elem = rgstatsdisjtc[ul]; // read input/output DXL file CHAR *szDXLInput = CDXLUtils::Read(mp, elem.m_szInputFile); CHAR *szDXLOutput = CDXLUtils::Read(mp, elem.m_szOutputFile); GPOS_CHECK_ABORT; // parse the statistics objects CDXLStatsDerivedRelationArray *dxl_derived_rel_stats_array = CDXLUtils::ParseDXLToStatsDerivedRelArray(mp, szDXLInput, NULL); CStatisticsArray *pdrgpstatBefore = CDXLUtils::ParseDXLToOptimizerStatisticObjArray(mp, md_accessor, dxl_derived_rel_stats_array); dxl_derived_rel_stats_array->Release(); GPOS_ASSERT(NULL != pdrgpstatBefore); GPOS_CHECK_ABORT; // generate the disjunctive predicate FnPstatspredDisj *pf = elem.m_pf; GPOS_ASSERT(NULL != pf); CStatsPred *disjunctive_pred_stats = pf(mp); GPOS_RESULT eres = EresUnittest_CStatisticsCompare ( mp, md_accessor, pdrgpstatBefore, disjunctive_pred_stats, szDXLOutput ); // clean up pdrgpstatBefore->Release(); disjunctive_pred_stats->Release(); GPOS_DELETE_ARRAY(szDXLInput); GPOS_DELETE_ARRAY(szDXLOutput); if (GPOS_FAILED == eres) { return eres; } } return GPOS_OK; } // reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. GPOS_RESULT CFilterCardinalityTest::EresUnittest_CStatisticsFilter() { SStatsFilterSTestCase rgstatstc[] = { {""../data/dxl/statistics/Select-Statistics-Input-Null-Bucket.xml"", ""../data/dxl/statistics/Select-Statistics-Output-Null-Bucket.xml"", PstatspredNullableCols}, {""../data/dxl/statistics/Select-Statistics-Input-Null-Bucket.xml"", ""../data/dxl/statistics/Select-Statistics-Output-Null-Constant.xml"", PstatspredWithNullConstant}, {""../data/dxl/statistics/Select-Statistics-Input-Null-Bucket.xml"", ""../data/dxl/statistics/Select-Statistics-Output-NotNull-Constant.xml"", PstatspredNotNull}, }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatstc); return EresUnittest_CStatistics(rgstatstc, ulTestCases); } // create a filter on a column with null values CStatsPred * CFilterCardinalityTest::PstatspredNullableCols ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspred = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspred->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptLEq, CTestUtils::PpointInt4(mp, 1))); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspred); } // create a point filter where the constant is null CStatsPred * CFilterCardinalityTest::PstatspredWithNullConstant ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspred = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspred->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4NullVal(mp))); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspred); } // create an 'is not null' point filter CStatsPred * CFilterCardinalityTest::PstatspredNotNull ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspred = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspred->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptNEq, CTestUtils::PpointInt4NullVal(mp))); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspred); } // testing ArryCmpAny predicates GPOS_RESULT CFilterCardinalityTest::EresUnittest_CStatisticsFilterArrayCmpAny() { SStatsFilterSTestCase rgstatsdisjtc[] = { { ""../data/dxl/statistics/ArrayCmpAny-Input-1.xml"", ""../data/dxl/statistics/ArrayCmpAny-Output-1.xml"", PstatspredArrayCmpAnySimple }, { ""../data/dxl/statistics/ArrayCmpAny-Input-1.xml"", ""../data/dxl/statistics/ArrayCmpAny-Output-1.xml"", PstatspredArrayCmpAnyDuplicate } }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatsdisjtc); return EresUnittest_CStatistics(rgstatsdisjtc, ulTestCases); } // create a 'col IN (...)' filter without duplicates CStatsPred * CFilterCardinalityTest::PstatspredArrayCmpAnySimple ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspred = GPOS_NEW(mp) CStatsPredPtrArry(mp); CPointArray *arr = GPOS_NEW(mp) CPointArray(mp); arr->Append(CTestUtils::PpointInt4(mp, 1)); arr->Append(CTestUtils::PpointInt4(mp, 2)); arr->Append(CTestUtils::PpointInt4(mp, 15)); pdrgpstatspred->Append(GPOS_NEW(mp) CStatsPredArrayCmp(1, CStatsPred::EstatscmptEq, arr)); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspred); } // create a 'col IN (...)' filter with duplicates (unsorted) CStatsPred * CFilterCardinalityTest::PstatspredArrayCmpAnyDuplicate ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspred = GPOS_NEW(mp) CStatsPredPtrArry(mp); CPointArray *arr = GPOS_NEW(mp) CPointArray(mp); arr->Append(CTestUtils::PpointInt4(mp, 1)); arr->Append(CTestUtils::PpointInt4(mp, 1)); arr->Append(CTestUtils::PpointInt4(mp, 15)); arr->Append(CTestUtils::PpointInt4(mp, 2)); arr->Append(CTestUtils::PpointInt4(mp, 1)); arr->Append(CTestUtils::PpointInt4(mp, 1)); arr->Append(CTestUtils::PpointInt4(mp, 2)); arr->Append(CTestUtils::PpointInt4(mp, 15)); arr->Append(CTestUtils::PpointInt4(mp, 15)); arr->Append(CTestUtils::PpointInt4(mp, 15)); pdrgpstatspred->Append(GPOS_NEW(mp) CStatsPredArrayCmp(1, CStatsPred::EstatscmptEq, arr)); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspred); } // reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. GPOS_RESULT CFilterCardinalityTest::EresUnittest_CStatisticsFilterDisj() { SStatsFilterSTestCase rgstatsdisjtc[] = { {""../data/dxl/statistics/Disj-Input-1.xml"", ""../data/dxl/statistics/Disj-Output-1.xml"", PstatspredDisj1}, {""../data/dxl/statistics/Disj-Input-1.xml"", ""../data/dxl/statistics/Disj-Output-1.xml"", PstatspredDisj2}, {""../data/dxl/statistics/Disj-Input-1.xml"", ""../data/dxl/statistics/Disj-Output-1.xml"", PstatspredDisj3}, {""../data/dxl/statistics/Disj-Input-2.xml"", ""../data/dxl/statistics/Disj-Output-2-1.xml"", PstatspredDisj4}, {""../data/dxl/statistics/Disj-Input-2.xml"", ""../data/dxl/statistics/Disj-Output-2-2.xml"", PstatspredDisj5}, {""../data/dxl/statistics/Disj-Input-2.xml"", ""../data/dxl/statistics/Disj-Output-2-3.xml"", PstatspredDisj6}, {""../data/dxl/statistics/Disj-Input-2.xml"", ""../data/dxl/statistics/Disj-Output-2-4.xml"", PstatspredDisj7}, {""../data/dxl/statistics/NestedPred-Input-10.xml"", ""../data/dxl/statistics/Disj-Output-8.xml"", PstatspredDisj8}, {""../data/dxl/statistics/Disj-Input-2.xml"", ""../data/dxl/statistics/Disj-Output-2-5.xml"", PstatspredDisj9}, }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatsdisjtc); return EresUnittest_CStatistics(rgstatsdisjtc, ulTestCases); } // create an or filter (no duplicate) CStatsPred * CFilterCardinalityTest::PstatspredDisj1 ( CMemoryPool *mp ) { // predicate col_1 in (13, 25, 47, 49); INT rgiVal[] = {13, 25, 47, 49}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 1, CStatsPred::EstatscmptEq, rgiVal, ulVals); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create an or filter (one duplicate constant) CStatsPred * CFilterCardinalityTest::PstatspredDisj2 ( CMemoryPool *mp ) { // predicate col_1 in (13, 13, 25, 47, 49); INT rgiVal[] = {13, 13, 25, 47, 49}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 1, CStatsPred::EstatscmptEq, rgiVal, ulVals); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create an or filter (multiple duplicate constants) CStatsPred * CFilterCardinalityTest::PstatspredDisj3 ( CMemoryPool *mp ) { // predicate col_1 in (13, 25, 47, 47, 47, 49, 13); INT rgiVal[] = {13, 25, 47, 47, 47, 49, 13}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 1, CStatsPred::EstatscmptEq, rgiVal, ulVals); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create an or filter CStatsPred * CFilterCardinalityTest::PstatspredDisj4 ( CMemoryPool *mp ) { // the predicate is (x <= 5 or x <= 10 or x <= 13) (domain [0 -- 20]) INT rgiVal[] = {5, 10, 13}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 1, CStatsPred::EstatscmptLEq, rgiVal, ulVals); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create an or filter (multiple LEQ) CStatsPred * CFilterCardinalityTest::PstatspredDisj5 ( CMemoryPool *mp ) { // the predicate is (x >= 5 or x >= 13) (domain [0 -- 20]) INT rgiVal[] = {5, 13}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 1, CStatsPred::EstatscmptGEq, rgiVal, ulVals); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create an or filter CStatsPred * CFilterCardinalityTest::PstatspredDisj6 ( CMemoryPool *mp ) { // the predicate is (x > 10 or x < 5) (domain [0 -- 20]) CStatsPredPtrArry *pdrgpstatspredDisj = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptG, CTestUtils::PpointInt4(mp, 10))); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptL, CTestUtils::PpointInt4(mp, 5))); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create an or filter CStatsPred * CFilterCardinalityTest::PstatspredDisj7 ( CMemoryPool *mp ) { // the predicate is (x <= 15 or x >= 5 or x > = 10) (domain [0 -- 20]) INT rgiVal[] = {5, 10}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 1, CStatsPred::EstatscmptGEq, rgiVal, ulVals); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptLEq, CTestUtils::PpointInt4(mp, 15))); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create disjunctive predicate on same columns CStatsPred * CFilterCardinalityTest::PstatspredDisj8 ( CMemoryPool *mp ) { // predicate is b = 2001 OR b == 2002 INT rgiVal[] = {2001, 2002}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 61, CStatsPred::EstatscmptEq, rgiVal, ulVals); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create an or filter (multiple LEQ) CStatsPred * CFilterCardinalityTest::PstatspredDisj9 ( CMemoryPool *mp ) { // the predicate is (x <= 3 or x <= 10) (domain [0 -- 20]) INT rgiVal[] = {3, 10}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 1, CStatsPred::EstatscmptLEq, rgiVal, ulVals); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. GPOS_RESULT CFilterCardinalityTest::EresUnittest_CStatisticsFilterConj() { SStatsFilterSTestCase rgstatsdisjtc[] = { {""../data/dxl/statistics/NestedPred-Input-9.xml"", ""../data/dxl/statistics/NestedPred-Output-9.xml"", PstatspredConj}, }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatsdisjtc); return EresUnittest_CStatistics(rgstatsdisjtc, ulTestCases); } // create conjunctive predicate CStatsPred * CFilterCardinalityTest::PstatspredConj ( CMemoryPool *mp ) { CWStringDynamic *pstrW = GPOS_NEW(mp) CWStringDynamic(mp, GPOS_WSZ_LIT(""AAAABXc="")); // predicate is a == 'w' AND b == 2001 AND c > 0 CStatsPredPtrArry *pdrgpstatspredConj3 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredConj3->Append(GPOS_NEW(mp) CStatsPredPoint(594, CStatsPred::EstatscmptEq, CCardinalityTestUtils::PpointGeneric(mp, GPDB_TEXT, pstrW, 160621100))); pdrgpstatspredConj3->Append(GPOS_NEW(mp) CStatsPredPoint(592, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2001))); pdrgpstatspredConj3->Append(GPOS_NEW(mp) CStatsPredPoint(593, CStatsPred::EstatscmptG, CTestUtils::PpointInt4(mp, 0))); GPOS_DELETE(pstrW); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj3); } // reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. GPOS_RESULT CFilterCardinalityTest::EresUnittest_CStatisticsNestedPred() { SStatsFilterSTestCase rgstatsdisjtc[] = { {""../data/dxl/statistics/NestedPred-Input-1.xml"", ""../data/dxl/statistics/NestedPred-Output-1.xml"", PstatspredNestedPredDiffCol1}, {""../data/dxl/statistics/NestedPred-Input-1.xml"", ""../data/dxl/statistics/NestedPred-Output-1.xml"", PstatspredNestedPredDiffCol2}, {""../data/dxl/statistics/NestedPred-Input-2.xml"", ""../data/dxl/statistics/NestedPred-Output-2.xml"", PstatspredNestedPredCommonCol1}, {""../data/dxl/statistics/NestedPred-Input-1.xml"", ""../data/dxl/statistics/NestedPred-Output-3.xml"", PstatspredNestedSharedCol}, {""../data/dxl/statistics/NestedPred-Input-3.xml"", ""../data/dxl/statistics/NestedPred-Output-4.xml"", PstatspredDisjOverConjSameCol1}, {""../data/dxl/statistics/NestedPred-Input-3.xml"", ""../data/dxl/statistics/NestedPred-Input-3.xml"", PstatspredDisjOverConjSameCol2}, {""../data/dxl/statistics/NestedPred-Input-1.xml"", ""../data/dxl/statistics/NestedPred-Output-5.xml"", PstatspredDisjOverConjDifferentCol1}, {""../data/dxl/statistics/NestedPred-Input-1.xml"", ""../data/dxl/statistics/NestedPred-Output-6.xml"", PstatspredDisjOverConjMultipleIdenticalCols}, {""../data/dxl/statistics/NestedPred-Input-2.xml"", ""../data/dxl/statistics/NestedPred-Output-7.xml"", PstatspredNestedPredCommonCol2}, {""../data/dxl/statistics/NestedPred-Input-8.xml"", ""../data/dxl/statistics/NestedPred-Output-8.xml"", PstatspredDisjOverConjSameCol3}, {""../data/dxl/statistics/NestedPred-Input-10.xml"", ""../data/dxl/statistics/NestedPred-Output-10.xml"", PstatspredDisjOverConjSameCol4}, }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatsdisjtc); return EresUnittest_CStatistics(rgstatsdisjtc, ulTestCases); } // Create nested AND and OR predicates where the AND and OR predicates // are on different columns CStatsPred * CFilterCardinalityTest::PstatspredNestedPredDiffCol1 ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspredConj = GPOS_NEW(mp) CStatsPredPtrArry(mp); // predicate col_1 <> 3 pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptNEq, CTestUtils::PpointInt4(mp, 3))); // predicate col_2 in (15, 20, 22, 24, 31, 39, 42, 46); INT rgiVal[] = {15, 20, 22, 24, 31, 39, 42, 46}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 2, CStatsPred::EstatscmptEq, rgiVal, ulVals); CStatsPredDisj *disjunctive_pred_stats = GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); pdrgpstatspredConj->Append(disjunctive_pred_stats); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj); } // create nested AND and OR predicates where the AND and OR predicates // are on different columns. note: the order of the predicates in // reversed as in PstatspredNestedPredDiffCol1 CStatsPred * CFilterCardinalityTest::PstatspredNestedPredDiffCol2 ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspredConj = GPOS_NEW(mp) CStatsPredPtrArry(mp); // predicate col_2 in (15, 20, 22, 24, 31, 39, 42, 46); INT rgiVal[] = {15, 20, 22, 24, 31, 39, 42, 46}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 2, CStatsPred::EstatscmptEq, rgiVal, ulVals); CStatsPredDisj *disjunctive_pred_stats = GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); pdrgpstatspredConj->Append(disjunctive_pred_stats); // predicate col_1 <> 3 pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptNEq, CTestUtils::PpointInt4(mp, 3))); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj); } // create nested AND and OR predicates where the AND and OR predicates // are on the same columns CStatsPred * CFilterCardinalityTest::PstatspredNestedPredCommonCol1 ( CMemoryPool *mp ) { // predicate is col_2 in (39, 31, 24, 22, 46, 20, 42, 15) AND col_2 == 2 CStatsPredPtrArry *pdrgpstatspredConj = GPOS_NEW(mp) CStatsPredPtrArry(mp); // predicate col_2 in (15, 20, 22, 24, 31, 39, 42, 46); INT rgiVal[] = {15, 20, 22, 24, 31, 39, 42, 46}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 2, CStatsPred::EstatscmptEq, rgiVal, ulVals); CStatsPredDisj *disjunctive_pred_stats = GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); pdrgpstatspredConj->Append(disjunctive_pred_stats); // predicate col_2 == 2 pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2))); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj); } // create nested AND and OR predicates where the AND and OR predicates // are on the same columns CStatsPred * CFilterCardinalityTest::PstatspredNestedPredCommonCol2 ( CMemoryPool *mp ) { // predicate is col_2 in (2, 39, 31, 24, 22, 46, 20, 42, 15) AND col_2 == 2 CStatsPredPtrArry *pdrgpstatspredConj = GPOS_NEW(mp) CStatsPredPtrArry(mp); // IN predicate: col_2 in (2, 39, 31, 24, 22, 46, 20, 42, 15); INT rgiVal[] = {2, 15, 20, 22, 24, 31, 39, 42, 46}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 2, CStatsPred::EstatscmptEq, rgiVal, ulVals); CStatsPredDisj *disjunctive_pred_stats = GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); pdrgpstatspredConj->Append(disjunctive_pred_stats); // predicate col_2 == 2 pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2))); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj); } // create nested AND and OR predicates where the AND and OR predicates // share common columns CStatsPred * CFilterCardinalityTest::PstatspredNestedSharedCol ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspredConj = GPOS_NEW(mp) CStatsPredPtrArry(mp); // predicate col_1 <> 3 pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptNEq, CTestUtils::PpointInt4(mp, 3))); // predicate col_2 in (15, 20, 22, 24, 31, 39, 42, 46) OR (col_1 == 4)); INT rgiVal[] = {15, 20, 22, 24, 31, 39, 42, 46}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); CStatsPredPtrArry *pdrgpstatspredDisj = PdrgpstatspredInteger(mp, 2, CStatsPred::EstatscmptEq, rgiVal, ulVals); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 4))); CStatsPredDisj *disjunctive_pred_stats = GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); pdrgpstatspredConj->Append(disjunctive_pred_stats); return GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj); } // create nested AND and OR predicates where the AND and OR predicates share common columns CStatsPred * CFilterCardinalityTest::PstatspredDisjOverConjSameCol1 ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspredConj = GPOS_NEW(mp) CStatsPredPtrArry(mp); // predicate col_1 = 3 AND col_1 >=3 pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 3))); pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptGEq, CTestUtils::PpointInt4(mp, 3))); CStatsPredConj *conjunctive_pred_stats = GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj); // predicate (col_1 = 1); CStatsPredPtrArry *pdrgpstatspredDisj = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 1))); pdrgpstatspredDisj->Append(conjunctive_pred_stats); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create nested AND and OR predicates where the AND and OR predicates share common columns CStatsPred * CFilterCardinalityTest::PstatspredDisjOverConjSameCol2 ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspredConj = GPOS_NEW(mp) CStatsPredPtrArry(mp); // predicate col_1 <= 5 AND col_1 >=1 pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptLEq, CTestUtils::PpointInt4(mp, 5))); pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptGEq, CTestUtils::PpointInt4(mp, 1))); CStatsPredConj *conjunctive_pred_stats = GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj); // predicate (col_1 = 1); CStatsPredPtrArry *pdrgpstatspredDisj = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 1))); pdrgpstatspredDisj->Append(conjunctive_pred_stats); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create disjunctive predicate over conjunctions on same columns CStatsPred * CFilterCardinalityTest::PstatspredDisjOverConjSameCol3 ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspredDisj = GPOS_NEW(mp) CStatsPredPtrArry(mp); CWStringDynamic *pstrS = GPOS_NEW(mp) CWStringDynamic(mp, GPOS_WSZ_LIT(""AAAABXM="")); CWStringDynamic *pstrW = GPOS_NEW(mp) CWStringDynamic(mp, GPOS_WSZ_LIT(""AAAABXc="")); // predicate is a == 's' AND b == 2001 CStatsPredPtrArry *pdrgpstatspredConj1 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredConj1->Append(GPOS_NEW(mp) CStatsPredPoint(142, CStatsPred::EstatscmptEq, CCardinalityTestUtils::PpointGeneric(mp, GPDB_TEXT, pstrS, 160588332))); pdrgpstatspredConj1->Append(GPOS_NEW(mp) CStatsPredPoint(113, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2001))); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj1)); // predicate is a == 's' AND b == 2002 CStatsPredPtrArry *pdrgpstatspredConj2 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredConj2->Append(GPOS_NEW(mp) CStatsPredPoint(142, CStatsPred::EstatscmptEq, CCardinalityTestUtils::PpointGeneric(mp, GPDB_TEXT, pstrS, 160588332))); pdrgpstatspredConj2->Append(GPOS_NEW(mp) CStatsPredPoint(113, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2002))); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj2)); // predicate is a == 'w' AND b == 2001 CStatsPredPtrArry *pdrgpstatspredConj3 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredConj3->Append(GPOS_NEW(mp) CStatsPredPoint(142, CStatsPred::EstatscmptEq, CCardinalityTestUtils::PpointGeneric(mp, GPDB_TEXT, pstrW, 160621100))); pdrgpstatspredConj3->Append(GPOS_NEW(mp) CStatsPredPoint(113, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2001))); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj3)); // predicate is a == 'w' AND b == 2002 CStatsPredPtrArry *pdrgpstatspredConj4 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredConj4->Append(GPOS_NEW(mp) CStatsPredPoint(142, CStatsPred::EstatscmptEq, CCardinalityTestUtils::PpointGeneric(mp, GPDB_TEXT, pstrW, 160621100))); pdrgpstatspredConj4->Append(GPOS_NEW(mp) CStatsPredPoint(113, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2002))); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj4)); GPOS_DELETE(pstrS); GPOS_DELETE(pstrW); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create disjunctive predicate over conjunctions on same columns CStatsPred * CFilterCardinalityTest::PstatspredDisjOverConjSameCol4 ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspredDisj = GPOS_NEW(mp) CStatsPredPtrArry(mp); CWStringDynamic *pstrS = GPOS_NEW(mp) CWStringDynamic(mp, GPOS_WSZ_LIT(""AAAABXM="")); CWStringDynamic *pstrW = GPOS_NEW(mp) CWStringDynamic(mp, GPOS_WSZ_LIT(""AAAABXc="")); // predicate is a == 's' AND b == 2001 AND c > 0 CStatsPredPtrArry *pdrgpstatspredConj1 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredConj1->Append(GPOS_NEW(mp) CStatsPredPoint(91, CStatsPred::EstatscmptEq, CCardinalityTestUtils::PpointGeneric(mp, GPDB_TEXT, pstrS, 160588332))); pdrgpstatspredConj1->Append(GPOS_NEW(mp) CStatsPredPoint(61, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2001))); pdrgpstatspredConj1->Append(GPOS_NEW(mp) CStatsPredPoint(90, CStatsPred::EstatscmptG, CTestUtils::PpointInt4(mp, 0))); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj1)); // predicate is a == 's' AND b == 2002 CStatsPredPtrArry *pdrgpstatspredConj2 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredConj2->Append(GPOS_NEW(mp) CStatsPredPoint(91, CStatsPred::EstatscmptEq, CCardinalityTestUtils::PpointGeneric(mp, GPDB_TEXT, pstrS, 160588332))); pdrgpstatspredConj2->Append(GPOS_NEW(mp) CStatsPredPoint(61, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2002))); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj2)); // predicate is a == 'w' AND b == 2001 AND c > 0 CStatsPredPtrArry *pdrgpstatspredConj3 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredConj3->Append(GPOS_NEW(mp) CStatsPredPoint(91, CStatsPred::EstatscmptEq, CCardinalityTestUtils::PpointGeneric(mp, GPDB_TEXT, pstrW, 160621100))); pdrgpstatspredConj3->Append(GPOS_NEW(mp) CStatsPredPoint(61, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2001))); pdrgpstatspredConj1->Append(GPOS_NEW(mp) CStatsPredPoint(90, CStatsPred::EstatscmptG, CTestUtils::PpointInt4(mp, 0))); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj3)); // predicate is a == 'w' AND b == 2002 CStatsPredPtrArry *pdrgpstatspredConj4 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredConj4->Append(GPOS_NEW(mp) CStatsPredPoint(91, CStatsPred::EstatscmptEq, CCardinalityTestUtils::PpointGeneric(mp, GPDB_TEXT, pstrW, 160621100))); pdrgpstatspredConj4->Append(GPOS_NEW(mp) CStatsPredPoint(61, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2002))); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj4)); GPOS_DELETE(pstrS); GPOS_DELETE(pstrW); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create nested AND and OR predicates where the AND and OR predicates share common columns CStatsPred * CFilterCardinalityTest::PstatspredDisjOverConjDifferentCol1 ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspredConj = GPOS_NEW(mp) CStatsPredPtrArry(mp); // predicate col_1 = 3 AND col_2 >=3 pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 3))); pdrgpstatspredConj->Append(GPOS_NEW(mp) CStatsPredPoint(2, CStatsPred::EstatscmptGEq, CTestUtils::PpointInt4(mp, 3))); CStatsPredConj *conjunctive_pred_stats = GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj); // predicate (col_1 = 1); CStatsPredPtrArry *pdrgpstatspredDisj = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredDisj->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 1))); pdrgpstatspredDisj->Append(conjunctive_pred_stats); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // create nested AND and OR predicates where the AND and OR predicates CStatsPred * CFilterCardinalityTest::PstatspredDisjOverConjMultipleIdenticalCols ( CMemoryPool *mp ) { CStatsPredPtrArry *pdrgpstatspredConj1 = GPOS_NEW(mp) CStatsPredPtrArry(mp); // predicate col_1 = 1 AND col_2 = 1 pdrgpstatspredConj1->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 1))); pdrgpstatspredConj1->Append(GPOS_NEW(mp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 1))); CStatsPredConj *pstatspredConj1 = GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj1); CStatsPredPtrArry *pdrgpstatspredConj2 = GPOS_NEW(mp) CStatsPredPtrArry(mp); // predicate col_1 = 2 AND col_2 = 2 pdrgpstatspredConj2->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2))); pdrgpstatspredConj2->Append(GPOS_NEW(mp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 2))); CStatsPredConj *pstatspredConj2 = GPOS_NEW(mp) CStatsPredConj(pdrgpstatspredConj2); CStatsPredPtrArry *pdrgpstatspredDisj = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspredDisj->Append(pstatspredConj1); pdrgpstatspredDisj->Append(pstatspredConj2); return GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspredDisj); } // reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. GPOS_RESULT CFilterCardinalityTest::EresUnittest_CStatisticsBasicsFromDXLNumeric() { // create memory pool CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); SStatsCmpValElem rgStatsCmpValElem[] = { {CStatsPred::EstatscmptL, GPOS_WSZ_LIT(""AAAACgAAAgABAA==""), CDouble(1.0)}, {CStatsPred::EstatscmptLEq, GPOS_WSZ_LIT(""AAAACgAAAgABAA==""), CDouble(1.0)}, {CStatsPred::EstatscmptEq, GPOS_WSZ_LIT(""AAAACgAAAgABAA==""), CDouble(1.0)}, {CStatsPred::EstatscmptG, GPOS_WSZ_LIT(""AAAACgAAAgAyAA==""), CDouble(50.0)}, {CStatsPred::EstatscmptGEq, GPOS_WSZ_LIT(""AAAACgAAAgAyAA==""), CDouble(50.0)}, {CStatsPred::EstatscmptEq, GPOS_WSZ_LIT(""AAAACgAAAgAyAA==""), CDouble(50.0)}, {CStatsPred::EstatscmptL, GPOS_WSZ_LIT(""AAAACgAAAgABAA==""), CDouble(1.0)}, {CStatsPred::EstatscmptLEq, GPOS_WSZ_LIT(""AAAACgAAAgABAA==""), CDouble(1.0)}, {CStatsPred::EstatscmptEq, GPOS_WSZ_LIT(""AAAACgAAAgABAA==""), CDouble(1.0)}, {CStatsPred::EstatscmptG, GPOS_WSZ_LIT(""AAAACgAAAgABAA==""), CDouble(1.0)}, {CStatsPred::EstatscmptGEq, GPOS_WSZ_LIT(""AAAACgAAAgABAA==""), CDouble(1.0)}, {CStatsPred::EstatscmptL, GPOS_WSZ_LIT(""AAAACgAAAgAyAA==""), CDouble(50.0)}, {CStatsPred::EstatscmptLEq, GPOS_WSZ_LIT(""AAAACgAAAgAyAA==""), CDouble(50.0)}, {CStatsPred::EstatscmptG, GPOS_WSZ_LIT(""AAAACgAAAgAyAA==""), CDouble(50.0)}, {CStatsPred::EstatscmptGEq, GPOS_WSZ_LIT(""AAAACgAAAgAyAA==""), CDouble(50.0)}, {CStatsPred::EstatscmptEq, GPOS_WSZ_LIT(""AAAACgAAAgAyAA==""), CDouble(50.0)}, }; const ULONG length = GPOS_ARRAY_SIZE(rgStatsCmpValElem); GPOS_ASSERT(length == GPOS_ARRAY_SIZE(rgtcStatistics)); for (ULONG ul = 0; ul < length; ul++) { // read input DXL file CHAR *szDXLInput = CDXLUtils::Read(mp, rgtcStatistics[ul].szInputFile); // read output DXL file CHAR *szDXLOutput = CDXLUtils::Read(mp, rgtcStatistics[ul].szOutputFile); GPOS_CHECK_ABORT; CMDAccessor *md_accessor = COptCtxt::PoctxtFromTLS()->Pmda(); // parse the statistics objects CDXLStatsDerivedRelationArray *dxl_derived_rel_stats_array = CDXLUtils::ParseDXLToStatsDerivedRelArray(mp, szDXLInput, NULL); CStatisticsArray *pdrgpstatBefore = CDXLUtils::ParseDXLToOptimizerStatisticObjArray(mp, md_accessor, dxl_derived_rel_stats_array); dxl_derived_rel_stats_array->Release(); GPOS_ASSERT(NULL != pdrgpstatBefore); GPOS_CHECK_ABORT; SStatsCmpValElem statsCmpValElem = rgStatsCmpValElem[ul]; CStatsPredPtrArry *pdrgpstatspred = PdrgppredfilterNumeric(mp, 1 /*colid*/, statsCmpValElem); CStatsPredConj *pred_stats = GPOS_NEW(mp) CStatsPredConj(pdrgpstatspred); GPOS_RESULT eres = EresUnittest_CStatisticsCompare ( mp, md_accessor, pdrgpstatBefore, pred_stats, szDXLOutput, true /*fApplyTwice*/ ); // clean up pdrgpstatBefore->Release(); pred_stats->Release(); GPOS_DELETE_ARRAY(szDXLInput); GPOS_DELETE_ARRAY(szDXLOutput); if (GPOS_OK != eres) { return eres; } } return GPOS_OK; } // generate an array of filter given a column identifier, comparison type, // and array of integer point CStatsPredPtrArry * CFilterCardinalityTest::PdrgpstatspredInteger ( CMemoryPool *mp, ULONG colid, CStatsPred::EStatsCmpType stats_cmp_type, INT *piVals, ULONG ulVals ) { GPOS_ASSERT(0 < ulVals); CStatsPredPtrArry *pdrgpstatspred = GPOS_NEW(mp) CStatsPredPtrArry(mp); for (ULONG ul = 0; ul < ulVals; ul++) { pdrgpstatspred->Append(GPOS_NEW(mp) CStatsPredPoint(colid, stats_cmp_type, CTestUtils::PpointInt4(mp, piVals[ul]))); } return pdrgpstatspred; } // generate a numeric filter on the column specified and the literal value CStatsPredPtrArry * CFilterCardinalityTest::PdrgppredfilterNumeric ( CMemoryPool *mp, ULONG colid, SStatsCmpValElem statsCmpValElem ) { // create a filter CStatsPredPtrArry *pdrgpstatspred = GPOS_NEW(mp) CStatsPredPtrArry(mp); CWStringDynamic *pstrNumeric = GPOS_NEW(mp) CWStringDynamic(mp, statsCmpValElem.m_wsz); CStatsPredPoint *pred_stats = GPOS_NEW(mp) CStatsPredPoint ( colid, statsCmpValElem.m_stats_cmp_type, CCardinalityTestUtils::PpointNumeric(mp, pstrNumeric, statsCmpValElem.m_value) ); pdrgpstatspred->Append(pred_stats); GPOS_DELETE(pstrNumeric); return pdrgpstatspred; } // reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. GPOS_RESULT CFilterCardinalityTest::EresUnittest_CStatisticsBasicsFromDXL() { // create memory pool CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); CWStringDynamic str(mp); COstreamString oss(&str); // read input DXL file CHAR *szDXLInput = CDXLUtils::Read(mp, szInputDXLFileName); // read output DXL file CHAR *szDXLOutput = CDXLUtils::Read(mp, szOutputDXLFileName); GPOS_CHECK_ABORT; CMDAccessor *md_accessor = COptCtxt::PoctxtFromTLS()->Pmda(); // parse the statistics objects CDXLStatsDerivedRelationArray *dxl_derived_rel_stats_array = CDXLUtils::ParseDXLToStatsDerivedRelArray(mp, szDXLInput, NULL); CStatisticsArray *pdrgpstatsBefore = CDXLUtils::ParseDXLToOptimizerStatisticObjArray ( mp, md_accessor, dxl_derived_rel_stats_array ); dxl_derived_rel_stats_array->Release(); GPOS_ASSERT(NULL != pdrgpstatsBefore); GPOS_CHECK_ABORT; // create a filter CStatsPredConj *pred_stats = GPOS_NEW(mp) CStatsPredConj(CStatisticsTest::Pdrgpstatspred2(mp)); GPOS_RESULT eres = EresUnittest_CStatisticsCompare ( mp, md_accessor, pdrgpstatsBefore, pred_stats, szDXLOutput ); // clean up pdrgpstatsBefore->Release(); pred_stats->Release(); GPOS_DELETE_ARRAY(szDXLInput); GPOS_DELETE_ARRAY(szDXLOutput); return eres; } // performs a filter operation on it, serializes it into a DXL document // and compares the generated DXL document with the expected DXL document GPOS_RESULT CFilterCardinalityTest::EresUnittest_CStatisticsCompare ( CMemoryPool *mp, CMDAccessor *md_accessor, CStatisticsArray *pdrgpstatBefore, CStatsPred *pred_stats, const CHAR *szDXLOutput, BOOL fApplyTwice ) { CWStringDynamic str(mp); COstreamString oss(&str); CStatistics *input_stats = (* pdrgpstatBefore)[0]; GPOS_TRACE(GPOS_WSZ_LIT(""Statistics before"")); CCardinalityTestUtils::PrintStats(mp, input_stats); CStatistics *pstatsOutput = CFilterStatsProcessor::MakeStatsFilter(mp, input_stats, pred_stats, true /* do_cap_NDVs */); GPOS_TRACE(GPOS_WSZ_LIT(""Statistics after"")); CCardinalityTestUtils::PrintStats(mp, pstatsOutput); // output array of stats objects CStatisticsArray *pdrgpstatOutput = GPOS_NEW(mp) CStatisticsArray(mp); pdrgpstatOutput->Append(pstatsOutput); oss << ""Serializing Input Statistics Objects (Before Filter)"" << std::endl; CWStringDynamic *pstrInput = CDXLUtils::SerializeStatistics ( mp, md_accessor, pdrgpstatBefore, true /*serialize_header_footer*/, true /*indentation*/ ); GPOS_TRACE(pstrInput->GetBuffer()); GPOS_DELETE(pstrInput); oss << ""Serializing Output Statistics Objects (After Filter)"" << std::endl; CWStringDynamic *pstrOutput = CDXLUtils::SerializeStatistics ( mp, md_accessor, pdrgpstatOutput, true /*serialize_header_footer*/, true /*indentation*/ ); GPOS_TRACE(pstrOutput->GetBuffer()); CWStringDynamic dstrExpected(mp); dstrExpected.AppendFormat(GPOS_WSZ_LIT(""%s""), szDXLOutput); GPOS_RESULT eres = CTestUtils::EresCompare ( oss, pstrOutput, &dstrExpected, false /* ignore mismatch */ ); if (fApplyTwice && GPOS_OK == eres) { CStatistics *pstatsOutput2 = CFilterStatsProcessor::MakeStatsFilter(mp, pstatsOutput, pred_stats, true /* do_cap_NDVs */); pstatsOutput2->Rows(); GPOS_TRACE(GPOS_WSZ_LIT(""Statistics after another filter"")); CCardinalityTestUtils::PrintStats(mp, pstatsOutput2); // output array of stats objects CStatisticsArray *pdrgpstatOutput2 = GPOS_NEW(mp) CStatisticsArray(mp); pdrgpstatOutput2->Append(pstatsOutput2); CWStringDynamic *pstrOutput2 = CDXLUtils::SerializeStatistics ( mp, md_accessor, pdrgpstatOutput2, true /*serialize_header_footer*/, true /*indentation*/ ); eres = CTestUtils::EresCompare ( oss, pstrOutput2, &dstrExpected, false /* ignore mismatch */ ); pdrgpstatOutput2->Release(); GPOS_DELETE(pstrOutput2); } pdrgpstatOutput->Release(); GPOS_DELETE(pstrOutput); return eres; } // test for accumulating cardinality in disjunctive and conjunctive predicates GPOS_RESULT CFilterCardinalityTest::EresUnittest_CStatisticsAccumulateCard() { // create memory pool CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // create hash map from colid -> histogram UlongToHistogramMap *col_histogram_mapping = GPOS_NEW(mp) UlongToHistogramMap(mp); // array capturing columns for which width information is available UlongToDoubleMap *colid_width_mapping = GPOS_NEW(mp) UlongToDoubleMap(mp); const ULONG num_cols = 3; for (ULONG ul = 0; ul < num_cols; ul ++) { // generate histogram of the form [0, 10), [10, 20), [20, 30), [80, 90), [100,100] col_histogram_mapping->Insert(GPOS_NEW(mp) ULONG(ul), CCardinalityTestUtils::PhistExampleInt4(mp)); // width for int colid_width_mapping->Insert(GPOS_NEW(mp) ULONG(ul), GPOS_NEW(mp) CDouble(4.0)); } CStatistics *stats = GPOS_NEW(mp) CStatistics ( mp, col_histogram_mapping, colid_width_mapping, CDouble(1000.0) /* rows */, false /* is_empty() */ ); GPOS_TRACE(GPOS_WSZ_LIT(""\\nOriginal Stats:\\n"")); CCardinalityTestUtils::PrintStats(mp, stats); // (1) // create disjunctive filter CStatsPredPtrArry *pdrgpstatspred = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspred->Append(GPOS_NEW(mp) CStatsPredPoint(0, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 5))); pdrgpstatspred->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 200))); pdrgpstatspred->Append(GPOS_NEW(mp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 200))); CStatsPredDisj *disjunctive_pred_stats = GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspred); // apply filter and print resulting stats CStatistics *pstats1 = CFilterStatsProcessor::MakeStatsFilter(mp, stats, disjunctive_pred_stats, true /* do_cap_NDVs */); CDouble num_rows1 = pstats1->Rows(); GPOS_TRACE(GPOS_WSZ_LIT(""\\n\\nStats after disjunctive filter [Col0=5 OR Col1=200 OR Col2=200]:\\n"")); CCardinalityTestUtils::PrintStats(mp, pstats1); disjunctive_pred_stats->Release(); // (2) // create point filter CStatsPredPtrArry *pdrgpstatspred1 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspred1->Append(GPOS_NEW(mp) CStatsPredPoint(0, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 5))); CStatsPredConj *pstatspredConj1 = GPOS_NEW(mp) CStatsPredConj(pdrgpstatspred1); // apply filter and print resulting stats CStatistics *pstats2 = CFilterStatsProcessor::MakeStatsFilter(mp, stats, pstatspredConj1, true /* do_cap_NDVs */); CDouble num_rows2 = pstats2->Rows(); GPOS_TRACE(GPOS_WSZ_LIT(""\\n\\nStats after point filter [Col0=5]:\\n"")); CCardinalityTestUtils::PrintStats(mp, pstats2); pstatspredConj1->Release(); GPOS_RTL_ASSERT(num_rows1 - num_rows2 < 10 && ""Disjunctive filter and point filter have very different row estimates""); // (3) // create conjunctive filter CStatsPredPtrArry *pdrgpstatspred2 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspred2->Append(GPOS_NEW(mp) CStatsPredPoint(0, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 5))); pdrgpstatspred2->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 200))); pdrgpstatspred2->Append(GPOS_NEW(mp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 200))); CStatsPredConj *pstatspredConj2 = GPOS_NEW(mp) CStatsPredConj(pdrgpstatspred2); // apply filter and print resulting stats CStatistics *pstats3 = CFilterStatsProcessor::MakeStatsFilter(mp, stats, pstatspredConj2, true /* do_cap_NDVs */); CDouble dRows3 = pstats3->Rows(); GPOS_TRACE(GPOS_WSZ_LIT(""\\n\\nStats after conjunctive filter [Col0=5 AND Col1=200 AND Col2=200]:\\n"")); CCardinalityTestUtils::PrintStats(mp, pstats3); pstatspredConj2->Release(); GPOS_RTL_ASSERT(dRows3 < num_rows2 && ""Conjunctive filter passes more rows than than point filter""); // (4) // create selective disjunctive filter that pass no rows CStatsPredPtrArry *pdrgpstatspred3 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspred3->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 200))); pdrgpstatspred3->Append(GPOS_NEW(mp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 200))); CStatsPredDisj *pstatspredDisj1 = GPOS_NEW(mp) CStatsPredDisj(pdrgpstatspred3); // apply filter and print resulting stats CStatistics *pstats4 = CFilterStatsProcessor::MakeStatsFilter(mp, stats, pstatspredDisj1, true /* do_cap_NDVs */); CDouble dRows4 = pstats4->Rows(); GPOS_TRACE(GPOS_WSZ_LIT(""\\n\\nStats after disjunctive filter [Col1=200 OR Col2=200]:\\n"")); CCardinalityTestUtils::PrintStats(mp, pstats4); pstatspredDisj1->Release(); GPOS_RTL_ASSERT(dRows4 < num_rows2 && ""Selective disjunctive filter passes more rows than than point filter""); // (5) // create selective conjunctive filter that pass no rows CStatsPredPtrArry *pdrgpstatspred4 = GPOS_NEW(mp) CStatsPredPtrArry(mp); pdrgpstatspred4->Append(GPOS_NEW(mp) CStatsPredPoint(0, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 5))); pdrgpstatspred4->Append(GPOS_NEW(mp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(mp, 200))); CStatsPredConj *pstatspredConj3 = GPOS_NEW(mp) CStatsPredConj(pdrgpstatspred4); // apply filter and print resulting stats CStatistics *pstats5 = CFilterStatsProcessor::MakeStatsFilter(mp, stats, pstatspredConj3, true /* do_cap_NDVs */); CDouble dRows5 = pstats5->Rows(); GPOS_TRACE(GPOS_WSZ_LIT(""\\n\\nStats after conjunctive filter [Col0=5 AND Col1=200]:\\n"")); CCardinalityTestUtils::PrintStats(mp, pstats5); pstatspredConj3->Release(); GPOS_RTL_ASSERT(dRows5 < num_rows2 && ""Selective conjunctive filter passes more rows than than point filter""); // clean up stats->Release(); pstats1->Release(); pstats2->Release(); pstats3->Release(); pstats4->Release(); pstats5->Release(); return GPOS_OK; } // EOF ",16146,True,3825.85256423041,median "// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include ""open_spiel/games/chess/chess_board.h"" #include #include #include #include #include #include ""open_spiel/abseil-cpp/absl/strings/match.h"" #include ""open_spiel/abseil-cpp/absl/strings/str_cat.h"" #include ""open_spiel/spiel_utils.h"" namespace open_spiel { namespace chess { bool IsMoveCharacter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); } std::pair SplitAnnotations(const std::string &move) { for (int i = 0; i < move.size(); ++i) { if (!IsMoveCharacter(move[i])) { return {move.substr(0, i), std::string(absl::ClippedSubstr(move, i))}; } } return {move, """"}; } std::string ColorToString(Color c) { switch (c) { case Color::kBlack: return ""black""; case Color::kWhite: return ""white""; case Color::kEmpty: return ""empty""; default: SpielFatalError(absl::StrCat(""Unknown color: "", c)); return ""This will never return.""; } } absl::optional PieceTypeFromChar(char c) { switch (toupper(c)) { case 'P': return PieceType::kPawn; case 'N': return PieceType::kKnight; case 'B': return PieceType::kBishop; case 'R': return PieceType::kRook; case 'Q': return PieceType::kQueen; case 'K': return PieceType::kKing; default: std::cerr << ""Invalid piece type: "" << c << std::endl; return absl::nullopt; } } std::string PieceTypeToString(PieceType p, bool uppercase) { switch (p) { case PieceType::kEmpty: return "" ""; case PieceType::kPawn: return uppercase ? ""P"" : ""p""; case PieceType::kKnight: return uppercase ? ""N"" : ""n""; case PieceType::kBishop: return uppercase ? ""B"" : ""b""; case PieceType::kRook: return uppercase ? ""R"" : ""r""; case PieceType::kQueen: return uppercase ? ""Q"" : ""q""; case PieceType::kKing: return uppercase ? ""K"" : ""k""; default: SpielFatalError(""Unknown piece.""); return ""This will never return.""; } } std::string Piece::ToUnicode() const { switch (color) { case Color::kBlack: switch (type) { case PieceType::kEmpty: return "" ""; case PieceType::kPawn: return ""♟""; case PieceType::kKnight: return ""♞""; case PieceType::kBishop: return ""♝""; case PieceType::kRook: return ""♜""; case PieceType::kQueen: return ""♛""; case PieceType::kKing: return ""♚""; default: SpielFatalError(""Unknown piece.""); return ""This will never return.""; } case Color::kWhite: switch (type) { case PieceType::kEmpty: return "" ""; case PieceType::kPawn: return ""♙""; case PieceType::kKnight: return ""♘""; case PieceType::kBishop: return ""♗""; case PieceType::kRook: return ""♖""; case PieceType::kQueen: return ""♕""; case PieceType::kKing: return ""♔""; default: SpielFatalError(""Unknown piece type.""); return ""This will never return.""; } case Color::kEmpty: return "" ""; default: SpielFatalError(""Unknown color.""); return ""This will never return.""; } } std::string Piece::ToString() const { std::string base = PieceTypeToString(type); return color == Color::kWhite ? absl::AsciiStrToUpper(base) : absl::AsciiStrToLower(base); } absl::optional SquareFromString(const std::string &s) { if (s.size() != 2) return kInvalidSquare; auto file = ParseFile(s[0]); auto rank = ParseRank(s[1]); if (file && rank) return Square{*file, *rank}; return absl::nullopt; } bool IsLongDiagonal(const chess::Square &from_sq, const chess::Square &to_sq, int board_size) { if (from_sq == to_sq) { return false; } int half_board_size = board_size / 2; if ((to_sq.y < half_board_size && to_sq.x < half_board_size) || (to_sq.y >= half_board_size && to_sq.x >= half_board_size)) { return from_sq.y - to_sq.y == from_sq.x - to_sq.x; } else { return from_sq.y - to_sq.y == to_sq.x - from_sq.x; } } std::string Move::ToString() const { std::string extra; if (promotion_type != PieceType::kEmpty) { absl::StrAppend(&extra, "", promotion to "", PieceTypeToString(promotion_type)); } if (is_castling) { absl::StrAppend(&extra, "" (castle)""); } return absl::StrCat(piece.ToString(), "" "", SquareToString(from), "" to "", SquareToString(to), extra); } std::string Move::ToLAN() const { std::string promotion; if (promotion_type != PieceType::kEmpty) { promotion = PieceTypeToString(promotion_type, false); } return absl::StrCat(SquareToString(from), SquareToString(to), promotion); } std::string Move::ToSAN(const ChessBoard &board) const { std::string move_text; PieceType piece_type = board.at(from).type; if (is_castling) { if (from.x < to.x) { move_text = ""O-O""; } else { move_text = ""O-O-O""; } } else { switch (piece_type) { case PieceType::kKing: case PieceType::kQueen: case PieceType::kRook: case PieceType::kBishop: case PieceType::kKnight: move_text += PieceTypeToString(piece_type); break; case PieceType::kPawn: // No piece type required. break; case PieceType::kEmpty: std::cerr << ""Move doesn't have a piece type"" << std::endl; } // Now we generate all moves from this position, and see if our file and // rank are unique. bool file_unique = true; bool rank_unique = true; bool disambiguation_required = false; board.GenerateLegalMoves([&](const Move &move) -> bool { if (move.to != to) { return true; } if (move.from == from) { // This is either us, or a promotion to a different type. We don't count // them as ambiguous in either case. return true; } disambiguation_required = true; if (move.from.x == from.x) { file_unique = false; } else if (move.from.y == from.y) { rank_unique = false; } return true; }); bool file_required = false; bool rank_required = false; if (piece_type == PieceType::kPawn && from.x != to.x) { // Pawn captures always need file, and they will never require rank dis- // ambiguation. file_required = true; } else if (disambiguation_required) { if (file_unique) { // This includes when both will disambiguate, in which case we have to // use file. [FIDE Laws of Chess (2018): C.10.3]. file_required = true; } else if (rank_unique) { rank_required = true; } else { // We have neither unique file nor unique rank. This is only possible // with 3 or more pieces of the same type. file_required = true; rank_required = true; } } if (file_required) { absl::StrAppend(&move_text, FileToString(from.x)); } if (rank_required) { absl::StrAppend(&move_text, RankToString(from.y)); } // We have a capture if either 1) the destination square has a piece, or // 2) we are making a diagonal pawn move (which can also be an en-passant // capture, where the destination square would not have a piece). auto piece_at_to_square = board.at(to); if ((piece_at_to_square.type != PieceType::kEmpty) || (piece_type == PieceType::kPawn && from.x != to.x)) { absl::StrAppend(&move_text, ""x""); } // Destination square is always fully encoded. absl::StrAppend(&move_text, SquareToString(to)); // Encode the promotion type if we have a promotion. switch (promotion_type) { case PieceType::kEmpty: break; case PieceType::kQueen: case PieceType::kRook: case PieceType::kBishop: case PieceType::kKnight: absl::StrAppend(&move_text, ""="", PieceTypeToString(promotion_type)); break; case PieceType::kKing: case PieceType::kPawn: std::cerr << ""Cannot promote to "" << PieceTypeToString(promotion_type) << ""! Only Q, R, B, N are allowed"" << std::endl; break; } } // Figure out if this is a check / checkmating move or not. if (!board.KingInCheckAllowed()) { auto board_copy = board; board_copy.ApplyMove(*this); if (board_copy.InCheck()) { bool has_escape = false; board_copy.GenerateLegalMoves([&](const Move &) -> bool { has_escape = true; return false; // No need to keep generating moves. }); if (has_escape) { // Check. absl::StrAppend(&move_text, ""+""); } else { // Checkmate. absl::StrAppend(&move_text, ""#""); } } } return move_text; } ChessBoard::ChessBoard(int board_size, bool king_in_check_allowed) : board_size_(board_size), king_in_check_allowed_(king_in_check_allowed), to_play_(Color::kWhite), ep_square_(kInvalidSquare), irreversible_move_counter_(0), move_number_(1), castling_rights_{{true, true}, {true, true}}, zobrist_hash_(0) { board_.fill(kEmptyPiece); } /*static*/ absl::optional ChessBoard::BoardFromFEN( const std::string &fen, int board_size, bool king_in_check_allowed) { /* An FEN string includes a board position, side to play, castling * rights, ep square, 50 moves clock, and full move number. In that order. * * Eg. start position is: * rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 * * Board is described from rank 8 to rank 1, and files from a to h. Empty * squares are encoded as number of consecutive empty squares. * * Many FEN strings don't have the last two fields. */ ChessBoard board(board_size, king_in_check_allowed); for (auto color : {Color::kBlack, Color::kWhite}) { for (auto dir : {CastlingDirection::kLeft, CastlingDirection::kRight}) { board.SetCastlingRight(color, dir, false); } } std::vector fen_parts = absl::StrSplit(fen, ' '); if (fen_parts.size() != 6 && fen_parts.size() != 4) { std::cerr << ""Invalid FEN: "" << fen << std::endl; return absl::nullopt; } std::string &piece_configuration = fen_parts[0]; std::string &side_to_move = fen_parts[1]; std::string &castling_rights = fen_parts[2]; std::string &ep_square = fen_parts[3]; // These are defaults if the FEN string doesn't have these fields. std::string fifty_clock = ""0""; std::string move_number = ""1""; if (fen_parts.size() == 6) { fifty_clock = fen_parts[4]; move_number = fen_parts[5]; } std::vector piece_config_by_rank = absl::StrSplit(piece_configuration, '/'); for (int8_t current_y = board_size - 1; current_y >= 0; --current_y) { std::string &rank = piece_config_by_rank[board_size - current_y - 1]; int8_t current_x = 0; for (char c : rank) { if (current_x >= board_size) { std::cerr << ""Too many things on FEN rank: "" << rank << std::endl; return absl::nullopt; } if (c >= '1' && c <= '8') { current_x += c - '0'; } else { auto piece_type = PieceTypeFromChar(c); if (!piece_type) { std::cerr << ""Invalid piece type in FEN: "" << c << std::endl; return absl::nullopt; } Color color = isupper(c) ? Color::kWhite : Color::kBlack; board.set_square(Square{current_x, current_y}, Piece{color, *piece_type}); ++current_x; } } } if (side_to_move == ""b"") { board.SetToPlay(Color::kBlack); } else if (side_to_move == ""w"") { board.SetToPlay(Color::kWhite); } else { std::cerr << ""Invalid side to move in FEN: "" << side_to_move << std::endl; return absl::nullopt; } if (castling_rights.find('K') != std::string::npos) { // NOLINT board.SetCastlingRight(Color::kWhite, CastlingDirection::kRight, true); } if (castling_rights.find('Q') != std::string::npos) { // NOLINT board.SetCastlingRight(Color::kWhite, CastlingDirection::kLeft, true); } if (castling_rights.find('k') != std::string::npos) { // NOLINT board.SetCastlingRight(Color::kBlack, CastlingDirection::kRight, true); } if (castling_rights.find('q') != std::string::npos) { // NOLINT board.SetCastlingRight(Color::kBlack, CastlingDirection::kLeft, true); } if (ep_square != ""-"") { auto maybe_ep_square = SquareFromString(ep_square); if (!maybe_ep_square) { std::cerr << ""Invalid en passant square in FEN: "" << ep_square << std::endl; return absl::nullopt; } board.SetEpSquare(*maybe_ep_square); } board.SetIrreversibleMoveCounter(std::stoi(fifty_clock)); board.SetMovenumber(std::stoi(move_number)); return board; } Square ChessBoard::find(const Piece &piece) const { for (int8_t y = 0; y < board_size_; ++y) { for (int8_t x = 0; x < board_size_; ++x) { Square sq{x, y}; if (at(sq) == piece) { return sq; } } } return kInvalidSquare; } void ChessBoard::GenerateLegalMoves(const MoveYieldFn &yield, Color color) const { // We do not need to filter moves that would result for King to move / stay // in check, so we can yield all pseudo legal moves if (king_in_check_allowed_) { GeneratePseudoLegalMoves(yield, color); } else { auto king_square = find(Piece{color, PieceType::kKing}); GeneratePseudoLegalMoves( [this, &king_square, &yield, color](const Move &move) { // See if the move is legal by applying, checking whether the king is // under attack, and undoing the move. // TODO: Optimize this. auto board_copy = *this; board_copy.ApplyMove(move); auto ks = at(move.from).type == PieceType::kKing ? move.to : king_square; if (board_copy.UnderAttack(ks, color)) { return true; } else { return yield(move); } }, color); } } void ChessBoard::GeneratePseudoLegalMoves( const MoveYieldFn &yield, Color color, PseudoLegalMoveSettings settings) const { bool generating = true; #define YIELD(move) \\ if (!yield(move)) { \\ generating = false; \\ } for (int8_t y = 0; y < board_size_ && generating; ++y) { for (int8_t x = 0; x < board_size_ && generating; ++x) { Square sq{x, y}; auto &piece = at(sq); if (piece.type != PieceType::kEmpty && piece.color == color) { switch (piece.type) { case PieceType::kKing: GenerateKingDestinations_( sq, color, [&yield, &piece, &sq, &generating](const Square &to) { YIELD(Move(sq, to, piece)); }); GenerateCastlingDestinations_( sq, color, settings, [&yield, &piece, &sq, &generating](const Square &to) { YIELD(Move(sq, to, piece, PieceType::kEmpty, true)); }); break; case PieceType::kQueen: GenerateQueenDestinations_( sq, color, settings, [&yield, &sq, &piece, &generating](const Square &to) { YIELD(Move(sq, to, piece)); }); break; case PieceType::kRook: GenerateRookDestinations_( sq, color, settings, [&yield, &sq, &piece, &generating](const Square &to) { YIELD(Move(sq, to, piece)); }); break; case PieceType::kBishop: GenerateBishopDestinations_( sq, color, settings, [&yield, &sq, &piece, &generating](const Square &to) { YIELD(Move(sq, to, piece)); }); break; case PieceType::kKnight: GenerateKnightDestinations_( sq, color, [&yield, &sq, &piece, &generating](const Square &to) { YIELD(Move(sq, to, piece)); }); break; case PieceType::kPawn: GeneratePawnDestinations_( sq, color, settings, [&yield, &sq, &piece, &generating, this](const Square &to) { if (IsPawnPromotionRank(to)) { YIELD(Move(sq, to, piece, PieceType::kQueen)); YIELD(Move(sq, to, piece, PieceType::kRook)); YIELD(Move(sq, to, piece, PieceType::kBishop)); YIELD(Move(sq, to, piece, PieceType::kKnight)); } else { YIELD(Move(sq, to, piece)); } }); GeneratePawnCaptureDestinations_( sq, color, settings, true, /* include enpassant */ [&yield, &sq, &piece, &generating, this](const Square &to) { if (IsPawnPromotionRank(to)) { YIELD(Move(sq, to, piece, PieceType::kQueen)); YIELD(Move(sq, to, piece, PieceType::kRook)); YIELD(Move(sq, to, piece, PieceType::kBishop)); YIELD(Move(sq, to, piece, PieceType::kKnight)); } else { YIELD(Move(sq, to, piece)); } }); break; default: std::cerr << ""Unknown piece type: "" << static_cast(piece.type) << std::endl; } } } } #undef YIELD } void ChessBoard::GenerateLegalPawnCaptures(const MoveYieldFn &yield, Color color) const { // We do not need to filter moves that would result for King to move / stay // in check, so we can yield all pseudo legal moves if (king_in_check_allowed_) { GeneratePseudoLegalPawnCaptures(yield, color); } else { auto king_square = find(Piece{color, PieceType::kKing}); GeneratePseudoLegalPawnCaptures( [this, &king_square, &yield, color](const Move &move) { // See if the move is legal by applying, checking whether the king is // under attack, and undoing the move. // TODO: Optimize this. auto board_copy = *this; board_copy.ApplyMove(move); auto ks = at(move.from).type == PieceType::kKing ? move.to : king_square; if (board_copy.UnderAttack(ks, color)) { return true; } else { return yield(move); } }, color); } } void ChessBoard::GeneratePseudoLegalPawnCaptures( const MoveYieldFn &yield, Color color, PseudoLegalMoveSettings settings) const { bool generating = true; #define YIELD(move) \\ if (!yield(move)) { \\ generating = false; \\ } for (int8_t y = 0; y < board_size_ && generating; ++y) { for (int8_t x = 0; x < board_size_ && generating; ++x) { Square sq{x, y}; auto &piece = at(sq); if (piece.type == PieceType::kPawn && piece.color == color) { GeneratePawnCaptureDestinations_( sq, color, settings, true, /* include enpassant */ [&yield, &sq, &piece, &generating, this](const Square &to) { if (IsPawnPromotionRank(to)) { YIELD(Move(sq, to, piece, PieceType::kQueen)); YIELD(Move(sq, to, piece, PieceType::kRook)); YIELD(Move(sq, to, piece, PieceType::kBishop)); YIELD(Move(sq, to, piece, PieceType::kKnight)); } else { YIELD(Move(sq, to, piece)); } }); } } } #undef YIELD } bool ChessBoard::IsBreachingMove(Move tested_move) const { const Piece &piece = at(tested_move.from); if (piece.type == PieceType::kEmpty) return false; if (piece.type == PieceType::kKnight) return false; if (piece.type == PieceType::kPawn) return false; // King never makes breaching moves: a castling that would be breaching // is considered an illegal move. if (piece.type == PieceType::kKing) return false; SPIEL_DCHECK_TRUE(piece.type == PieceType::kQueen || piece.type == PieceType::kRook || piece.type == PieceType::kBishop); // The move is not breaching, if it is generated with // PseudoLegalMoveSettings::kAcknowledgeEnemyPieces bool is_breaching = true; const auto check_breaching = [&](const Square &to) { if (to == tested_move.to) is_breaching = false; }; // Queen moves are a combination of rook and bishop moves. if (piece.type == PieceType::kRook || piece.type == PieceType::kQueen) { GenerateRookDestinations_(tested_move.from, piece.color, kAcknowledgeEnemyPieces, check_breaching); } if (piece.type == PieceType::kBishop || piece.type == PieceType::kQueen) { GenerateBishopDestinations_(tested_move.from, piece.color, kAcknowledgeEnemyPieces, check_breaching); } return is_breaching; } void ChessBoard::BreachingMoveToCaptureMove(Move* move) const { SPIEL_CHECK_TRUE(move); SPIEL_DCHECK_TRUE(IsBreachingMove(*move)); int dx = move->to.x - move->from.x; int dy = move->to.y - move->from.y; SPIEL_DCHECK_TRUE(dx == 0 || dy == 0 || std::abs(dx) == std::abs(dy)); // Cap values to [-1, 1] range to make a proper step size. dx = std::max(-1, dx); dx = std::min(1, dx); dy = std::max(-1, dy); dy = std::min(1, dy); const Offset step{static_cast(dx), static_cast(dy)}; Square sq; for (sq = move->from + step; sq != move->to; sq += step) { if (at(sq).type != PieceType::kEmpty) break; } move->to = sq; } bool ChessBoard::HasSufficientMaterial() const { // Try to detect these 4 conditions. // 1. K vs K // 2. K+B vs K // 3. K+N vs K // 4. K+B* vs K+B* (all bishops on same coloured squares) // If king is allowed to move to/stay in check, any material is sufficient // material. If there is no material, then there is also no opponent king and // that means the game had already ended. if (king_in_check_allowed_) { return true; } // Indexed by colour. int knights[2] = {0, 0}; int dark_bishops[2] = {0, 0}; int light_bishops[2] = {0, 0}; for (int8_t y = 0; y < board_size_; ++y) { for (int8_t x = 0; x < board_size_; ++x) { const auto &piece = at(Square{x, y}); // If we have a queen, rook, or pawn, we have sufficient material. // This is early exit for almost all positions. We check rooks first // because they tend to appear on the corners of boards. if (piece.color != Color::kEmpty) { if (piece.type == PieceType::kRook || piece.type == PieceType::kPawn || piece.type == PieceType::kQueen) { return true; } // We don't care about kings. if (piece.type == PieceType::kKing) { continue; } if (piece.type == PieceType::kKnight) { ++knights[static_cast(piece.color)]; } if (piece.type == PieceType::kBishop) { bool is_dark = ((x + y) % 2 == 0); if (is_dark) { ++dark_bishops[static_cast(piece.color)]; } else { ++light_bishops[static_cast(piece.color)]; } } } } } // Having two knights allows helpmate. if (knights[0] > 1 || knights[1] > 1) { return true; } if (knights[0] == 1) { // If we have anything else, mate is possible. if (light_bishops[0] > 0 || dark_bishops[0] > 0) { return true; } else { // If one side only has a knight, the other side must have something (#3). return knights[1] > 0 || dark_bishops[1] > 0 || light_bishops[1] > 0; } } if (knights[1] == 1) { // If we have anything else, mate is possible. if (light_bishops[1] > 0 || dark_bishops[1] > 0) { return true; } else { // If one side only has a knight, the other side must have something (#3). return knights[0] > 0 || dark_bishops[0] > 0 || light_bishops[0] > 0; } } // Now we only have bishops and kings. We must have two bishops on opposite // coloured squares (from either side) to not be a draw. // This covers #1, #2, and #4. bool dark_bishop_exists = (dark_bishops[0] + dark_bishops[1]) > 0; bool light_bishop_exists = (light_bishops[0] + light_bishops[1]) > 0; return dark_bishop_exists && light_bishop_exists; } absl::optional ChessBoard::ParseMove(const std::string &move) const { // First see if they are in the long form - // ""anan"" (eg. ""e2e4"") or ""anana"" (eg. ""f7f8q"") // SAN moves will never have this form because an SAN move that starts with // a lowercase letter must be a pawn move, and pawn moves will never require // rank disambiguation (meaning the second character will never be a number). auto lan_move = ParseLANMove(move); if (lan_move) { return lan_move; } auto san_move = ParseSANMove(move); if (san_move) { return san_move; } return absl::nullopt; } absl::optional ChessBoard::ParseSANMove( const std::string &move_str) const { std::string move = move_str; if (move.empty()) return absl::nullopt; if (absl::StartsWith(move, ""O-O-O"")) { // Queenside / left castling. std::vector candidates; GenerateLegalMoves([&candidates](const Move &move) { if (move.is_castling && move.to.x == 2) { candidates.push_back(move); } return true; }); if (candidates.size() == 1) return candidates[0]; std::cerr << ""Invalid O-O-O"" << std::endl; return absl::nullopt; } if (absl::StartsWith(move, ""O-O"")) { // Kingside / right castling. std::vector candidates; GenerateLegalMoves([&candidates](const Move &move) { if (move.is_castling && move.to.x == 6) { candidates.push_back(move); } return true; }); if (candidates.size() == 1) return candidates[0]; std::cerr << ""Invalid O-O"" << std::endl; return absl::nullopt; } auto move_annotation = SplitAnnotations(move); move = move_annotation.first; if (move.empty()) { return absl::nullopt; } auto annotation = move_annotation.second; // A move starts with a single letter identifying the piece. This may be // omitted for pawns. PieceType piece_type = PieceType::kPawn; std::string pieces = ""PNBRQK""; if (pieces.find(move[0]) != std::string::npos) { // NOLINT auto maybe_piece_type = PieceTypeFromChar(move[0]); if (!maybe_piece_type) { std::cerr << ""Invalid piece type: "" << move[0] << std::endl; return absl::nullopt; } piece_type = *maybe_piece_type; move = std::string(absl::ClippedSubstr(move, 1)); } // A move always ends with the destination square. if (move.size() < 2) { std::cerr << ""Missing destination square"" << std::endl; return absl::nullopt; } auto destination = std::string(absl::ClippedSubstr(move, move.size() - 2)); move = move.substr(0, move.size() - 2); auto dest_file = ParseFile(destination[0]); auto dest_rank = ParseRank(destination[1]); if (!dest_file || !dest_rank) { std::cerr << ""Failed to parse destination square: "" << destination << std::endl; return absl::nullopt; } Square destination_square{*dest_file, *dest_rank}; // Captures are indicated by a 'x' immediately preceding the destination. // This is irrelevant for parsing, so we just drop it. if (!move.empty() && move[move.size() - 1] == 'x') { move = move.substr(0, move.size() - 1); } // If necessary, source rank and/or file are also included for // disambiguation. absl::optional source_file, source_rank; if (!move.empty()) { source_file = ParseFile(move[0]); if (source_file) { move = std::string(absl::ClippedSubstr(move, 1)); } } if (!move.empty()) { source_rank = ParseRank(move[0]); if (source_rank) { move = std::string(absl::ClippedSubstr(move, 1)); } } if (!move.empty()) { return absl::nullopt; } // Pawn promations are annotated with =Q to indicate the promotion type. absl::optional promotion_type; if (!annotation.empty() && annotation[0] == '=') { if (annotation.size() < 2) { return absl::nullopt; } auto maybe_piece = PieceTypeFromChar(annotation[1]); if (!maybe_piece) return absl::optional(); promotion_type = maybe_piece; } std::vector candidates; GenerateLegalMoves([&candidates, destination_square, piece_type, source_file, source_rank, promotion_type, this](const Move &move) { PieceType moving_piece_type = at(move.from).type; if (move.to == destination_square && moving_piece_type == piece_type && (!source_file || move.from.x == *source_file) && (!source_rank || move.from.y == *source_rank) && (!promotion_type || move.promotion_type == *promotion_type)) { candidates.push_back(move); } return true; }); if (candidates.size() == 1) return candidates[0]; std::cerr << ""expected exactly one matching move, got "" << candidates.size() << std::endl; return absl::optional(); } absl::optional ChessBoard::ParseLANMove(const std::string &move) const { if (move.empty()) { return absl::nullopt; } // Long algebraic notation moves (of the variant we care about) are in one of // two forms - // ""anan"" (eg. ""e2e4"") or ""anana"" (eg. ""f7f8q"") if (move.size() == 4 || move.size() == 5) { if (move[0] < 'a' || move[0] >= ('a' + board_size_) || move[1] < '1' || move[1] >= ('1' + board_size_) || move[2] < 'a' || move[2] >= ('a' + board_size_) || move[3] < '1' || move[3] >= ('1' + board_size_)) { return absl::nullopt; } if (move.size() == 5 && move[4] != 'q' && move[4] != 'r' && move[4] != 'b' && move[4] != 'n') { return absl::nullopt; } auto from = SquareFromString(move.substr(0, 2)); auto to = SquareFromString(std::string(absl::ClippedSubstr(move, 2, 2))); if (from && to) { absl::optional promotion_type; if (move.size() == 5) { promotion_type = PieceTypeFromChar(move[4]); if (!promotion_type) { std::cerr << ""Invalid promotion type"" << std::endl; return absl::nullopt; } } std::vector candidates; GenerateLegalMoves( [&to, &from, &promotion_type, &candidates](const Move &move) { if (move.from == *from && move.to == *to && (!promotion_type || (move.promotion_type == *promotion_type))) { candidates.push_back(move); } return true; }); if (candidates.empty()) { std::cerr << ""Illegal move - "" << move << "" on "" << ToUnicodeString() << std::endl; return Move(); } else if (candidates.size() > 1) { std::cerr << ""Multiple matches (is promotion type missing?) - "" << move << std::endl; return Move(); } return candidates[0]; } } else { return absl::nullopt; } SpielFatalError(""All conditionals failed; this is a bug.""); } void ChessBoard::ApplyMove(const Move &move) { // Most moves are simple - we remove the moving piece from the original // square, and put it on the destination square, overwriting whatever was // there before, update the 50 move counter, and update castling rights. // // There are a few exceptions - castling, en passant, promotions, double pawn // pushes. They require special adjustments in addition to those things. We // do them after the basic apply move. Piece moving_piece = at(move.from); Piece destination_piece = at(move.to); // We have to do it in this order because in Chess960 the king can castle // in-place! That's the only possibility for move.from == move.to. set_square(move.from, kEmptyPiece); set_square(move.to, moving_piece); // Whether the move is irreversible for the purpose of the 50-moves rule. Note // that although castling (and losing castling rights) should be irreversible, // it is counted as reversible here. // Irreversible moves are pawn moves and captures. We don't have to make a // special case for en passant, since they are pawn moves anyways. bool irreversible = (moving_piece.type == PieceType::kPawn) || (destination_piece.type != PieceType::kEmpty); if (irreversible) { SetIrreversibleMoveCounter(0); } else { SetIrreversibleMoveCounter(IrreversibleMoveCounter() + 1); } // Castling rights can be lost in a few different ways - // 1. The king moves (loses both rights), including castling. // 2. A rook moves (loses the right on that side). // 3. Captures an opponent rook (OPPONENT loses the right on that side). if (moving_piece.type == PieceType::kKing) { SetCastlingRight(to_play_, CastlingDirection::kLeft, false); SetCastlingRight(to_play_, CastlingDirection::kRight, false); } if (moving_piece.type == PieceType::kRook) { // TODO(author12): Fix this for Chess960, which requires storing initial // positions of rooks. if ((to_play_ == Color::kWhite && move.from == Square{0, 0}) || (to_play_ == Color::kBlack && move.from == Square{0, 7})) { SetCastlingRight(to_play_, CastlingDirection::kLeft, false); } else if ((to_play_ == Color::kWhite && move.from == Square{7, 0}) || (to_play_ == Color::kBlack && move.from == Square{7, 7})) { SetCastlingRight(to_play_, CastlingDirection::kRight, false); } } if (destination_piece.type == PieceType::kRook) { if ((to_play_ == Color::kWhite && move.to == Square{0, 7}) || (to_play_ == Color::kBlack && move.to == Square{0, 0})) { SetCastlingRight(OppColor(to_play_), CastlingDirection::kLeft, false); } else if ((to_play_ == Color::kWhite && move.to == Square{7, 7}) || (to_play_ == Color::kBlack && move.to == Square{7, 0})) { SetCastlingRight(OppColor(to_play_), CastlingDirection::kRight, false); } } // Special cases that require adjustment - // 1. Castling if (move.is_castling) { SPIEL_CHECK_EQ(moving_piece.type, PieceType::kKing); // We can tell which side we are castling to using ""to"" square. if (to_play_ == Color::kWhite) { if (move.to == Square{2, 0}) { // left castle // TODO(author12): In Chess960, rooks can be anywhere, so delete the // correct squares. set_square(Square{0, 0}, kEmptyPiece); set_square(Square{2, 0}, Piece{Color::kWhite, PieceType::kKing}); set_square(Square{3, 0}, Piece{Color::kWhite, PieceType::kRook}); } else if (move.to == Square{6, 0}) { // right castle set_square(Square{7, 0}, kEmptyPiece); set_square(Square{6, 0}, Piece{Color::kWhite, PieceType::kKing}); set_square(Square{5, 0}, Piece{Color::kWhite, PieceType::kRook}); } else { std::cerr << ""Trying to castle but destination is not valid."" << std::endl; } } else { if (move.to == Square{2, 7}) { // left castle set_square(Square{0, 7}, kEmptyPiece); set_square(Square{2, 7}, Piece{Color::kBlack, PieceType::kKing}); set_square(Square{3, 7}, Piece{Color::kBlack, PieceType::kRook}); } else if (move.to == Square{6, 7}) { // right castle set_square(Square{7, 7}, kEmptyPiece); set_square(Square{6, 7}, Piece{Color::kBlack, PieceType::kKing}); set_square(Square{5, 7}, Piece{Color::kBlack, PieceType::kRook}); } else { std::cerr << ""Trying to castle but destination is not valid.""; } } } // 2. En-passant if (moving_piece.type == PieceType::kPawn && move.from.x != move.to.x && destination_piece.type == PieceType::kEmpty) { if (move.to != EpSquare()) { std::cerr << ""We are trying to capture an empty square "" << ""with a pawn, but the square is not the en passant square:\\n"" << *this << ""\\n"" << ""Move: "" << move.ToString() << std::endl; SpielFatalError(""Trying to apply an invalid move""); } Square captured_pawn_square = move.to; if (to_play_ == Color::kWhite) { --captured_pawn_square.y; } else { ++captured_pawn_square.y; } SPIEL_CHECK_EQ(at(captured_pawn_square), (Piece{OppColor(to_play_), PieceType::kPawn})); set_square(captured_pawn_square, kEmptyPiece); } // 3. Promotions if (moving_piece.type == PieceType::kPawn && IsPawnPromotionRank(move.to)) { set_square(move.to, Piece{at(move.to).color, move.promotion_type}); } // 4. Double push if (moving_piece.type == PieceType::kPawn && abs(move.from.y - move.to.y) == 2) { SetEpSquare(Square{move.from.x, static_cast((move.from.y + move.to.y) / 2)}); } else { SetEpSquare(kInvalidSquare); } if (to_play_ == Color::kBlack) { ++move_number_; } SetToPlay(OppColor(to_play_)); } bool ChessBoard::TestApplyMove(const Move &move) { Color color = to_play_; ApplyMove(move); return !UnderAttack(find(Piece{color, PieceType::kKing}), color); } bool ChessBoard::UnderAttack(const Square &sq, Color our_color) const { SPIEL_CHECK_NE(sq, kInvalidSquare); bool under_attack = false; Color opponent_color = OppColor(our_color); // We do this by pretending we are a piece of different types, and seeing if // we can attack opponent pieces. Eg. if we pretend we are a knight, and can // attack an opponent knight, that means the knight can also attack us. // King moves (this is possible because we use this function for checking // whether we are moving into check, and we can be trying to move the king // into a square attacked by opponent king). GenerateKingDestinations_( sq, our_color, [this, &under_attack, &opponent_color](const Square &to) { if (at(to) == Piece{opponent_color, PieceType::kKing}) { under_attack = true; } }); if (under_attack) { return true; } // Rook moves (for rooks and queens) GenerateRookDestinations_( sq, our_color, PseudoLegalMoveSettings::kAcknowledgeEnemyPieces, [this, &under_attack, &opponent_color](const Square &to) { if ((at(to) == Piece{opponent_color, PieceType::kRook}) || (at(to) == Piece{opponent_color, PieceType::kQueen})) { under_attack = true; } }); if (under_attack) { return true; } // Bishop moves (for bishops and queens) GenerateBishopDestinations_( sq, our_color, PseudoLegalMoveSettings::kAcknowledgeEnemyPieces, [this, &under_attack, &opponent_color](const Square &to) { if ((at(to) == Piece{opponent_color, PieceType::kBishop}) || (at(to) == Piece{opponent_color, PieceType::kQueen})) { under_attack = true; } }); if (under_attack) { return true; } // Knight moves GenerateKnightDestinations_( sq, our_color, [this, &under_attack, &opponent_color](const Square &to) { if (at(to) == Piece{opponent_color, PieceType::kKnight}) { under_attack = true; } }); if (under_attack) { return true; } // Pawn captures. GeneratePawnCaptureDestinations_( sq, our_color, PseudoLegalMoveSettings::kAcknowledgeEnemyPieces, false /* no ep */, [this, &under_attack, &opponent_color](const Square &to) { if (at(to) == Piece{opponent_color, PieceType::kPawn}) { under_attack = true; } }); if (under_attack) { return true; } return false; } std::string ChessBoard::DebugString() const { std::string s; s = absl::StrCat(""FEN: "", ToFEN(), ""\\n""); absl::StrAppend(&s, ""\\n ---------------------------------\\n""); for (int8_t y = board_size_ - 1; y >= 0; --y) { // Rank label. absl::StrAppend(&s, RankToString(y), "" ""); // Pieces on the rank. for (int8_t x = 0; x < board_size_; ++x) { Square sq{x, y}; absl::StrAppend(&s, ""| "", at(sq).ToString(), "" ""); } absl::StrAppend(&s, ""|\\n""); absl::StrAppend(&s, "" ---------------------------------\\n""); } // File labels. absl::StrAppend(&s, "" ""); for (int8_t x = 0; x < board_size_; ++x) { absl::StrAppend(&s, FileToString(x), "" ""); } absl::StrAppend(&s, ""\\n""); absl::StrAppend(&s, ""To play: "", to_play_ == Color::kWhite ? ""W"" : ""B"", ""\\n""); absl::StrAppend(&s, ""En passant square: "", SquareToString(EpSquare()), ""\\n""); absl::StrAppend(&s, ""50-moves clock: "", IrreversibleMoveCounter(), ""\\n""); absl::StrAppend(&s, ""Move number: "", move_number_, ""\\n\\n""); absl::StrAppend(&s, ""Castling rights:\\n""); absl::StrAppend(&s, ""White left (queen-side): "", CastlingRight(Color::kWhite, CastlingDirection::kLeft), ""\\n""); absl::StrAppend(&s, ""White right (king-side): "", CastlingRight(Color::kWhite, CastlingDirection::kRight), ""\\n""); absl::StrAppend(&s, ""Black left (queen-side): "", CastlingRight(Color::kBlack, CastlingDirection::kLeft), ""\\n""); absl::StrAppend(&s, ""Black right (king-side): "", CastlingRight(Color::kBlack, CastlingDirection::kRight), ""\\n""); absl::StrAppend(&s, ""\\n""); return s; } // King moves without castling. template void ChessBoard::GenerateKingDestinations_(Square sq, Color color, const YieldFn &yield) const { static const std::array kOffsets = { {{1, 0}, {1, 1}, {1, -1}, {0, 1}, {0, -1}, {-1, 1}, {-1, 0}, {-1, -1}}}; for (const auto &offset : kOffsets) { Square dest = sq + offset; if (InBoardArea(dest) && IsEmptyOrEnemy(dest, color)) { yield(dest); } } } // Whether all squares between sq1 and sq2 exclusive are empty, and // optionally safe (not under attack). bool ChessBoard::CanCastleBetween( Square sq1, Square sq2, bool check_safe_from_opponent, PseudoLegalMoveSettings settings) const { SPIEL_DCHECK_EQ(sq1.y, sq2.y); const int y = sq1.y; const Color &our_color = at(sq1).color; const int x_start = std::min(sq1.x, sq2.x); const int x_end = std::max(sq1.x, sq2.x); for (int x = x_start; x <= x_end; ++x) { Square test_square{static_cast(x), static_cast(y)}; if (check_safe_from_opponent && UnderAttack(test_square, our_color)) return false; if (settings == PseudoLegalMoveSettings::kAcknowledgeEnemyPieces && IsEnemy(test_square, our_color)) return false; const bool x_in_between = x > x_start && x < x_end; if (x_in_between && IsFriendly(test_square, our_color)) return false; } return true; } template void ChessBoard::GenerateCastlingDestinations_(Square sq, Color color, PseudoLegalMoveSettings settings, const YieldFn &yield) const { // There are 8 conditions for castling - // 1. The rook involved must not have moved. // 2. The king must not have moved. // 3. The rook involved must still be alive. // 4. All squares king jumps over must be empty. // 5. All squares the rook jumps over must be empty. // 6. The squares the king jumps over must not be under attack. // 7. The king must not be in check. // (8). The square the king ends up in must not be under attack. // // We don't check for (8) here because this is not unique to castling, and // we will check for it later. // // We use the generalized definition of castling from Chess960, instead of // hard-coding starting squares. // By Chess960 rules, the king and rook end up in the same positions as in // standard chess, but they can start from any squares. // // Castling to one side doesn't necessarily mean the king will move towards // that side. // Eg. // |RK...R..| + long castle (to the left) => // |..KR.R..| // castling is not defined for other chessboards than the standard one if (board_size_ != 8) { return; } const auto check_castling_conditions = [this, &sq, &color, &settings](int8_t x_direction) -> bool { // First we need to find the rook. Square rook_sq = sq + Offset{x_direction, 0}; bool rook_found = false; // Yes, we do actually have to check colour - // https://github.com/official-stockfish/Stockfish/issues/356 for (; InBoardArea(rook_sq); rook_sq.x += x_direction) { if (at(rook_sq) == Piece{color, PieceType::kRook}) { rook_found = true; break; } } if (!rook_found) { std::cerr << ""Where did our rook go?"" << *this << ""\\n"" << ""Square: "" << SquareToString(sq) << std::endl; SpielFatalError(""Rook not found""); } int8_t rook_final_x = x_direction == -1 ? 3 /* d-file */ : 5 /* f-file */; Square rook_final_sq = Square{rook_final_x, sq.y}; int8_t king_final_x = x_direction == -1 ? 2 /* c-file */ : 6 /* g-file */; Square king_final_sq = Square{king_final_x, sq.y}; // 4. 5. 6. All squares the king and rook jump over, including the final // squares, must be empty. Squares king jumps over must additionally be // safe. const bool make_king_jump_check = !king_in_check_allowed_ && settings == PseudoLegalMoveSettings::kAcknowledgeEnemyPieces; if (!CanCastleBetween(rook_sq, rook_final_sq, false, settings) || !CanCastleBetween(sq, king_final_sq, make_king_jump_check, settings)) { return false; } return true; }; // 1. 2. 3. Moving the king, moving the rook, or the rook getting captured // will reset the flag. bool can_left_castle = CastlingRight(color, CastlingDirection::kLeft) && check_castling_conditions(-1); bool can_right_castle = CastlingRight(color, CastlingDirection::kRight) && check_castling_conditions(1); if (can_left_castle || can_right_castle) { // 7. No castling to escape from check. if (UnderAttack(sq, color) && !(king_in_check_allowed_ || settings == PseudoLegalMoveSettings::kBreachEnemyPieces)) { return; } if (can_left_castle) { yield(Square{static_cast(2), sq.y}); } if (can_right_castle) { yield(Square{static_cast(6), sq.y}); } } } template void ChessBoard::GenerateQueenDestinations_(Square sq, Color color, PseudoLegalMoveSettings settings, const YieldFn &yield) const { GenerateRookDestinations_(sq, color, settings, yield); GenerateBishopDestinations_(sq, color, settings, yield); } template void ChessBoard::GenerateRookDestinations_(Square sq, Color color, PseudoLegalMoveSettings settings, const YieldFn &yield) const { GenerateRayDestinations_(sq, color, settings, {1, 0}, yield); GenerateRayDestinations_(sq, color, settings, {-1, 0}, yield); GenerateRayDestinations_(sq, color, settings, {0, 1}, yield); GenerateRayDestinations_(sq, color, settings, {0, -1}, yield); } template void ChessBoard::GenerateBishopDestinations_(Square sq, Color color, PseudoLegalMoveSettings settings, const YieldFn &yield) const { GenerateRayDestinations_(sq, color, settings, {1, 1}, yield); GenerateRayDestinations_(sq, color, settings, {-1, 1}, yield); GenerateRayDestinations_(sq, color, settings, {1, -1}, yield); GenerateRayDestinations_(sq, color, settings, {-1, -1}, yield); } template void ChessBoard::GenerateKnightDestinations_(Square sq, Color color, const YieldFn &yield) const { for (const auto &offset : kKnightOffsets) { Square dest = sq + offset; if (InBoardArea(dest) && IsEmptyOrEnemy(dest, color)) { yield(dest); } } } // Pawn moves without captures. template void ChessBoard::GeneratePawnDestinations_(Square sq, Color color, PseudoLegalMoveSettings settings, const YieldFn &yield) const { int8_t y_direction = color == Color::kWhite ? 1 : -1; Square dest = sq + Offset{0, y_direction}; if (InBoardArea(dest) && (IsEmpty(dest) || (IsEnemy(dest, color) && settings == PseudoLegalMoveSettings::kBreachEnemyPieces))) { yield(dest); // Test for double move. Only defined on standard board if (board_size_ == 8 && IsPawnStartingRank(sq, color)) { dest = sq + Offset{0, static_cast(2 * y_direction)}; if (IsEmpty(dest) || (IsEnemy(dest, color) && settings == PseudoLegalMoveSettings::kBreachEnemyPieces)) { yield(dest); } } } } // Pawn capture destinations, with or without en passant. template void ChessBoard::GeneratePawnCaptureDestinations_( Square sq, Color color, PseudoLegalMoveSettings settings, bool include_ep, const YieldFn &yield) const { int8_t y_direction = color == Color::kWhite ? 1 : -1; Square dest = sq + Offset{1, y_direction}; if (InBoardArea(dest) && (IsEnemy(dest, color) || (include_ep && dest == EpSquare()) || (IsEmpty(dest) && settings == PseudoLegalMoveSettings::kBreachEnemyPieces))) { yield(dest); } dest = sq + Offset{-1, y_direction}; if (InBoardArea(dest) && (IsEnemy(dest, color) || (include_ep && dest == EpSquare()) || (IsEmpty(dest) && settings == PseudoLegalMoveSettings::kBreachEnemyPieces))) { yield(dest); } } template void ChessBoard::GenerateRayDestinations_(Square sq, Color color, PseudoLegalMoveSettings settings, Offset offset_step, const YieldFn &yield) const { for (Square dest = sq + offset_step; InBoardArea(dest); dest += offset_step) { if (IsEmpty(dest)) { yield(dest); } else if (IsEnemy(dest, color)) { yield(dest); if (settings == PseudoLegalMoveSettings::kAcknowledgeEnemyPieces) { break; } } else { // We have a friendly piece. break; } } } std::string ChessBoard::ToUnicodeString() const { std::string out = ""\\n""; for (int8_t rank = board_size_ - 1; rank >= 0; --rank) { out += std::to_string(rank + 1); for (int8_t file = 0; file < board_size_; ++file) { out += at(Square{file, rank}).ToUnicode(); } out += ""\\n""; } out += ' '; for (int8_t file = 0; file < board_size_; ++file) { out += ('a' + file); } out += '\\n'; return out; } std::string ChessBoard::ToFEN() const { // Example FEN: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 std::string fen; // 1. encode the board. for (int8_t rank = board_size_ - 1; rank >= 0; --rank) { int num_empty = 0; for (int8_t file = 0; file < board_size_; ++file) { auto piece = at(Square{file, rank}); if (piece == kEmptyPiece) { ++num_empty; } else { if (num_empty > 0) { absl::StrAppend(&fen, num_empty); num_empty = 0; } absl::StrAppend(&fen, piece.ToString()); } } if (num_empty > 0) { absl::StrAppend(&fen, num_empty); } if (rank > 0) { fen.push_back('/'); } } // 2. color to play. absl::StrAppend(&fen, "" "", to_play_ == Color::kWhite ? ""w"" : ""b""); // 3. by castling rights. absl::StrAppend(&fen, "" ""); std::string castling_rights; if (CastlingRight(Color::kWhite, CastlingDirection::kRight)) { castling_rights.push_back('K'); } if (CastlingRight(Color::kWhite, CastlingDirection::kLeft)) { castling_rights.push_back('Q'); } if (CastlingRight(Color::kBlack, CastlingDirection::kRight)) { castling_rights.push_back('k'); } if (CastlingRight(Color::kBlack, CastlingDirection::kLeft)) { castling_rights.push_back('q'); } absl::StrAppend(&fen, castling_rights.empty() ? ""-"" : castling_rights); // 4. en passant square absl::StrAppend(&fen, "" ""); absl::StrAppend( &fen, EpSquare() == kInvalidSquare ? ""-"" : SquareToString(EpSquare())); // 5. half-move clock for 50-move rule absl::StrAppend(&fen, "" "", irreversible_move_counter_); // 6. full-move clock absl::StrAppend(&fen, "" "", move_number_); return fen; } // Used in Dark Chess (see games/dark_chess.{h,cc}) std::string ChessBoard::ToDarkFEN(const ObservationTable &observability_table, Color color) const { std::string fen; // 1. encode the board. for (int8_t rank = board_size_ - 1; rank >= 0; --rank) { int num_empty = 0; for (int8_t file = 0; file < board_size_; ++file) { size_t index = SquareToIndex_(chess::Square{file, rank}); if (!observability_table[index]) { if (num_empty > 0) { fen += std::to_string(num_empty); num_empty = 0; } fen.push_back('?'); } else { const Piece &piece = at(chess::Square{file, rank}); if (piece == chess::kEmptyPiece) { ++num_empty; } else { if (num_empty > 0) { fen += std::to_string(num_empty); num_empty = 0; } absl::StrAppend(&fen, piece.ToString()); } } } if (num_empty > 0) { absl::StrAppend(&fen, num_empty); } if (rank > 0) { fen.push_back('/'); } } // 2. color to play. absl::StrAppend(&fen, "" "", ToPlay() == chess::Color::kWhite ? ""w"" : ""b""); // 3. by castling rights. absl::StrAppend(&fen, "" ""); std::string castling_rights; if (color == chess::Color::kWhite) { if (CastlingRight(chess::Color::kWhite, chess::CastlingDirection::kRight)) { castling_rights.push_back('K'); } if (CastlingRight(chess::Color::kWhite, chess::CastlingDirection::kLeft)) { castling_rights.push_back('Q'); } } else { if (CastlingRight(chess::Color::kBlack, chess::CastlingDirection::kRight)) { castling_rights.push_back('k'); } if (CastlingRight(chess::Color::kBlack, chess::CastlingDirection::kLeft)) { castling_rights.push_back('q'); } } absl::StrAppend(&fen, castling_rights.empty() ? ""-"" : castling_rights); // 4. en passant square std::string ep_square = ""-""; if (EpSquare() != kInvalidSquare) { int8_t reversed_y_direction = color == Color::kWhite ? -1 : 1; Square from = EpSquare() + Offset{1, reversed_y_direction}; Piece piece = at(from); if (piece.color == color && piece.type == PieceType::kPawn) { ep_square = SquareToString(EpSquare()); } else { from = EpSquare() + Offset{-1, reversed_y_direction}; piece = at(from); if (piece.color == color && piece.type == PieceType::kPawn) { ep_square = SquareToString(EpSquare()); } } } absl::StrAppend(&fen, "" "", ep_square); // 5. half-move clock for 50-move rule absl::StrAppend(&fen, "" "", IrreversibleMoveCounter()); // 6. full-move clock absl::StrAppend(&fen, "" "", move_number_); return fen; } void ChessBoard::set_square(Square sq, Piece piece) { static const ZobristTableU64 kZobristValues( /*seed=*/2765481); // First, remove the current piece from the hash. auto position = SquareToIndex_(sq); auto current_piece = at(sq); zobrist_hash_ ^= kZobristValues[position][static_cast(current_piece.color)] [static_cast(current_piece.type)]; // Then add the new piece zobrist_hash_ ^= kZobristValues[position][static_cast(piece.color)] [static_cast(piece.type)]; board_[position] = piece; } bool ChessBoard::CastlingRight(Color side, CastlingDirection direction) const { switch (direction) { case CastlingDirection::kLeft: return castling_rights_[ToInt(side)].left_castle; case CastlingDirection::kRight: return castling_rights_[ToInt(side)].right_castle; default: SpielFatalError(""Unknown direction.""); return -1; } } int ToInt(CastlingDirection direction) { switch (direction) { case CastlingDirection::kLeft: return 0; case CastlingDirection::kRight: return 1; default: SpielFatalError(""Unknown direction.""); return -1; } } void ChessBoard::SetCastlingRight(Color side, CastlingDirection direction, bool can_castle) { static const ZobristTableU64<2, 2, 2> kZobristValues(/*seed=*/876387212); // Remove old value from hash. zobrist_hash_ ^= kZobristValues[ToInt(side)][ToInt(direction)] [CastlingRight(side, direction)]; // Then add the new value. zobrist_hash_ ^= kZobristValues[ToInt(side)][ToInt(direction)][can_castle]; switch (direction) { case CastlingDirection::kLeft: castling_rights_[ToInt(side)].left_castle = can_castle; break; case CastlingDirection::kRight: castling_rights_[ToInt(side)].right_castle = can_castle; break; } } void ChessBoard::SetToPlay(Color c) { static const ZobristTableU64<2> kZobristValues(/*seed=*/284628); // Remove old color and add new to play. zobrist_hash_ ^= kZobristValues[ToInt(to_play_)]; zobrist_hash_ ^= kZobristValues[ToInt(c)]; to_play_ = c; } void ChessBoard::SetIrreversibleMoveCounter(int c) { irreversible_move_counter_ = c; } void ChessBoard::SetMovenumber(int move_number) { move_number_ = move_number; } void ChessBoard::SetEpSquare(Square sq) { static const ZobristTableU64 kZobristValues( /*seed=*/837261); if (EpSquare() != kInvalidSquare) { // Remove en passant square if there was one. zobrist_hash_ ^= kZobristValues[EpSquare().x][EpSquare().y]; } if (sq != kInvalidSquare) { zobrist_hash_ ^= kZobristValues[sq.x][sq.y]; } ep_square_ = sq; } ChessBoard MakeDefaultBoard() { auto maybe_board = ChessBoard::BoardFromFEN(kDefaultStandardFEN); SPIEL_CHECK_TRUE(maybe_board); return *maybe_board; } std::string DefaultFen(int board_size) { if (board_size == 8) return chess::kDefaultStandardFEN; else if (board_size == 4) return chess::kDefaultSmallFEN; else SpielFatalError( ""Only board sizes 4 and 8 have their default chessboards. "" ""For other sizes, you have to pass your own FEN.""); } } // namespace chess } // namespace open_spiel ",16206,True,2970.1949672142237,median "[[main-component]] = Main Component :docTitle: Main :artifactId: camel-main :description: Camel Main support :since: 3.0 :supportLevel: Stable //Manually maintained attributes :group: Core *Since Camel {since}* This module is used for running Camel standalone via a main class extended from `camel-main`. == Configuration options When running Camel via `camel-main` you can configure Camel in the `application.properties` file. The following table lists all the options: // main options: START [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.main.allowUseOriginal{zwsp}Message* | Sets whether to allow access to the original message from Camel's error handler, or from org.apache.camel.spi.UnitOfWork.getOriginalInMessage(). Turning this off can optimize performance, as defensive copy of the original message is not needed. Default is false. | | boolean | *camel.main.autoConfiguration{zwsp}Enabled* | Whether auto configuration of components, dataformats, languages is enabled or not. When enabled the configuration parameters are loaded from the properties component and optionally from the classpath file META-INF/services/org/apache/camel/autowire.properties. You can prefix the parameters in the properties file with: - camel.component.name.option1=value1 - camel.component.name.option2=value2 - camel.dataformat.name.option1=value1 - camel.dataformat.name.option2=value2 - camel.language.name.option1=value1 - camel.language.name.option2=value2 Where name is the name of the component, dataformat or language such as seda,direct,jaxb. The auto configuration also works for any options on components that is a complex type (not standard Java type) and there has been an explicit single bean instance registered to the Camel registry via the org.apache.camel.spi.Registry#bind(String,Object) method or by using the org.apache.camel.BindToRegistry annotation style. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}EnvironmentVariablesEnabled* | Whether auto configuration should include OS environment variables as well. When enabled this allows to overrule any configuration using an OS environment variable. For example to set a shutdown timeout of 5 seconds: CAMEL_MAIN_SHUTDOWNTIMEOUT=5. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}FailFast* | Whether auto configuration should fail fast when configuring one ore more properties fails for whatever reason such as a invalid property name, etc. This option is default enabled. | true | boolean | *camel.main.autoConfiguration{zwsp}LogSummary* | Whether auto configuration should log a summary with the configured properties. This option is default enabled. | true | boolean | *camel.main.autoStartup* | Sets whether the object should automatically start when Camel starts. Important: Currently only routes can be disabled, as CamelContext's are always started. Note: When setting auto startup false on CamelContext then that takes precedence and no routes are started. You would need to start CamelContext explicit using the org.apache.camel.CamelContext.start() method, to start the context, and then you would need to start the routes manually using CamelContext.getRouteController().startRoute(String). Default is true to always start up. | true | boolean | *camel.main.backlogTracing* | Sets whether backlog tracing is enabled or not. Default is false. | | boolean | *camel.main.beanIntrospection{zwsp}ExtendedStatistics* | Sets whether bean introspection uses extended statistics. The default is false. | | boolean | *camel.main.beanIntrospection{zwsp}LoggingLevel* | Sets the logging level used by bean introspection, logging activity of its usage. The default is TRACE. | | LoggingLevel | *camel.main.beanPostProcessor{zwsp}Enabled* | Can be used to turn off bean post processing. Be careful to turn this off, as this means that beans that use Camel annotations such as org.apache.camel.EndpointInject , org.apache.camel.ProducerTemplate , org.apache.camel.Produce , org.apache.camel.Consume etc will not be injected and in use. Turning this off should only be done if you are sure you do not use any of these Camel features. Not all runtimes allow turning this off (such as camel-blueprint or camel-cdi with XML). The default value is true (enabled). | true | boolean | *camel.main.caseInsensitive{zwsp}Headers* | Whether to use case sensitive or insensitive headers. Important: When using case sensitive (this is set to false). Then the map is case sensitive which means headers such as content-type and Content-Type are two different keys which can be a problem for some protocols such as HTTP based, which rely on case insensitive headers. However case sensitive implementations can yield faster performance. Therefore use case sensitive implementation with care. Default is true. | true | boolean | *camel.main.configuration{zwsp}Classes* | Sets classes names that will be used to configure the camel context as example by providing custom beans through org.apache.camel.BindToRegistry annotation. | | String | *camel.main.configurations* | Sets the configuration objects used to configure the camel context. | | List | *camel.main.consumerTemplate{zwsp}CacheSize* | Consumer template endpoints cache size. | 1000 | int | *camel.main.durationHitExitCode* | Sets the exit code for the application if duration was hit | | int | *camel.main.durationMaxIdle{zwsp}Seconds* | To specify for how long time in seconds Camel can be idle before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.durationMaxMessages* | To specify how many messages to process by Camel before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.durationMaxSeconds* | To specify for how long time in seconds to keep running the JVM before automatic terminating the JVM. You can use this to run Camel for a short while. | | int | *camel.main.endpointBasic{zwsp}PropertyBinding* | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities. The default value is false. | | boolean | *camel.main.endpointBridgeError{zwsp}Handler* | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN/ERROR level and ignored. The default value is false. | | boolean | *camel.main.endpointLazyStart{zwsp}Producer* | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. The default value is false. | | boolean | *camel.main.endpointRuntime{zwsp}StatisticsEnabled* | Sets whether endpoint runtime statistics is enabled (gathers runtime usage of each incoming and outgoing endpoints). The default value is false. | | boolean | *camel.main.fileConfigurations* | Directory to load additional configuration files that contains configuration values that takes precedence over any other configuration. This can be used to refer to files that may have secret configuration that has been mounted on the file system for containers. You can specify a pattern to load from sub directories and a name pattern such as /var/app/secret/.properties, multiple directories can be separated by comma. | | String | *camel.main.inflightRepository{zwsp}BrowseEnabled* | Sets whether the inflight repository should allow browsing each inflight exchange. This is by default disabled as there is a very slight performance overhead when enabled. | | boolean | *camel.main.javaRoutesExclude{zwsp}Pattern* | Used for exclusive filtering component scanning of RouteBuilder classes with Component annotation. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma. For example to exclude all classes starting with Bar use: **/Bar* To exclude all routes form a specific package use: com/mycompany/bar/* To exclude all routes form a specific package and its sub-packages use double wildcards: com/mycompany/bar/** And to exclude all routes from two specific packages use: com/mycompany/bar/*,com/mycompany/stuff/* | | String | *camel.main.javaRoutesInclude{zwsp}Pattern* | Used for inclusive filtering component scanning of RouteBuilder classes with Component annotation. The exclusive filtering takes precedence over inclusive filtering. The pattern is using Ant-path style pattern. Multiple patterns can be specified separated by comma. For example to include all classes starting with Foo use: **/Foo To include all routes form a specific package use: com/mycompany/foo/* To include all routes form a specific package and its sub-packages use double wildcards: com/mycompany/foo/** And to include all routes from two specific packages use: com/mycompany/foo/*,com/mycompany/stuff/* | | String | *camel.main.jmxEnabled* | Enable JMX in your Camel application. | true | boolean | *camel.main.jmxManagementName{zwsp}Pattern* | The naming pattern for creating the CamelContext JMX management name. The default pattern is #name# | #name# | String | *camel.main.jmxManagement{zwsp}StatisticsLevel* | Sets the JMX statistics level, the level can be set to Extended to gather additional information The default value is Default. | Default | ManagementStatisticsLevel | *camel.main.lightweight* | Experimental: Configure the context to be lightweight. This will trigger some optimizations and memory reduction options. Lightweight context have some limitations. At this moment, dynamic endpoint destinations are not supported. | | boolean | *camel.main.loadTypeConverters* | Whether to load custom type converters by scanning classpath. This is used for backwards compatibility with Camel 2.x. Its recommended to migrate to use fast type converter loading by setting Converter(loader = true) on your custom type converter classes. | | boolean | *camel.main.logDebugMaxChars* | Is used to limit the maximum length of the logging Camel message bodies. If the message body is longer than the limit, the log message is clipped. Use -1 to have unlimited length. Use for example 1000 to log at most 1000 characters. | | int | *camel.main.logExhaustedMessage{zwsp}Body* | Sets whether to log exhausted message body with message history. Default is false. | | boolean | *camel.main.logMask* | Sets whether log mask is enabled or not. Default is false. | | boolean | *camel.main.mdcLoggingKeys{zwsp}Pattern* | Sets the pattern used for determine which custom MDC keys to propagate during message routing when the routing engine continues routing asynchronously for the given message. Setting this pattern to will propagate all custom keys. Or setting the pattern to foo,bar will propagate any keys starting with either foo or bar. Notice that a set of standard Camel MDC keys are always propagated which starts with camel. as key name. The match rules are applied in this order (case insensitive): 1. exact match, returns true 2. wildcard match (pattern ends with a and the name starts with the pattern), returns true 3. regular expression match, returns true 4. otherwise returns false | | String | *camel.main.messageHistory* | Sets whether message history is enabled or not. Default is false. | | boolean | *camel.main.name* | Sets the name of the CamelContext. | | String | *camel.main.packageScanRoute{zwsp}Builders* | Sets package names for scanning for org.apache.camel.builder.RouteBuilder classes as candidates to be included. If you are using Spring Boot then its instead recommended to use Spring Boots component scanning and annotate your route builder classes with Component. In other words only use this for Camel Main in standalone mode. | | String | *camel.main.producerTemplate{zwsp}CacheSize* | Producer template endpoints cache size. | 1000 | int | *camel.main.routeControllerBack{zwsp}OffDelay* | Backoff delay in millis when restarting a route that failed to startup. | | long | *camel.main.routeControllerBack{zwsp}OffMaxAttempts* | Backoff maximum number of attempts to restart a route that failed to startup. When this threshold has been exceeded then the controller will give up attempting to restart the route, and the route will remain as stopped. | | long | *camel.main.routeControllerBack{zwsp}OffMaxDelay* | Backoff maximum delay in millis when restarting a route that failed to startup. | | long | *camel.main.routeControllerBack{zwsp}OffMaxElapsedTime* | Backoff maximum elapsed time in millis, after which the backoff should be considered exhausted and no more attempts should be made. | | long | *camel.main.routeControllerBack{zwsp}OffMultiplier* | Backoff multiplier to use for exponential backoff. This is used to extend the delay between restart attempts. | | double | *camel.main.routeController{zwsp}ExcludeRoutes* | Pattern for filtering routes to be excluded as supervised. The pattern is matching on route id, and endpoint uri for the route. Multiple patterns can be separated by comma. For example to exclude all JMS routes, you can say jms:. And to exclude routes with specific route ids mySpecialRoute,myOtherSpecialRoute. The pattern supports wildcards and uses the matcher from org.apache.camel.support.PatternHelper#matchPattern. | | String | *camel.main.routeController{zwsp}IncludeRoutes* | Pattern for filtering routes to be included as supervised. The pattern is matching on route id, and endpoint uri for the route. Multiple patterns can be separated by comma. For example to include all kafka routes, you can say kafka:. And to include routes with specific route ids myRoute,myOtherRoute. The pattern supports wildcards and uses the matcher from org.apache.camel.support.PatternHelper#matchPattern. | | String | *camel.main.routeController{zwsp}InitialDelay* | Initial delay in milli seconds before the route controller starts, after CamelContext has been started. | | long | *camel.main.routeController{zwsp}RouteStartupLoggingLevel* | Sets the logging level used for logging route startup activity. By default INFO level is used. You can use this to change the level for example to OFF if this kind of logging is not wanted. | INFO | LoggingLevel | *camel.main.routeController{zwsp}SuperviseEnabled* | To enable using supervising route controller which allows Camel to startup and then the controller takes care of starting the routes in a safe manner. This can be used when you want to startup Camel despite a route may otherwise fail fast during startup and cause Camel to fail to startup as well. By delegating the route startup to the supervising route controller then its manages the startup using a background thread. The controller allows to be configured with various settings to attempt to restart failing routes. | | boolean | *camel.main.routeController{zwsp}ThreadPoolSize* | The number of threads used by the route controller scheduled thread pool that are used for restarting routes. The pool uses 1 thread by default, but you can increase this to allow the controller to concurrently attempt to restart multiple routes in case more than one route has problems starting. | | int | *camel.main.routeController{zwsp}UnhealthyOnExhausted* | Whether to mark the route as unhealthy (down) when all restarting attempts (backoff) have failed and the route is not successfully started and the route manager is giving up. Setting this to true allows health checks to know about this and can report the Camel application as DOWN. The default is false. | | boolean | *camel.main.routeFilterExclude{zwsp}Pattern* | Used for filtering routes routes matching the given pattern, which follows the following rules: - Match by route id - Match by route input endpoint uri The matching is using exact match, by wildcard and regular expression as documented by PatternHelper#matchPattern(String,String) . For example to only include routes which starts with foo in their route id's, use: include=foo* And to exclude routes which starts from JMS endpoints, use: exclude=jms:* Multiple patterns can be separated by comma, for example to exclude both foo and bar routes, use: exclude=foo*,bar* Exclude takes precedence over include. | | String | *camel.main.routeFilterInclude{zwsp}Pattern* | Used for filtering routes matching the given pattern, which follows the following rules: - Match by route id - Match by route input endpoint uri The matching is using exact match, by wildcard and regular expression as documented by PatternHelper#matchPattern(String,String) . For example to only include routes which starts with foo in their route id's, use: include=foo* And to exclude routes which starts from JMS endpoints, use: exclude=jms:* Multiple patterns can be separated by comma, for example to exclude both foo and bar routes, use: exclude=foo*,bar* Exclude takes precedence over include. | | String | *camel.main.routesBuilder{zwsp}Classes* | Sets classes names that implement RoutesBuilder . | | String | *camel.main.routesBuilders* | Sets the RoutesBuilder instances. | | List | *camel.main.routesCollector{zwsp}Enabled* | Whether the routes collector is enabled or not. When enabled Camel will auto-discover routes (RouteBuilder instances from the registry and also load additional XML routes from the file system. The routes collector is default enabled. | true | boolean | *camel.main.shutdownLogInflight{zwsp}ExchangesOnTimeout* | Sets whether to log information about the inflight Exchanges which are still running during a shutdown which didn't complete without the given timeout. This requires to enable the option inflightRepositoryBrowseEnabled. | true | boolean | *camel.main.shutdownNowOn{zwsp}Timeout* | Sets whether to force shutdown of all consumers when a timeout occurred and thus not all consumers was shutdown within that period. You should have good reasons to set this option to false as it means that the routes keep running and is halted abruptly when CamelContext has been shutdown. | true | boolean | *camel.main.shutdownRoutesIn{zwsp}ReverseOrder* | Sets whether routes should be shutdown in reverse or the same order as they were started. | true | boolean | *camel.main.shutdownSuppress{zwsp}LoggingOnTimeout* | Whether Camel should try to suppress logging during shutdown and timeout was triggered, meaning forced shutdown is happening. And during forced shutdown we want to avoid logging errors/warnings et all in the logs as a side-effect of the forced timeout. Notice the suppress is a best effort as there may still be some logs coming from 3rd party libraries and whatnot, which Camel cannot control. This option is default false. | | boolean | *camel.main.shutdownTimeout* | Timeout in seconds to graceful shutdown Camel. | 45 | int | *camel.main.streamCachingAny{zwsp}SpoolRules* | Sets whether if just any of the org.apache.camel.spi.StreamCachingStrategy.SpoolRule rules returns true then shouldSpoolCache(long) returns true, to allow spooling to disk. If this option is false, then all the org.apache.camel.spi.StreamCachingStrategy.SpoolRule must return true. The default value is false which means that all the rules must return true. | | boolean | *camel.main.streamCachingBuffer{zwsp}Size* | Sets the stream caching buffer size to use when allocating in-memory buffers used for in-memory stream caches. The default size is 4096. | | int | *camel.main.streamCaching{zwsp}Enabled* | Sets whether stream caching is enabled or not. Default is false. | | boolean | *camel.main.streamCachingRemove{zwsp}SpoolDirectoryWhenStopping* | Whether to remove stream caching temporary directory when stopping. This option is default true. | true | boolean | *camel.main.streamCachingSpool{zwsp}Cipher* | Sets a stream caching cipher name to use when spooling to disk to write with encryption. By default the data is not encrypted. | | String | *camel.main.streamCachingSpool{zwsp}Directory* | Sets the stream caching spool (temporary) directory to use for overflow and spooling to disk. If no spool directory has been explicit configured, then a temporary directory is created in the java.io.tmpdir directory. | | String | *camel.main.streamCachingSpool{zwsp}Threshold* | Stream caching threshold in bytes when overflow to disk is activated. The default threshold is 128kb. Use -1 to disable overflow to disk. | | long | *camel.main.streamCachingSpool{zwsp}UsedHeapMemoryLimit* | Sets what the upper bounds should be when streamCachingSpoolUsedHeapMemoryThreshold is in use. | | String | *camel.main.streamCachingSpool{zwsp}UsedHeapMemoryThreshold* | Sets a percentage (1-99) of used heap memory threshold to activate stream caching spooling to disk. | | int | *camel.main.streamCaching{zwsp}StatisticsEnabled* | Sets whether stream caching statistics is enabled. | | boolean | *camel.main.threadNamePattern* | Sets the thread name pattern used for creating the full thread name. The default pattern is: Camel (#camelId#) thread ##counter# - #name# Where #camelId# is the name of the CamelContext. and #counter# is a unique incrementing counter. and #name# is the regular thread name. You can also use #longName# which is the long thread name which can includes endpoint parameters etc. | | String | *camel.main.tracing* | Sets whether tracing is enabled or not. Default is false. | | boolean | *camel.main.tracingPattern* | Tracing pattern to match which node EIPs to trace. For example to match all To EIP nodes, use to. The pattern matches by node and route id's Multiple patterns can be separated by comma. | | String | *camel.main.useBreadcrumb* | Set whether breadcrumb is enabled. The default value is false. | | boolean | *camel.main.useDataType* | Whether to enable using data type on Camel messages. Data type are automatic turned on if one ore more routes has been explicit configured with input and output types. Otherwise data type is default off. | | boolean | *camel.main.useMdcLogging* | To turn on MDC logging | | boolean | *camel.main.xmlRests* | Directory to scan for adding additional XML rests. You can turn this off by setting the value to false. Files can be loaded from either classpath or file by prefixing with classpath: or file: Wildcards is supported using a ANT pattern style paths, such as classpath:**/*camel*.xml Notice when using wildcards, then there is additional overhead as the classpath is scanned, where as if you specific the exact name for each XML file is faster as no classpath scanning is needed. Multiple directories can be specified and separated by comma, such as: file:/myapp/mycamel/*.xml,file:/myapp/myothercamel/*.xml | classpath:camel-rest/*.xml | String | *camel.main.xmlRoutes* | Directory to scan for adding additional XML routes. You can turn this off by setting the value to false. Files can be loaded from either classpath or file by prefixing with classpath: or file: Wildcards is supported using a ANT pattern style paths, such as classpath:**/*camel*.xml Notice when using wildcards, then there is additional overhead as the classpath is scanned, where as if you specific the exact name for each XML file is faster as no classpath scanning is needed. Multiple directories can be specified and separated by comma, such as: file:/myapp/mycamel/*.xml,file:/myapp/myothercamel/*.xml | classpath:camel/*.xml | String | *camel.main.xmlRouteTemplates* | Directory to scan for adding additional XML route templates. You can turn this off by setting the value to false. Files can be loaded from either classpath or file by prefixing with classpath: or file: Wildcards is supported using a ANT pattern style paths, such as classpath:**/*template-*.xml Notice when using wildcards, then there is additional overhead as the classpath is scanned, where as if you specific the exact name for each XML file is faster as no classpath scanning is needed. Multiple directories can be specified and separated by comma, such as: file:/myapp/mycamel/*.xml,file:/myapp/myothercamel/*.xml | classpath:camel-template/*.xml | String | *camel.faulttolerance.bulkhead{zwsp}Enabled* | Whether bulkhead is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.faulttolerance.bulkhead{zwsp}ExecutorServiceRef* | References to a custom thread pool to use when bulkhead is enabled. | | String | *camel.faulttolerance.bulkhead{zwsp}MaxConcurrentCalls* | Configures the max amount of concurrent calls the bulkhead will support. Default value is 10. | 10 | Integer | *camel.faulttolerance.bulkhead{zwsp}WaitingTaskQueue* | Configures the task queue size for holding waiting tasks to be processed by the bulkhead. Default value is 10. | 10 | Integer | *camel.faulttolerance.circuit{zwsp}BreakerRef* | Refers to an existing io.smallrye.faulttolerance.core.circuit.breaker.CircuitBreaker instance to lookup and use from the registry. When using this, then any other circuit breaker options are not in use. | | String | *camel.faulttolerance.delay* | Control how long the circuit breaker stays open. The value are in seconds and the default is 5 seconds. | 5 | Long | *camel.faulttolerance.failure{zwsp}Ratio* | Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. | 50 | Integer | *camel.faulttolerance.request{zwsp}VolumeThreshold* | Controls the size of the rolling window used when the circuit breaker is closed Default value is 20. | 20 | Integer | *camel.faulttolerance.success{zwsp}Threshold* | Controls the number of trial calls which are allowed when the circuit breaker is half-open Default value is 1. | 1 | Integer | *camel.faulttolerance.timeout{zwsp}Duration* | Configures the thread execution timeout. Default value is 1000 milliseconds. | 1000 | Long | *camel.faulttolerance.timeout{zwsp}Enabled* | Whether timeout is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.faulttolerance.timeout{zwsp}PoolSize* | Configures the pool size of the thread pool when timeout is enabled. Default value is 10. | 10 | Integer | *camel.faulttolerance.timeout{zwsp}ScheduledExecutorServiceRef* | References to a custom thread pool to use when timeout is enabled | | String | *camel.health.config* | Set additional HealthConfigurationProperties for fine grained configuration of health checks. | | Map | *camel.health.contextEnabled* | Whether context health check is enabled | true | Boolean | *camel.health.enabled* | Whether health check is enabled globally | true | Boolean | *camel.health.registryEnabled* | Whether registry health check is enabled | true | Boolean | *camel.health.routesEnabled* | Whether routes health check is enabled | true | Boolean | *camel.hystrix.allowMaximumSize{zwsp}ToDivergeFromCoreSize* | Allows the configuration for maximumSize to take effect. That value can then be equal to, or higher, than coreSize | | Boolean | *camel.hystrix.circuitBreaker{zwsp}Enabled* | Whether to use a HystrixCircuitBreaker or not. If false no circuit-breaker logic will be used and all requests permitted. This is similar in effect to circuitBreakerForceClosed() except that continues tracking metrics and knowing whether it should be open/closed, this property results in not even instantiating a circuit-breaker. | | Boolean | *camel.hystrix.circuitBreaker{zwsp}ErrorThresholdPercentage* | Error percentage threshold (as whole number such as 50) at which point the circuit breaker will trip open and reject requests. It will stay tripped for the duration defined in circuitBreakerSleepWindowInMilliseconds; The error percentage this is compared against comes from HystrixCommandMetrics.getHealthCounts(). | | Integer | *camel.hystrix.circuitBreaker{zwsp}ForceClosed* | If true the HystrixCircuitBreaker#allowRequest() will always return true to allow requests regardless of the error percentage from HystrixCommandMetrics.getHealthCounts(). The circuitBreakerForceOpen() property takes precedence so if it set to true this property does nothing. | | Boolean | *camel.hystrix.circuitBreaker{zwsp}ForceOpen* | If true the HystrixCircuitBreaker.allowRequest() will always return false, causing the circuit to be open (tripped) and reject all requests. This property takes precedence over circuitBreakerForceClosed(); | | Boolean | *camel.hystrix.circuitBreaker{zwsp}RequestVolumeThreshold* | Minimum number of requests in the metricsRollingStatisticalWindowInMilliseconds() that must exist before the HystrixCircuitBreaker will trip. If below this number the circuit will not trip regardless of error percentage. | | Integer | *camel.hystrix.circuitBreaker{zwsp}SleepWindowInMilliseconds* | The time in milliseconds after a HystrixCircuitBreaker trips open that it should wait before trying requests again. | | Integer | *camel.hystrix.corePoolSize* | Core thread-pool size that gets passed to java.util.concurrent.ThreadPoolExecutor#setCorePoolSize(int) | | Integer | *camel.hystrix.execution{zwsp}IsolationSemaphoreMax{zwsp}ConcurrentRequests* | Number of concurrent requests permitted to HystrixCommand.run(). Requests beyond the concurrent limit will be rejected. Applicable only when executionIsolationStrategy == SEMAPHORE. | | Integer | *camel.hystrix.execution{zwsp}IsolationStrategy* | What isolation strategy HystrixCommand.run() will be executed with. If THREAD then it will be executed on a separate thread and concurrent requests limited by the number of threads in the thread-pool. If SEMAPHORE then it will be executed on the calling thread and concurrent requests limited by the semaphore count. | | String | *camel.hystrix.execution{zwsp}IsolationThreadInterruptOn{zwsp}Timeout* | Whether the execution thread should attempt an interrupt (using Future#cancel ) when a thread times out. Applicable only when executionIsolationStrategy() == THREAD. | | Boolean | *camel.hystrix.executionTimeout{zwsp}Enabled* | Whether the timeout mechanism is enabled for this command | | Boolean | *camel.hystrix.executionTimeout{zwsp}InMilliseconds* | Time in milliseconds at which point the command will timeout and halt execution. If executionIsolationThreadInterruptOnTimeout == true and the command is thread-isolated, the executing thread will be interrupted. If the command is semaphore-isolated and a HystrixObservableCommand, that command will get unsubscribed. | | Integer | *camel.hystrix.fallbackEnabled* | Whether HystrixCommand.getFallback() should be attempted when failure occurs. | | Boolean | *camel.hystrix.fallback{zwsp}IsolationSemaphoreMax{zwsp}ConcurrentRequests* | Number of concurrent requests permitted to HystrixCommand.getFallback(). Requests beyond the concurrent limit will fail-fast and not attempt retrieving a fallback. | | Integer | *camel.hystrix.groupKey* | Sets the group key to use. The default value is CamelHystrix. | | String | *camel.hystrix.keepAliveTime* | Keep-alive time in minutes that gets passed to ThreadPoolExecutor#setKeepAliveTime(long,TimeUnit) | | Integer | *camel.hystrix.maximumSize* | Maximum thread-pool size that gets passed to ThreadPoolExecutor#setMaximumPoolSize(int) . This is the maximum amount of concurrency that can be supported without starting to reject HystrixCommands. Please note that this setting only takes effect if you also set allowMaximumSizeToDivergeFromCoreSize | | Integer | *camel.hystrix.maxQueueSize* | Max queue size that gets passed to BlockingQueue in HystrixConcurrencyStrategy.getBlockingQueue(int) This should only affect the instantiation of a threadpool - it is not eliglible to change a queue size on the fly. For that, use queueSizeRejectionThreshold(). | | Integer | *camel.hystrix.metricsHealth{zwsp}SnapshotIntervalInMilliseconds* | Time in milliseconds to wait between allowing health snapshots to be taken that calculate success and error percentages and affect HystrixCircuitBreaker.isOpen() status. On high-volume circuits the continual calculation of error percentage can become CPU intensive thus this controls how often it is calculated. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileBucketSize* | Maximum number of values stored in each bucket of the rolling percentile. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileEnabled* | Whether percentile metrics should be captured using HystrixRollingPercentile inside HystrixCommandMetrics. | | Boolean | *camel.hystrix.metricsRolling{zwsp}PercentileWindowBuckets* | Number of buckets the rolling percentile window is broken into. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}PercentileWindowInMilliseconds* | Duration of percentile rolling window in milliseconds. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}StatisticalWindowBuckets* | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside HystrixCommandMetrics. | | Integer | *camel.hystrix.metricsRolling{zwsp}StatisticalWindowIn{zwsp}Milliseconds* | This property sets the duration of the statistical rolling window, in milliseconds. This is how long metrics are kept for the thread pool. The window is divided into buckets and rolls by those increments. | | Integer | *camel.hystrix.queueSize{zwsp}RejectionThreshold* | Queue size rejection threshold is an artificial max size at which rejections will occur even if maxQueueSize has not been reached. This is done because the maxQueueSize of a BlockingQueue can not be dynamically changed and we want to support dynamically changing the queue size that affects rejections. This is used by HystrixCommand when queuing a thread for execution. | | Integer | *camel.hystrix.requestLog{zwsp}Enabled* | Whether HystrixCommand execution and events should be logged to HystrixRequestLog. | | Boolean | *camel.hystrix.threadPoolKey* | Sets the thread pool key to use. Will by default use the same value as groupKey has been configured to use. | | String | *camel.hystrix.threadPool{zwsp}RollingNumberStatisticalWindow{zwsp}Buckets* | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | | Integer | *camel.hystrix.threadPool{zwsp}RollingNumberStatisticalWindow{zwsp}InMilliseconds* | Duration of statistical rolling window in milliseconds. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | | Integer | *camel.lra.coordinatorContext{zwsp}Path* | The context-path for the LRA coordinator. Is default /lra-coordinator | /lra-coordinator | String | *camel.lra.coordinatorUrl* | The URL for the LRA coordinator service that orchestrates the transactions | | String | *camel.lra.localParticipant{zwsp}ContextPath* | The context-path for the local participant. Is default /lra-participant | /lra-participant | String | *camel.lra.localParticipantUrl* | The URL for the local participant | | String | *camel.resilience4j.automatic{zwsp}TransitionFromOpenToHalfOpen{zwsp}Enabled* | Enables automatic transition from OPEN to HALF_OPEN state once the waitDurationInOpenState has passed. | | Boolean | *camel.resilience4j.bulkhead{zwsp}Enabled* | Whether bulkhead is enabled or not on the circuit breaker. | false | Boolean | *camel.resilience4j.bulkheadMax{zwsp}ConcurrentCalls* | Configures the max amount of concurrent calls the bulkhead will support. | | Integer | *camel.resilience4j.bulkheadMax{zwsp}WaitDuration* | Configures a maximum amount of time which the calling thread will wait to enter the bulkhead. If bulkhead has space available, entry is guaranteed and immediate. If bulkhead is full, calling threads will contest for space, if it becomes available. maxWaitDuration can be set to 0. Note: for threads running on an event-loop or equivalent (rx computation pool, etc), setting maxWaitDuration to 0 is highly recommended. Blocking an event-loop thread will most likely have a negative effect on application throughput. | | Integer | *camel.resilience4j.circuit{zwsp}BreakerRef* | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreaker instance to lookup and use from the registry. When using this, then any other circuit breaker options are not in use. | | String | *camel.resilience4j.configRef* | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreakerConfig instance to lookup and use from the registry. | | String | *camel.resilience4j.failureRate{zwsp}Threshold* | Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. | 50 | Float | *camel.resilience4j.minimum{zwsp}NumberOfCalls* | Configures configures the minimum number of calls which are required (per sliding window period) before the CircuitBreaker can calculate the error rate. For example, if minimumNumberOfCalls is 10, then at least 10 calls must be recorded, before the failure rate can be calculated. If only 9 calls have been recorded the CircuitBreaker will not transition to open even if all 9 calls have failed. Default minimumNumberOfCalls is 100 | 100 | Integer | *camel.resilience4j.permitted{zwsp}NumberOfCallsInHalfOpenState* | Configures the number of permitted calls when the CircuitBreaker is half open. The size must be greater than 0. Default size is 10. | 10 | Integer | *camel.resilience4j.sliding{zwsp}WindowSize* | Configures the size of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. slidingWindowSize configures the size of the sliding window. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. The slidingWindowSize must be greater than 0. The minimumNumberOfCalls must be greater than 0. If the slidingWindowType is COUNT_BASED, the minimumNumberOfCalls cannot be greater than slidingWindowSize . If the slidingWindowType is TIME_BASED, you can pick whatever you want. Default slidingWindowSize is 100. | 100 | Integer | *camel.resilience4j.sliding{zwsp}WindowType* | Configures the type of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. Default slidingWindowType is COUNT_BASED. | COUNT_BASED | String | *camel.resilience4j.slowCall{zwsp}DurationThreshold* | Configures the duration threshold (seconds) above which calls are considered as slow and increase the slow calls percentage. Default value is 60 seconds. | 60 | Integer | *camel.resilience4j.slowCall{zwsp}RateThreshold* | Configures a threshold in percentage. The CircuitBreaker considers a call as slow when the call duration is greater than slowCallDurationThreshold(Duration. When the percentage of slow calls is equal or greater the threshold, the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 100 percentage which means that all recorded calls must be slower than slowCallDurationThreshold. | 100 | Float | *camel.resilience4j.timeout{zwsp}CancelRunningFuture* | Configures whether cancel is called on the running future. Defaults to true. | true | Boolean | *camel.resilience4j.timeout{zwsp}Duration* | Configures the thread execution timeout (millis). Default value is 1000 millis (1 second). | 1000 | Integer | *camel.resilience4j.timeout{zwsp}Enabled* | Whether timeout is enabled or not on the circuit breaker. Default is false. | false | Boolean | *camel.resilience4j.timeout{zwsp}ExecutorServiceRef* | References to a custom thread pool to use when timeout is enabled (uses ForkJoinPool#commonPool() by default) | | String | *camel.resilience4j.wait{zwsp}DurationInOpenState* | Configures the wait duration (in seconds) which specifies how long the CircuitBreaker should stay open, before it switches to half open. Default value is 60 seconds. | 60 | Integer | *camel.resilience4j.writable{zwsp}StackTraceEnabled* | Enables writable stack traces. When set to false, Exception.getStackTrace returns a zero length array. This may be used to reduce log spam when the circuit breaker is open as the cause of the exceptions is already known (the circuit breaker is short-circuiting calls). | | Boolean | *camel.rest.apiComponent* | Sets the name of the Camel component to use as the REST API (such as swagger or openapi) | | String | *camel.rest.apiContextIdPattern* | Optional CamelContext id pattern to only allow Rest APIs from rest services within CamelContext's which name matches the pattern. The pattern #name# refers to the CamelContext name, to match on the current CamelContext only. For any other value, the pattern uses the rules from org.apache.camel.support.EndpointHelper#matchPattern(String,String) | | String | *camel.rest.apiContextListing* | Sets whether listing of all available CamelContext's with REST services in the JVM is enabled. If enabled it allows to discover these contexts, if false then only the current CamelContext is in use. | | boolean | *camel.rest.apiContextPath* | Sets a leading API context-path the REST API services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. | | String | *camel.rest.apiContextRouteId* | Sets the route id to use for the route that services the REST API. The route will by default use an auto assigned route id. | | String | *camel.rest.apiHost* | To use an specific hostname for the API documentation (eg swagger) This can be used to override the generated host with this configured hostname | | String | *camel.rest.apiProperties* | Sets additional options on api level | | Map | *camel.rest.apiVendorExtension* | Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information as vendor extension (eg keys starting with x-) such as route ids, class names etc. Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. | | boolean | *camel.rest.bindingMode* | Sets the binding mode to be used by the REST consumer | RestBindingMode.off | RestBindingMode | *camel.rest.clientRequest{zwsp}Validation* | Whether to enable validation of the client request to check whether the Content-Type and Accept headers from the client is supported by the Rest-DSL configuration of its consumes/produces settings. This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. The default value is false. | | boolean | *camel.rest.component* | Sets the name of the Camel component to use as the REST consumer | | String | *camel.rest.componentProperties* | Sets additional options on component level | | Map | *camel.rest.consumerProperties* | Sets additional options on consumer level | | Map | *camel.rest.contextPath* | Sets a leading context-path the REST services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. Or for components such as camel-jetty or camel-netty-http that includes a HTTP server. | | String | *camel.rest.corsHeaders* | Sets the CORS headers to use if CORS has been enabled. | | Map | *camel.rest.dataFormat{zwsp}Properties* | Sets additional options on data format level | | Map | *camel.rest.enableCORS* | To specify whether to enable CORS which means Camel will automatic include CORS in the HTTP headers in the response. This option is default false | | boolean | *camel.rest.endpointProperties* | Sets additional options on endpoint level | | Map | *camel.rest.host* | Sets the hostname to use by the REST consumer | | String | *camel.rest.hostNameResolver* | Sets the resolver to use for resolving hostname | RestHostNameResolver.allLocalIp | RestHostNameResolver | *camel.rest.jsonDataFormat* | Sets a custom json data format to be used Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | | String | *camel.rest.port* | Sets the port to use by the REST consumer | | int | *camel.rest.producerApiDoc* | Sets the location of the api document (swagger api) the REST producer will use to validate the REST uri and query parameters are valid accordingly to the api document. This requires adding camel-swagger-java to the classpath, and any miss configuration will let Camel fail on startup and report the error(s). The location of the api document is loaded from classpath by default, but you can use file: or http: to refer to resources to load from file or http url. | | String | *camel.rest.producerComponent* | Sets the name of the Camel component to use as the REST producer | | String | *camel.rest.scheme* | Sets the scheme to use by the REST consumer | | String | *camel.rest.skipBindingOnError{zwsp}Code* | Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. This option is default true. | true | boolean | *camel.rest.useXForwardHeaders* | WWhether to use X-Forward headers to set host etc. for Swagger. This option is default true. | true | boolean | *camel.rest.xmlDataFormat* | Sets a custom xml data format to be used. Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | | String | *camel.threadpool.allowCore{zwsp}ThreadTimeOut* | Sets default whether to allow core threads to timeout | | Boolean | *camel.threadpool.config* | Adds a configuration for a specific thread pool profile (inherits default values) | | Map | *camel.threadpool.keepAliveTime* | Sets the default keep alive time for inactive threads | | Long | *camel.threadpool.maxPoolSize* | Sets the default maximum pool size | | Integer | *camel.threadpool.maxQueueSize* | Sets the default maximum number of tasks in the work queue. Use -1 or an unbounded queue | | Integer | *camel.threadpool.poolSize* | Sets the default core pool size (threads to keep minimum in pool) | | Integer | *camel.threadpool.rejected{zwsp}Policy* | Sets the default handler for tasks which cannot be executed by the thread pool. | | ThreadPoolRejectedPolicy | *camel.threadpool.timeUnit* | Sets the default time unit used for keep alive time | | TimeUnit |=== // main options: END == Specifying custom beans Custom beans can be configured in `camel-main` via properties (such as in the `application.properties` file). For example to create a `DataSource` for a Postgress database, you can create a new bean instance via `#class:` with the class name (fully qualified). Properties on the data source can then additional configured such as the server and database name, etc. [source,properties] ---- camel.beans.myDS = #class:org.postgresql.jdbc3.Jdbc3PoolingDataSource camel.beans.myDS.dataSourceName = myDS camel.beans.myDS.serverName = mypostrgress camel.beans.myDS.databaseName = test camel.beans.myDS.user = testuser camel.beans.myDS.password = testpassword camel.beans.myDS.maxConnections = 10 ---- The bean is registered in the Camel Registry with the name `myDS`. If you use the SQL component then the datasource can be configured on the SQL component: [source,properties] ---- camel.component.sql.dataSource = #myDS ---- To refer to a custom bean you may want to favour using `#bean:` style, as this states the intention more clearly that its referring to a bean, and not just a text value that happens to start with a `#` sign: [source,properties] ---- camel.component.sql.dataSource = #bean:myDS ---- === Creating a custom bean with constructor parameters When creating a bean then parameters to the constructor can be provided. Suppose we have a class `MyFoo` with a constructor: [source,java] ---- public class MyFoo { private String name; private boolean important; private int id; public MyFoo(String name, boolean important, int id) { this.name = name; this.important = important; this.id = id; } } ---- Then we can create a bean instance with name `foo` and provide parameters to the constructor as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) ---- === Optional parameters on beans If a parameter on a bean is not mandatory then the parameter can be marked as optional using `?` syntax, as shown: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) camel.beans.foo.?company = Acme ---- Then the company parameter is only set if `MyBean` has this option (silent ignore if no option present). Otherwise if a parameter is set and the bean does not have such a parameter, then an exception is thrown by Camel. === Nested parameters on beans You can configure nested parameters separating them via `.` (dot). For example given this `Country` class: [source,java] ---- public class Country { private String iso; private String name; public void setIso(String iso) { this.iso = iso; } public void setName(String name) { this.name = name; } } ---- Which is an option on the `MyBean` class. Then we can then configure its iso and name parameter as shown below: [source,properties] ---- camel.beans.foo = #class:com.foo.MyBean(""Hello World"", true, 123) camel.beans.foo.country.iso = USA camel.beans.foo.country.name = United States of America ---- Camel will automatic create an instance of `Country` if `MyBean` has a getter/setter for this option, and that the `Country` bean has a default no-arg constructor. === Configuring singleton beans by their type In the example above the SQL component was configured with the name of the `DataSource`. There can be situations where you know there is only a single instance of a data source in the Camel registry. In such a situation you can instead refer to the class or interface type via the `#type:` prefix as shown below: [source,properties] ---- camel.component.sql.dataSource = #type:javax.sql.DataSource ---- If there is no bean in the registry with the type `javax.sql.DataSource` then the option isn't configured. === Autowiring beans The example above can be taken one step further by letting `camel-main` try to autowire the beans. [source,properties] ---- camel.component.sql.dataSource = #autowired ---- In this situation then `#autowrired` will make Camel detect the type of the `dataSource` option on the `SQL` component. As the type is a `javax.sql.DataSource` instance, then Camel will lookup in the registry if there is a single instance of the same type. If there is no such bean then the option isn't configured. == Defining a Map bean You can specify `java.util.Map` beans in `camel-main` via properties (such as in the `application.properties` file). Maps have a special syntax with brackets as shown below: [source,properties] ---- camel.beans.mymap[table] = 12 camel.beans.mymap[food] = Big Burger camel.beans.mymap[cheese] = yes camel.beans.mymap[quantity] = 1 ---- The Map is registered in the Camel Registry with the name `mymap`. == Defining a List bean This is similar to Map bean where the key is the index, eg 0, 1, 2, etc: [source,properties] ---- camel.beans.myprojects[0] = Camel camel.beans.myprojects[1] = Kafka camel.beans.myprojects[2] = Quarkus ---- The List is registered in the Camel Registry with the name `myprojects`. == Examples You can find a set of examples using `camel-main` in https://github.com/apache/camel-examples[Camel Examples] which demonstrate running Camel in standalone with `camel-main`. ",12273,False,2181.746043847497,median "// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include #include #include #ifndef WIN32 #include #include #include #endif #include BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(util_criticalsection) { CCriticalSection cs; do { LOCK(cs); break; BOOST_ERROR(""break was swallowed!""); } while(0); do { TRY_LOCK(cs, lockTest); if (lockTest) break; BOOST_ERROR(""break was swallowed!""); } while(0); } static const unsigned char ParseHex_expected[65] = { 0x04, 0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, 0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7, 0x10, 0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, 0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde, 0xb6, 0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, 0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12, 0xde, 0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, 0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d, 0x5f }; BOOST_AUTO_TEST_CASE(util_ParseHex) { std::vector result; std::vector expected(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected)); // Basic test vector result = ParseHex(""04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f""); BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end()); // Spaces between bytes must be supported result = ParseHex(""12 34 56 78""); BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78); // Leading space must be supported (used in BerkeleyEnvironment::Salvage) result = ParseHex("" 89 34 56 78""); BOOST_CHECK(result.size() == 4 && result[0] == 0x89 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78); // Stop parsing at invalid value result = ParseHex(""1234 invalid 1234""); BOOST_CHECK(result.size() == 2 && result[0] == 0x12 && result[1] == 0x34); } BOOST_AUTO_TEST_CASE(util_HexStr) { BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected)), ""04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f""); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected + 5, true), ""04 67 8a fd b0""); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected + sizeof(ParseHex_expected), ParseHex_expected + sizeof(ParseHex_expected)), """"); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected + sizeof(ParseHex_expected), ParseHex_expected + sizeof(ParseHex_expected), true), """"); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected), """"); BOOST_CHECK_EQUAL( HexStr(ParseHex_expected, ParseHex_expected, true), """"); std::vector ParseHex_vec(ParseHex_expected, ParseHex_expected + 5); BOOST_CHECK_EQUAL( HexStr(ParseHex_vec, true), ""04 67 8a fd b0""); BOOST_CHECK_EQUAL( HexStr(ParseHex_vec.rbegin(), ParseHex_vec.rend()), ""b0fd8a6704"" ); BOOST_CHECK_EQUAL( HexStr(ParseHex_vec.rbegin(), ParseHex_vec.rend(), true), ""b0 fd 8a 67 04"" ); BOOST_CHECK_EQUAL( HexStr(std::reverse_iterator(ParseHex_expected), std::reverse_iterator(ParseHex_expected)), """" ); BOOST_CHECK_EQUAL( HexStr(std::reverse_iterator(ParseHex_expected), std::reverse_iterator(ParseHex_expected), true), """" ); BOOST_CHECK_EQUAL( HexStr(std::reverse_iterator(ParseHex_expected + 1), std::reverse_iterator(ParseHex_expected)), ""04"" ); BOOST_CHECK_EQUAL( HexStr(std::reverse_iterator(ParseHex_expected + 1), std::reverse_iterator(ParseHex_expected), true), ""04"" ); BOOST_CHECK_EQUAL( HexStr(std::reverse_iterator(ParseHex_expected + 5), std::reverse_iterator(ParseHex_expected)), ""b0fd8a6704"" ); BOOST_CHECK_EQUAL( HexStr(std::reverse_iterator(ParseHex_expected + 5), std::reverse_iterator(ParseHex_expected), true), ""b0 fd 8a 67 04"" ); BOOST_CHECK_EQUAL( HexStr(std::reverse_iterator(ParseHex_expected + 65), std::reverse_iterator(ParseHex_expected)), ""5f1df16b2b704c8a578d0bbaf74d385cde12c11ee50455f3c438ef4c3fbcf649b6de611feae06279a60939e028a8d65c10b73071a6f16719274855feb0fd8a6704"" ); } BOOST_AUTO_TEST_CASE(util_FormatISO8601DateTime) { BOOST_CHECK_EQUAL(FormatISO8601DateTime(1317425777), ""2011-09-30T23:36:17Z""); } BOOST_AUTO_TEST_CASE(util_FormatISO8601Date) { BOOST_CHECK_EQUAL(FormatISO8601Date(1317425777), ""2011-09-30""); } BOOST_AUTO_TEST_CASE(util_FormatISO8601Time) { BOOST_CHECK_EQUAL(FormatISO8601Time(1317425777), ""23:36:17Z""); } struct TestArgsManager : public ArgsManager { TestArgsManager() { m_network_only_args.clear(); } std::map >& GetOverrideArgs() { return m_override_args; } std::map >& GetConfigArgs() { return m_config_args; } void ReadConfigString(const std::string str_config) { std::istringstream streamConfig(str_config); { LOCK(cs_args); m_config_args.clear(); } ReadConfigStream(streamConfig); } void SetNetworkOnlyArg(const std::string arg) { LOCK(cs_args); m_network_only_args.insert(arg); } }; BOOST_AUTO_TEST_CASE(util_ParseParameters) { TestArgsManager testArgs; const char *argv_test[] = {""-ignored"", ""-a"", ""-b"", ""-ccc=argument"", ""-ccc=multiple"", ""f"", ""-d=e""}; testArgs.ParseParameters(0, (char**)argv_test); BOOST_CHECK(testArgs.GetOverrideArgs().empty() && testArgs.GetConfigArgs().empty()); testArgs.ParseParameters(1, (char**)argv_test); BOOST_CHECK(testArgs.GetOverrideArgs().empty() && testArgs.GetConfigArgs().empty()); testArgs.ParseParameters(7, (char**)argv_test); // expectation: -ignored is ignored (program name argument), // -a, -b and -ccc end up in map, -d ignored because it is after // a non-option argument (non-GNU option parsing) BOOST_CHECK(testArgs.GetOverrideArgs().size() == 3 && testArgs.GetConfigArgs().empty()); BOOST_CHECK(testArgs.IsArgSet(""-a"") && testArgs.IsArgSet(""-b"") && testArgs.IsArgSet(""-ccc"") && !testArgs.IsArgSet(""f"") && !testArgs.IsArgSet(""-d"")); BOOST_CHECK(testArgs.GetOverrideArgs().count(""-a"") && testArgs.GetOverrideArgs().count(""-b"") && testArgs.GetOverrideArgs().count(""-ccc"") && !testArgs.GetOverrideArgs().count(""f"") && !testArgs.GetOverrideArgs().count(""-d"")); BOOST_CHECK(testArgs.GetOverrideArgs()[""-a""].size() == 1); BOOST_CHECK(testArgs.GetOverrideArgs()[""-a""].front() == """"); BOOST_CHECK(testArgs.GetOverrideArgs()[""-ccc""].size() == 2); BOOST_CHECK(testArgs.GetOverrideArgs()[""-ccc""].front() == ""argument""); BOOST_CHECK(testArgs.GetOverrideArgs()[""-ccc""].back() == ""multiple""); BOOST_CHECK(testArgs.GetArgs(""-ccc"").size() == 2); } BOOST_AUTO_TEST_CASE(util_GetBoolArg) { TestArgsManager testArgs; const char *argv_test[] = { ""ignored"", ""-a"", ""-nob"", ""-c=0"", ""-d=1"", ""-e=false"", ""-f=true""}; testArgs.ParseParameters(7, (char**)argv_test); // Each letter should be set. for (char opt : ""abcdef"") BOOST_CHECK(testArgs.IsArgSet({'-', opt}) || !opt); // Nothing else should be in the map BOOST_CHECK(testArgs.GetOverrideArgs().size() == 6 && testArgs.GetConfigArgs().empty()); // The -no prefix should get stripped on the way in. BOOST_CHECK(!testArgs.IsArgSet(""-nob"")); // The -b option is flagged as negated, and nothing else is BOOST_CHECK(testArgs.IsArgNegated(""-b"")); BOOST_CHECK(!testArgs.IsArgNegated(""-a"")); // Check expected values. BOOST_CHECK(testArgs.GetBoolArg(""-a"", false) == true); BOOST_CHECK(testArgs.GetBoolArg(""-b"", true) == false); BOOST_CHECK(testArgs.GetBoolArg(""-c"", true) == false); BOOST_CHECK(testArgs.GetBoolArg(""-d"", false) == true); BOOST_CHECK(testArgs.GetBoolArg(""-e"", true) == false); BOOST_CHECK(testArgs.GetBoolArg(""-f"", true) == false); } BOOST_AUTO_TEST_CASE(util_GetBoolArgEdgeCases) { // Test some awful edge cases that hopefully no user will ever exercise. TestArgsManager testArgs; // Params test const char *argv_test[] = {""ignored"", ""-nofoo"", ""-foo"", ""-nobar=0""}; testArgs.ParseParameters(4, (char**)argv_test); // This was passed twice, second one overrides the negative setting. BOOST_CHECK(!testArgs.IsArgNegated(""-foo"")); BOOST_CHECK(testArgs.GetArg(""-foo"", ""xxx"") == """"); // A double negative is a positive, and not marked as negated. BOOST_CHECK(!testArgs.IsArgNegated(""-bar"")); BOOST_CHECK(testArgs.GetArg(""-bar"", ""xxx"") == ""1""); // Config test const char *conf_test = ""nofoo=1\\nfoo=1\\nnobar=0\\n""; testArgs.ParseParameters(1, (char**)argv_test); testArgs.ReadConfigString(conf_test); // This was passed twice, second one overrides the negative setting, // and the value. BOOST_CHECK(!testArgs.IsArgNegated(""-foo"")); BOOST_CHECK(testArgs.GetArg(""-foo"", ""xxx"") == ""1""); // A double negative is a positive, and does not count as negated. BOOST_CHECK(!testArgs.IsArgNegated(""-bar"")); BOOST_CHECK(testArgs.GetArg(""-bar"", ""xxx"") == ""1""); // Combined test const char *combo_test_args[] = {""ignored"", ""-nofoo"", ""-bar""}; const char *combo_test_conf = ""foo=1\\nnobar=1\\n""; testArgs.ParseParameters(3, (char**)combo_test_args); testArgs.ReadConfigString(combo_test_conf); // Command line overrides, but doesn't erase old setting BOOST_CHECK(testArgs.IsArgNegated(""-foo"")); BOOST_CHECK(testArgs.GetArg(""-foo"", ""xxx"") == ""0""); BOOST_CHECK(testArgs.GetArgs(""-foo"").size() == 0); // Command line overrides, but doesn't erase old setting BOOST_CHECK(!testArgs.IsArgNegated(""-bar"")); BOOST_CHECK(testArgs.GetArg(""-bar"", ""xxx"") == """"); BOOST_CHECK(testArgs.GetArgs(""-bar"").size() == 1 && testArgs.GetArgs(""-bar"").front() == """"); } BOOST_AUTO_TEST_CASE(util_ReadConfigStream) { const char *str_config = ""a=\\n"" ""b=1\\n"" ""ccc=argument\\n"" ""ccc=multiple\\n"" ""d=e\\n"" ""nofff=1\\n"" ""noggg=0\\n"" ""h=1\\n"" ""noh=1\\n"" ""noi=1\\n"" ""i=1\\n"" ""sec1.ccc=extend1\\n"" ""\\n"" ""[sec1]\\n"" ""ccc=extend2\\n"" ""d=eee\\n"" ""h=1\\n"" ""[sec2]\\n"" ""ccc=extend3\\n"" ""iii=2\\n""; TestArgsManager test_args; test_args.ReadConfigString(str_config); // expectation: a, b, ccc, d, fff, ggg, h, i end up in map // so do sec1.ccc, sec1.d, sec1.h, sec2.ccc, sec2.iii BOOST_CHECK(test_args.GetOverrideArgs().empty()); BOOST_CHECK(test_args.GetConfigArgs().size() == 13); BOOST_CHECK(test_args.GetConfigArgs().count(""-a"") && test_args.GetConfigArgs().count(""-b"") && test_args.GetConfigArgs().count(""-ccc"") && test_args.GetConfigArgs().count(""-d"") && test_args.GetConfigArgs().count(""-fff"") && test_args.GetConfigArgs().count(""-ggg"") && test_args.GetConfigArgs().count(""-h"") && test_args.GetConfigArgs().count(""-i"") ); BOOST_CHECK(test_args.GetConfigArgs().count(""-sec1.ccc"") && test_args.GetConfigArgs().count(""-sec1.h"") && test_args.GetConfigArgs().count(""-sec2.ccc"") && test_args.GetConfigArgs().count(""-sec2.iii"") ); BOOST_CHECK(test_args.IsArgSet(""-a"") && test_args.IsArgSet(""-b"") && test_args.IsArgSet(""-ccc"") && test_args.IsArgSet(""-d"") && test_args.IsArgSet(""-fff"") && test_args.IsArgSet(""-ggg"") && test_args.IsArgSet(""-h"") && test_args.IsArgSet(""-i"") && !test_args.IsArgSet(""-zzz"") && !test_args.IsArgSet(""-iii"") ); BOOST_CHECK(test_args.GetArg(""-a"", ""xxx"") == """" && test_args.GetArg(""-b"", ""xxx"") == ""1"" && test_args.GetArg(""-ccc"", ""xxx"") == ""argument"" && test_args.GetArg(""-d"", ""xxx"") == ""e"" && test_args.GetArg(""-fff"", ""xxx"") == ""0"" && test_args.GetArg(""-ggg"", ""xxx"") == ""1"" && test_args.GetArg(""-h"", ""xxx"") == ""0"" && test_args.GetArg(""-i"", ""xxx"") == ""1"" && test_args.GetArg(""-zzz"", ""xxx"") == ""xxx"" && test_args.GetArg(""-iii"", ""xxx"") == ""xxx"" ); for (bool def : {false, true}) { BOOST_CHECK(test_args.GetBoolArg(""-a"", def) && test_args.GetBoolArg(""-b"", def) && !test_args.GetBoolArg(""-ccc"", def) && !test_args.GetBoolArg(""-d"", def) && !test_args.GetBoolArg(""-fff"", def) && test_args.GetBoolArg(""-ggg"", def) && !test_args.GetBoolArg(""-h"", def) && test_args.GetBoolArg(""-i"", def) && test_args.GetBoolArg(""-zzz"", def) == def && test_args.GetBoolArg(""-iii"", def) == def ); } BOOST_CHECK(test_args.GetArgs(""-a"").size() == 1 && test_args.GetArgs(""-a"").front() == """"); BOOST_CHECK(test_args.GetArgs(""-b"").size() == 1 && test_args.GetArgs(""-b"").front() == ""1""); BOOST_CHECK(test_args.GetArgs(""-ccc"").size() == 2 && test_args.GetArgs(""-ccc"").front() == ""argument"" && test_args.GetArgs(""-ccc"").back() == ""multiple""); BOOST_CHECK(test_args.GetArgs(""-fff"").size() == 0); BOOST_CHECK(test_args.GetArgs(""-nofff"").size() == 0); BOOST_CHECK(test_args.GetArgs(""-ggg"").size() == 1 && test_args.GetArgs(""-ggg"").front() == ""1""); BOOST_CHECK(test_args.GetArgs(""-noggg"").size() == 0); BOOST_CHECK(test_args.GetArgs(""-h"").size() == 0); BOOST_CHECK(test_args.GetArgs(""-noh"").size() == 0); BOOST_CHECK(test_args.GetArgs(""-i"").size() == 1 && test_args.GetArgs(""-i"").front() == ""1""); BOOST_CHECK(test_args.GetArgs(""-noi"").size() == 0); BOOST_CHECK(test_args.GetArgs(""-zzz"").size() == 0); BOOST_CHECK(!test_args.IsArgNegated(""-a"")); BOOST_CHECK(!test_args.IsArgNegated(""-b"")); BOOST_CHECK(!test_args.IsArgNegated(""-ccc"")); BOOST_CHECK(!test_args.IsArgNegated(""-d"")); BOOST_CHECK(test_args.IsArgNegated(""-fff"")); BOOST_CHECK(!test_args.IsArgNegated(""-ggg"")); BOOST_CHECK(test_args.IsArgNegated(""-h"")); // last setting takes precedence BOOST_CHECK(!test_args.IsArgNegated(""-i"")); // last setting takes precedence BOOST_CHECK(!test_args.IsArgNegated(""-zzz"")); // Test sections work test_args.SelectConfigNetwork(""sec1""); // same as original BOOST_CHECK(test_args.GetArg(""-a"", ""xxx"") == """" && test_args.GetArg(""-b"", ""xxx"") == ""1"" && test_args.GetArg(""-fff"", ""xxx"") == ""0"" && test_args.GetArg(""-ggg"", ""xxx"") == ""1"" && test_args.GetArg(""-zzz"", ""xxx"") == ""xxx"" && test_args.GetArg(""-iii"", ""xxx"") == ""xxx"" ); // d is overridden BOOST_CHECK(test_args.GetArg(""-d"", ""xxx"") == ""eee""); // section-specific setting BOOST_CHECK(test_args.GetArg(""-h"", ""xxx"") == ""1""); // section takes priority for multiple values BOOST_CHECK(test_args.GetArg(""-ccc"", ""xxx"") == ""extend1""); // check multiple values works const std::vector sec1_ccc_expected = {""extend1"",""extend2"",""argument"",""multiple""}; const auto& sec1_ccc_res = test_args.GetArgs(""-ccc""); BOOST_CHECK_EQUAL_COLLECTIONS(sec1_ccc_res.begin(), sec1_ccc_res.end(), sec1_ccc_expected.begin(), sec1_ccc_expected.end()); test_args.SelectConfigNetwork(""sec2""); // same as original BOOST_CHECK(test_args.GetArg(""-a"", ""xxx"") == """" && test_args.GetArg(""-b"", ""xxx"") == ""1"" && test_args.GetArg(""-d"", ""xxx"") == ""e"" && test_args.GetArg(""-fff"", ""xxx"") == ""0"" && test_args.GetArg(""-ggg"", ""xxx"") == ""1"" && test_args.GetArg(""-zzz"", ""xxx"") == ""xxx"" && test_args.GetArg(""-h"", ""xxx"") == ""0"" ); // section-specific setting BOOST_CHECK(test_args.GetArg(""-iii"", ""xxx"") == ""2""); // section takes priority for multiple values BOOST_CHECK(test_args.GetArg(""-ccc"", ""xxx"") == ""extend3""); // check multiple values works const std::vector sec2_ccc_expected = {""extend3"",""argument"",""multiple""}; const auto& sec2_ccc_res = test_args.GetArgs(""-ccc""); BOOST_CHECK_EQUAL_COLLECTIONS(sec2_ccc_res.begin(), sec2_ccc_res.end(), sec2_ccc_expected.begin(), sec2_ccc_expected.end()); // Test section only options test_args.SetNetworkOnlyArg(""-d""); test_args.SetNetworkOnlyArg(""-ccc""); test_args.SetNetworkOnlyArg(""-h""); test_args.SelectConfigNetwork(CBaseChainParams::MAIN); BOOST_CHECK(test_args.GetArg(""-d"", ""xxx"") == ""e""); BOOST_CHECK(test_args.GetArgs(""-ccc"").size() == 2); BOOST_CHECK(test_args.GetArg(""-h"", ""xxx"") == ""0""); test_args.SelectConfigNetwork(""sec1""); BOOST_CHECK(test_args.GetArg(""-d"", ""xxx"") == ""eee""); BOOST_CHECK(test_args.GetArgs(""-d"").size() == 1); BOOST_CHECK(test_args.GetArgs(""-ccc"").size() == 2); BOOST_CHECK(test_args.GetArg(""-h"", ""xxx"") == ""1""); test_args.SelectConfigNetwork(""sec2""); BOOST_CHECK(test_args.GetArg(""-d"", ""xxx"") == ""xxx""); BOOST_CHECK(test_args.GetArgs(""-d"").size() == 0); BOOST_CHECK(test_args.GetArgs(""-ccc"").size() == 1); BOOST_CHECK(test_args.GetArg(""-h"", ""xxx"") == ""0""); } BOOST_AUTO_TEST_CASE(util_GetArg) { TestArgsManager testArgs; testArgs.GetOverrideArgs().clear(); testArgs.GetOverrideArgs()[""strtest1""] = {""string...""}; // strtest2 undefined on purpose testArgs.GetOverrideArgs()[""inttest1""] = {""12345""}; testArgs.GetOverrideArgs()[""inttest2""] = {""81985529216486895""}; // inttest3 undefined on purpose testArgs.GetOverrideArgs()[""booltest1""] = {""""}; // booltest2 undefined on purpose testArgs.GetOverrideArgs()[""booltest3""] = {""0""}; testArgs.GetOverrideArgs()[""booltest4""] = {""1""}; // priorities testArgs.GetOverrideArgs()[""pritest1""] = {""a"", ""b""}; testArgs.GetConfigArgs()[""pritest2""] = {""a"", ""b""}; testArgs.GetOverrideArgs()[""pritest3""] = {""a""}; testArgs.GetConfigArgs()[""pritest3""] = {""b""}; testArgs.GetOverrideArgs()[""pritest4""] = {""a"",""b""}; testArgs.GetConfigArgs()[""pritest4""] = {""c"",""d""}; BOOST_CHECK_EQUAL(testArgs.GetArg(""strtest1"", ""default""), ""string...""); BOOST_CHECK_EQUAL(testArgs.GetArg(""strtest2"", ""default""), ""default""); BOOST_CHECK_EQUAL(testArgs.GetArg(""inttest1"", -1), 12345); BOOST_CHECK_EQUAL(testArgs.GetArg(""inttest2"", -1), 81985529216486895LL); BOOST_CHECK_EQUAL(testArgs.GetArg(""inttest3"", -1), -1); BOOST_CHECK_EQUAL(testArgs.GetBoolArg(""booltest1"", false), true); BOOST_CHECK_EQUAL(testArgs.GetBoolArg(""booltest2"", false), false); BOOST_CHECK_EQUAL(testArgs.GetBoolArg(""booltest3"", false), false); BOOST_CHECK_EQUAL(testArgs.GetBoolArg(""booltest4"", false), true); BOOST_CHECK_EQUAL(testArgs.GetArg(""pritest1"", ""default""), ""b""); BOOST_CHECK_EQUAL(testArgs.GetArg(""pritest2"", ""default""), ""a""); BOOST_CHECK_EQUAL(testArgs.GetArg(""pritest3"", ""default""), ""a""); BOOST_CHECK_EQUAL(testArgs.GetArg(""pritest4"", ""default""), ""b""); } BOOST_AUTO_TEST_CASE(util_GetChainName) { TestArgsManager test_args; const char* argv_testnet[] = {""cmd"", ""-testnet""}; const char* argv_regtest[] = {""cmd"", ""-regtest""}; const char* argv_test_no_reg[] = {""cmd"", ""-testnet"", ""-noregtest""}; const char* argv_both[] = {""cmd"", ""-testnet"", ""-regtest""}; // equivalent to ""-testnet"" // regtest in testnet section is ignored const char* testnetconf = ""testnet=1\\nregtest=0\\n[test]\\nregtest=1""; test_args.ParseParameters(0, (char**)argv_testnet); BOOST_CHECK_EQUAL(test_args.GetChainName(), ""main""); test_args.ParseParameters(2, (char**)argv_testnet); BOOST_CHECK_EQUAL(test_args.GetChainName(), ""test""); test_args.ParseParameters(2, (char**)argv_regtest); BOOST_CHECK_EQUAL(test_args.GetChainName(), ""regtest""); test_args.ParseParameters(3, (char**)argv_test_no_reg); BOOST_CHECK_EQUAL(test_args.GetChainName(), ""test""); test_args.ParseParameters(3, (char**)argv_both); BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); test_args.ParseParameters(0, (char**)argv_testnet); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), ""test""); test_args.ParseParameters(2, (char**)argv_testnet); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), ""test""); test_args.ParseParameters(2, (char**)argv_regtest); test_args.ReadConfigString(testnetconf); BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); test_args.ParseParameters(3, (char**)argv_test_no_reg); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), ""test""); test_args.ParseParameters(3, (char**)argv_both); test_args.ReadConfigString(testnetconf); BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); // check setting the network to test (and thus making // [test] regtest=1 potentially relevant) doesn't break things test_args.SelectConfigNetwork(""test""); test_args.ParseParameters(0, (char**)argv_testnet); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), ""test""); test_args.ParseParameters(2, (char**)argv_testnet); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), ""test""); test_args.ParseParameters(2, (char**)argv_regtest); test_args.ReadConfigString(testnetconf); BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); test_args.ParseParameters(2, (char**)argv_test_no_reg); test_args.ReadConfigString(testnetconf); BOOST_CHECK_EQUAL(test_args.GetChainName(), ""test""); test_args.ParseParameters(3, (char**)argv_both); test_args.ReadConfigString(testnetconf); BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error); } BOOST_AUTO_TEST_CASE(util_FormatMoney) { BOOST_CHECK_EQUAL(FormatMoney(0), ""0.00""); BOOST_CHECK_EQUAL(FormatMoney((COIN/10000)*123456789), ""12345.6789""); BOOST_CHECK_EQUAL(FormatMoney(-COIN), ""-1.00""); BOOST_CHECK_EQUAL(FormatMoney(COIN*100000000), ""100000000.00""); BOOST_CHECK_EQUAL(FormatMoney(COIN*10000000), ""10000000.00""); BOOST_CHECK_EQUAL(FormatMoney(COIN*1000000), ""1000000.00""); BOOST_CHECK_EQUAL(FormatMoney(COIN*100000), ""100000.00""); BOOST_CHECK_EQUAL(FormatMoney(COIN*10000), ""10000.00""); BOOST_CHECK_EQUAL(FormatMoney(COIN*1000), ""1000.00""); BOOST_CHECK_EQUAL(FormatMoney(COIN*100), ""100.00""); BOOST_CHECK_EQUAL(FormatMoney(COIN*10), ""10.00""); BOOST_CHECK_EQUAL(FormatMoney(COIN), ""1.00""); BOOST_CHECK_EQUAL(FormatMoney(COIN/10), ""0.10""); BOOST_CHECK_EQUAL(FormatMoney(COIN/100), ""0.01""); BOOST_CHECK_EQUAL(FormatMoney(COIN/1000), ""0.001""); BOOST_CHECK_EQUAL(FormatMoney(COIN/10000), ""0.0001""); BOOST_CHECK_EQUAL(FormatMoney(COIN/100000), ""0.00001""); BOOST_CHECK_EQUAL(FormatMoney(COIN/1000000), ""0.000001""); BOOST_CHECK_EQUAL(FormatMoney(COIN/10000000), ""0.0000001""); BOOST_CHECK_EQUAL(FormatMoney(COIN/100000000), ""0.00000001""); } BOOST_AUTO_TEST_CASE(util_ParseMoney) { CAmount ret = 0; BOOST_CHECK(ParseMoney(""0.0"", ret)); BOOST_CHECK_EQUAL(ret, 0); BOOST_CHECK(ParseMoney(""12345.6789"", ret)); BOOST_CHECK_EQUAL(ret, (COIN/10000)*123456789); BOOST_CHECK(ParseMoney(""100000000.00"", ret)); BOOST_CHECK_EQUAL(ret, COIN*100000000); BOOST_CHECK(ParseMoney(""10000000.00"", ret)); BOOST_CHECK_EQUAL(ret, COIN*10000000); BOOST_CHECK(ParseMoney(""1000000.00"", ret)); BOOST_CHECK_EQUAL(ret, COIN*1000000); BOOST_CHECK(ParseMoney(""100000.00"", ret)); BOOST_CHECK_EQUAL(ret, COIN*100000); BOOST_CHECK(ParseMoney(""10000.00"", ret)); BOOST_CHECK_EQUAL(ret, COIN*10000); BOOST_CHECK(ParseMoney(""1000.00"", ret)); BOOST_CHECK_EQUAL(ret, COIN*1000); BOOST_CHECK(ParseMoney(""100.00"", ret)); BOOST_CHECK_EQUAL(ret, COIN*100); BOOST_CHECK(ParseMoney(""10.00"", ret)); BOOST_CHECK_EQUAL(ret, COIN*10); BOOST_CHECK(ParseMoney(""1.00"", ret)); BOOST_CHECK_EQUAL(ret, COIN); BOOST_CHECK(ParseMoney(""1"", ret)); BOOST_CHECK_EQUAL(ret, COIN); BOOST_CHECK(ParseMoney(""0.1"", ret)); BOOST_CHECK_EQUAL(ret, COIN/10); BOOST_CHECK(ParseMoney(""0.01"", ret)); BOOST_CHECK_EQUAL(ret, COIN/100); BOOST_CHECK(ParseMoney(""0.001"", ret)); BOOST_CHECK_EQUAL(ret, COIN/1000); BOOST_CHECK(ParseMoney(""0.0001"", ret)); BOOST_CHECK_EQUAL(ret, COIN/10000); BOOST_CHECK(ParseMoney(""0.00001"", ret)); BOOST_CHECK_EQUAL(ret, COIN/100000); BOOST_CHECK(ParseMoney(""0.000001"", ret)); BOOST_CHECK_EQUAL(ret, COIN/1000000); BOOST_CHECK(ParseMoney(""0.0000001"", ret)); BOOST_CHECK_EQUAL(ret, COIN/10000000); BOOST_CHECK(ParseMoney(""0.00000001"", ret)); BOOST_CHECK_EQUAL(ret, COIN/100000000); // Attempted 63 bit overflow should fail BOOST_CHECK(!ParseMoney(""92233720368.54775808"", ret)); // Parsing negative amounts must fail BOOST_CHECK(!ParseMoney(""-1"", ret)); } BOOST_AUTO_TEST_CASE(util_IsHex) { BOOST_CHECK(IsHex(""00"")); BOOST_CHECK(IsHex(""00112233445566778899aabbccddeeffAABBCCDDEEFF"")); BOOST_CHECK(IsHex(""ff"")); BOOST_CHECK(IsHex(""FF"")); BOOST_CHECK(!IsHex("""")); BOOST_CHECK(!IsHex(""0"")); BOOST_CHECK(!IsHex(""a"")); BOOST_CHECK(!IsHex(""eleven"")); BOOST_CHECK(!IsHex(""00xx00"")); BOOST_CHECK(!IsHex(""0x0000"")); } BOOST_AUTO_TEST_CASE(util_IsHexNumber) { BOOST_CHECK(IsHexNumber(""0x0"")); BOOST_CHECK(IsHexNumber(""0"")); BOOST_CHECK(IsHexNumber(""0x10"")); BOOST_CHECK(IsHexNumber(""10"")); BOOST_CHECK(IsHexNumber(""0xff"")); BOOST_CHECK(IsHexNumber(""ff"")); BOOST_CHECK(IsHexNumber(""0xFfa"")); BOOST_CHECK(IsHexNumber(""Ffa"")); BOOST_CHECK(IsHexNumber(""0x00112233445566778899aabbccddeeffAABBCCDDEEFF"")); BOOST_CHECK(IsHexNumber(""00112233445566778899aabbccddeeffAABBCCDDEEFF"")); BOOST_CHECK(!IsHexNumber("""")); // empty string not allowed BOOST_CHECK(!IsHexNumber(""0x"")); // empty string after prefix not allowed BOOST_CHECK(!IsHexNumber(""0x0 "")); // no spaces at end, BOOST_CHECK(!IsHexNumber("" 0x0"")); // or beginning, BOOST_CHECK(!IsHexNumber(""0x 0"")); // or middle, BOOST_CHECK(!IsHexNumber("" "")); // etc. BOOST_CHECK(!IsHexNumber(""0x0ga"")); // invalid character BOOST_CHECK(!IsHexNumber(""x0"")); // broken prefix BOOST_CHECK(!IsHexNumber(""0x0x00"")); // two prefixes not allowed } BOOST_AUTO_TEST_CASE(util_seed_insecure_rand) { SeedInsecureRand(true); for (int mod=2;mod<11;mod++) { int mask = 1; // Really rough binomial confidence approximation. int err = 30*10000./mod*sqrt((1./mod*(1-1./mod))/10000.); //mask is 2^ceil(log2(mod))-1 while(mask=(uint32_t)mod); count += rval==0; } BOOST_CHECK(count<=10000/mod+err); BOOST_CHECK(count>=10000/mod-err); } } BOOST_AUTO_TEST_CASE(util_TimingResistantEqual) { BOOST_CHECK(TimingResistantEqual(std::string(""""), std::string(""""))); BOOST_CHECK(!TimingResistantEqual(std::string(""abc""), std::string(""""))); BOOST_CHECK(!TimingResistantEqual(std::string(""""), std::string(""abc""))); BOOST_CHECK(!TimingResistantEqual(std::string(""a""), std::string(""aa""))); BOOST_CHECK(!TimingResistantEqual(std::string(""aa""), std::string(""a""))); BOOST_CHECK(TimingResistantEqual(std::string(""abc""), std::string(""abc""))); BOOST_CHECK(!TimingResistantEqual(std::string(""abc""), std::string(""aba""))); } /* Test strprintf formatting directives. * Put a string before and after to ensure sanity of element sizes on stack. */ #define B ""check_prefix"" #define E ""check_postfix"" BOOST_AUTO_TEST_CASE(strprintf_numbers) { int64_t s64t = -9223372036854775807LL; /* signed 64 bit test value */ uint64_t u64t = 18446744073709551615ULL; /* unsigned 64 bit test value */ BOOST_CHECK(strprintf(""%s %d %s"", B, s64t, E) == B"" -9223372036854775807 "" E); BOOST_CHECK(strprintf(""%s %u %s"", B, u64t, E) == B"" 18446744073709551615 "" E); BOOST_CHECK(strprintf(""%s %x %s"", B, u64t, E) == B"" ffffffffffffffff "" E); size_t st = 12345678; /* unsigned size_t test value */ ssize_t sst = -12345678; /* signed size_t test value */ BOOST_CHECK(strprintf(""%s %d %s"", B, sst, E) == B"" -12345678 "" E); BOOST_CHECK(strprintf(""%s %u %s"", B, st, E) == B"" 12345678 "" E); BOOST_CHECK(strprintf(""%s %x %s"", B, st, E) == B"" bc614e "" E); ptrdiff_t pt = 87654321; /* positive ptrdiff_t test value */ ptrdiff_t spt = -87654321; /* negative ptrdiff_t test value */ BOOST_CHECK(strprintf(""%s %d %s"", B, spt, E) == B"" -87654321 "" E); BOOST_CHECK(strprintf(""%s %u %s"", B, pt, E) == B"" 87654321 "" E); BOOST_CHECK(strprintf(""%s %x %s"", B, pt, E) == B"" 5397fb1 "" E); } #undef B #undef E /* Check for mingw/wine issue #3494 * Remove this test before time.ctime(0xffffffff) == 'Sun Feb 7 07:28:15 2106' */ BOOST_AUTO_TEST_CASE(gettime) { BOOST_CHECK((GetTime() & ~0xFFFFFFFFLL) == 0); } BOOST_AUTO_TEST_CASE(test_ParseInt32) { int32_t n; // Valid values BOOST_CHECK(ParseInt32(""1234"", nullptr)); BOOST_CHECK(ParseInt32(""0"", &n) && n == 0); BOOST_CHECK(ParseInt32(""1234"", &n) && n == 1234); BOOST_CHECK(ParseInt32(""01234"", &n) && n == 1234); // no octal BOOST_CHECK(ParseInt32(""2147483647"", &n) && n == 2147483647); BOOST_CHECK(ParseInt32(""-2147483648"", &n) && n == (-2147483647 - 1)); // (-2147483647 - 1) equals INT_MIN BOOST_CHECK(ParseInt32(""-1234"", &n) && n == -1234); // Invalid values BOOST_CHECK(!ParseInt32("""", &n)); BOOST_CHECK(!ParseInt32("" 1"", &n)); // no padding inside BOOST_CHECK(!ParseInt32(""1 "", &n)); BOOST_CHECK(!ParseInt32(""1a"", &n)); BOOST_CHECK(!ParseInt32(""aap"", &n)); BOOST_CHECK(!ParseInt32(""0x1"", &n)); // no hex BOOST_CHECK(!ParseInt32(""0x1"", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseInt32(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseInt32(""-2147483649"", nullptr)); BOOST_CHECK(!ParseInt32(""2147483648"", nullptr)); BOOST_CHECK(!ParseInt32(""-32482348723847471234"", nullptr)); BOOST_CHECK(!ParseInt32(""32482348723847471234"", nullptr)); } BOOST_AUTO_TEST_CASE(test_ParseInt64) { int64_t n; // Valid values BOOST_CHECK(ParseInt64(""1234"", nullptr)); BOOST_CHECK(ParseInt64(""0"", &n) && n == 0LL); BOOST_CHECK(ParseInt64(""1234"", &n) && n == 1234LL); BOOST_CHECK(ParseInt64(""01234"", &n) && n == 1234LL); // no octal BOOST_CHECK(ParseInt64(""2147483647"", &n) && n == 2147483647LL); BOOST_CHECK(ParseInt64(""-2147483648"", &n) && n == -2147483648LL); BOOST_CHECK(ParseInt64(""9223372036854775807"", &n) && n == (int64_t)9223372036854775807); BOOST_CHECK(ParseInt64(""-9223372036854775808"", &n) && n == (int64_t)-9223372036854775807-1); BOOST_CHECK(ParseInt64(""-1234"", &n) && n == -1234LL); // Invalid values BOOST_CHECK(!ParseInt64("""", &n)); BOOST_CHECK(!ParseInt64("" 1"", &n)); // no padding inside BOOST_CHECK(!ParseInt64(""1 "", &n)); BOOST_CHECK(!ParseInt64(""1a"", &n)); BOOST_CHECK(!ParseInt64(""aap"", &n)); BOOST_CHECK(!ParseInt64(""0x1"", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseInt64(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseInt64(""-9223372036854775809"", nullptr)); BOOST_CHECK(!ParseInt64(""9223372036854775808"", nullptr)); BOOST_CHECK(!ParseInt64(""-32482348723847471234"", nullptr)); BOOST_CHECK(!ParseInt64(""32482348723847471234"", nullptr)); } BOOST_AUTO_TEST_CASE(test_ParseUInt32) { uint32_t n; // Valid values BOOST_CHECK(ParseUInt32(""1234"", nullptr)); BOOST_CHECK(ParseUInt32(""0"", &n) && n == 0); BOOST_CHECK(ParseUInt32(""1234"", &n) && n == 1234); BOOST_CHECK(ParseUInt32(""01234"", &n) && n == 1234); // no octal BOOST_CHECK(ParseUInt32(""2147483647"", &n) && n == 2147483647); BOOST_CHECK(ParseUInt32(""2147483648"", &n) && n == (uint32_t)2147483648); BOOST_CHECK(ParseUInt32(""4294967295"", &n) && n == (uint32_t)4294967295); // Invalid values BOOST_CHECK(!ParseUInt32("""", &n)); BOOST_CHECK(!ParseUInt32("" 1"", &n)); // no padding inside BOOST_CHECK(!ParseUInt32("" -1"", &n)); BOOST_CHECK(!ParseUInt32(""1 "", &n)); BOOST_CHECK(!ParseUInt32(""1a"", &n)); BOOST_CHECK(!ParseUInt32(""aap"", &n)); BOOST_CHECK(!ParseUInt32(""0x1"", &n)); // no hex BOOST_CHECK(!ParseUInt32(""0x1"", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseUInt32(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseUInt32(""-2147483648"", &n)); BOOST_CHECK(!ParseUInt32(""4294967296"", &n)); BOOST_CHECK(!ParseUInt32(""-1234"", &n)); BOOST_CHECK(!ParseUInt32(""-32482348723847471234"", nullptr)); BOOST_CHECK(!ParseUInt32(""32482348723847471234"", nullptr)); } BOOST_AUTO_TEST_CASE(test_ParseUInt64) { uint64_t n; // Valid values BOOST_CHECK(ParseUInt64(""1234"", nullptr)); BOOST_CHECK(ParseUInt64(""0"", &n) && n == 0LL); BOOST_CHECK(ParseUInt64(""1234"", &n) && n == 1234LL); BOOST_CHECK(ParseUInt64(""01234"", &n) && n == 1234LL); // no octal BOOST_CHECK(ParseUInt64(""2147483647"", &n) && n == 2147483647LL); BOOST_CHECK(ParseUInt64(""9223372036854775807"", &n) && n == 9223372036854775807ULL); BOOST_CHECK(ParseUInt64(""9223372036854775808"", &n) && n == 9223372036854775808ULL); BOOST_CHECK(ParseUInt64(""18446744073709551615"", &n) && n == 18446744073709551615ULL); // Invalid values BOOST_CHECK(!ParseUInt64("""", &n)); BOOST_CHECK(!ParseUInt64("" 1"", &n)); // no padding inside BOOST_CHECK(!ParseUInt64("" -1"", &n)); BOOST_CHECK(!ParseUInt64(""1 "", &n)); BOOST_CHECK(!ParseUInt64(""1a"", &n)); BOOST_CHECK(!ParseUInt64(""aap"", &n)); BOOST_CHECK(!ParseUInt64(""0x1"", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseUInt64(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseUInt64(""-9223372036854775809"", nullptr)); BOOST_CHECK(!ParseUInt64(""18446744073709551616"", nullptr)); BOOST_CHECK(!ParseUInt64(""-32482348723847471234"", nullptr)); BOOST_CHECK(!ParseUInt64(""-2147483648"", &n)); BOOST_CHECK(!ParseUInt64(""-9223372036854775808"", &n)); BOOST_CHECK(!ParseUInt64(""-1234"", &n)); } BOOST_AUTO_TEST_CASE(test_ParseDouble) { double n; // Valid values BOOST_CHECK(ParseDouble(""1234"", nullptr)); BOOST_CHECK(ParseDouble(""0"", &n) && n == 0.0); BOOST_CHECK(ParseDouble(""1234"", &n) && n == 1234.0); BOOST_CHECK(ParseDouble(""01234"", &n) && n == 1234.0); // no octal BOOST_CHECK(ParseDouble(""2147483647"", &n) && n == 2147483647.0); BOOST_CHECK(ParseDouble(""-2147483648"", &n) && n == -2147483648.0); BOOST_CHECK(ParseDouble(""-1234"", &n) && n == -1234.0); BOOST_CHECK(ParseDouble(""1e6"", &n) && n == 1e6); BOOST_CHECK(ParseDouble(""-1e6"", &n) && n == -1e6); // Invalid values BOOST_CHECK(!ParseDouble("""", &n)); BOOST_CHECK(!ParseDouble("" 1"", &n)); // no padding inside BOOST_CHECK(!ParseDouble(""1 "", &n)); BOOST_CHECK(!ParseDouble(""1a"", &n)); BOOST_CHECK(!ParseDouble(""aap"", &n)); BOOST_CHECK(!ParseDouble(""0x1"", &n)); // no hex const char test_bytes[] = {'1', 0, '1'}; std::string teststr(test_bytes, sizeof(test_bytes)); BOOST_CHECK(!ParseDouble(teststr, &n)); // no embedded NULs // Overflow and underflow BOOST_CHECK(!ParseDouble(""-1e10000"", nullptr)); BOOST_CHECK(!ParseDouble(""1e10000"", nullptr)); } BOOST_AUTO_TEST_CASE(test_FormatParagraph) { BOOST_CHECK_EQUAL(FormatParagraph("""", 79, 0), """"); BOOST_CHECK_EQUAL(FormatParagraph(""test"", 79, 0), ""test""); BOOST_CHECK_EQUAL(FormatParagraph("" test"", 79, 0), "" test""); BOOST_CHECK_EQUAL(FormatParagraph(""test test"", 79, 0), ""test test""); BOOST_CHECK_EQUAL(FormatParagraph(""test test"", 4, 0), ""test\\ntest""); BOOST_CHECK_EQUAL(FormatParagraph(""testerde test"", 4, 0), ""testerde\\ntest""); BOOST_CHECK_EQUAL(FormatParagraph(""test test"", 4, 4), ""test\\n test""); // Make sure we don't indent a fully-new line following a too-long line ending BOOST_CHECK_EQUAL(FormatParagraph(""test test\\nabc"", 4, 4), ""test\\n test\\nabc""); BOOST_CHECK_EQUAL(FormatParagraph(""This_is_a_very_long_test_string_without_any_spaces_so_it_should_just_get_returned_as_is_despite_the_length until it gets here"", 79), ""This_is_a_very_long_test_string_without_any_spaces_so_it_should_just_get_returned_as_is_despite_the_length\\nuntil it gets here""); // Test wrap length is exact BOOST_CHECK_EQUAL(FormatParagraph(""a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p"", 79), ""a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\\nf g h i j k l m n o p""); BOOST_CHECK_EQUAL(FormatParagraph(""x\\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p"", 79), ""x\\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\\nf g h i j k l m n o p""); // Indent should be included in length of lines BOOST_CHECK_EQUAL(FormatParagraph(""x\\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e fg h i j k"", 79, 4), ""x\\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\\n f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e fg\\n h i j k""); BOOST_CHECK_EQUAL(FormatParagraph(""This is a very long test string. This is a second sentence in the very long test string."", 79), ""This is a very long test string. This is a second sentence in the very long\\ntest string.""); BOOST_CHECK_EQUAL(FormatParagraph(""This is a very long test string.\\nThis is a second sentence in the very long test string. This is a third sentence in the very long test string."", 79), ""This is a very long test string.\\nThis is a second sentence in the very long test string. This is a third\\nsentence in the very long test string.""); BOOST_CHECK_EQUAL(FormatParagraph(""This is a very long test string.\\n\\nThis is a second sentence in the very long test string. This is a third sentence in the very long test string."", 79), ""This is a very long test string.\\n\\nThis is a second sentence in the very long test string. This is a third\\nsentence in the very long test string.""); BOOST_CHECK_EQUAL(FormatParagraph(""Testing that normal newlines do not get indented.\\nLike here."", 79), ""Testing that normal newlines do not get indented.\\nLike here.""); } BOOST_AUTO_TEST_CASE(test_FormatSubVersion) { std::vector comments; comments.push_back(std::string(""comment1"")); std::vector comments2; comments2.push_back(std::string(""comment1"")); comments2.push_back(SanitizeString(std::string(""Comment2; .,_?@-; !\\""#$%&'()*+/<=>[]\\\\^`{|}~""), SAFE_CHARS_UA_COMMENT)); // Semicolon is discouraged but not forbidden by BIP-0014 BOOST_CHECK_EQUAL(FormatSubVersion(""Test"", 99900, std::vector()),std::string(""/Test:0.9.99/"")); BOOST_CHECK_EQUAL(FormatSubVersion(""Test"", 99900, comments),std::string(""/Test:0.9.99(comment1)/"")); BOOST_CHECK_EQUAL(FormatSubVersion(""Test"", 99900, comments2),std::string(""/Test:0.9.99(comment1; Comment2; .,_?@-; )/"")); } BOOST_AUTO_TEST_CASE(test_ParseFixedPoint) { int64_t amount = 0; BOOST_CHECK(ParseFixedPoint(""0"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 0LL); BOOST_CHECK(ParseFixedPoint(""1"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 100000000LL); BOOST_CHECK(ParseFixedPoint(""0.0"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 0LL); BOOST_CHECK(ParseFixedPoint(""-0.1"", 8, &amount)); BOOST_CHECK_EQUAL(amount, -10000000LL); BOOST_CHECK(ParseFixedPoint(""1.1"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 110000000LL); BOOST_CHECK(ParseFixedPoint(""1.10000000000000000"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 110000000LL); BOOST_CHECK(ParseFixedPoint(""1.1e1"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 1100000000LL); BOOST_CHECK(ParseFixedPoint(""1.1e-1"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 11000000LL); BOOST_CHECK(ParseFixedPoint(""1000"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 100000000000LL); BOOST_CHECK(ParseFixedPoint(""-1000"", 8, &amount)); BOOST_CHECK_EQUAL(amount, -100000000000LL); BOOST_CHECK(ParseFixedPoint(""0.00000001"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 1LL); BOOST_CHECK(ParseFixedPoint(""0.0000000100000000"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 1LL); BOOST_CHECK(ParseFixedPoint(""-0.00000001"", 8, &amount)); BOOST_CHECK_EQUAL(amount, -1LL); BOOST_CHECK(ParseFixedPoint(""1000000000.00000001"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 100000000000000001LL); BOOST_CHECK(ParseFixedPoint(""9999999999.99999999"", 8, &amount)); BOOST_CHECK_EQUAL(amount, 999999999999999999LL); BOOST_CHECK(ParseFixedPoint(""-9999999999.99999999"", 8, &amount)); BOOST_CHECK_EQUAL(amount, -999999999999999999LL); BOOST_CHECK(!ParseFixedPoint("""", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""a-1000"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-a1000"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-1000a"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-01000"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""00.1"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint("".1"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""--0.1"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""0.000000001"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-0.000000001"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""0.00000001000000001"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-10000000000.00000000"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""10000000000.00000000"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-10000000000.00000001"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""10000000000.00000001"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-10000000000.00000009"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""10000000000.00000009"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-99999999999.99999999"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""99999909999.09999999"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""92233720368.54775807"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""92233720368.54775808"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-92233720368.54775808"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""-92233720368.54775809"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""1.1e"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""1.1e-"", 8, &amount)); BOOST_CHECK(!ParseFixedPoint(""1."", 8, &amount)); } static void TestOtherThread(fs::path dirname, std::string lockname, bool *result) { *result = LockDirectory(dirname, lockname); } #ifndef WIN32 // Cannot do this test on WIN32 due to lack of fork() static constexpr char LockCommand = 'L'; static constexpr char UnlockCommand = 'U'; static constexpr char ExitCommand = 'X'; static void TestOtherProcess(fs::path dirname, std::string lockname, int fd) { char ch; while (true) { int rv = read(fd, &ch, 1); // Wait for command assert(rv == 1); switch(ch) { case LockCommand: ch = LockDirectory(dirname, lockname); rv = write(fd, &ch, 1); assert(rv == 1); break; case UnlockCommand: ReleaseDirectoryLocks(); ch = true; // Always succeeds rv = write(fd, &ch, 1); break; case ExitCommand: close(fd); exit(0); default: assert(0); } } } #endif BOOST_AUTO_TEST_CASE(test_LockDirectory) { fs::path dirname = fs::temp_directory_path() / fs::unique_path(); const std::string lockname = "".lock""; #ifndef WIN32 // Revert SIGCHLD to default, otherwise boost.test will catch and fail on // it: there is BOOST_TEST_IGNORE_SIGCHLD but that only works when defined // at build-time of the boost library void (*old_handler)(int) = signal(SIGCHLD, SIG_DFL); // Fork another process for testing before creating the lock, so that we // won't fork while holding the lock (which might be undefined, and is not // relevant as test case as that is avoided with -daemonize). int fd[2]; BOOST_CHECK_EQUAL(socketpair(AF_UNIX, SOCK_STREAM, 0, fd), 0); pid_t pid = fork(); if (!pid) { BOOST_CHECK_EQUAL(close(fd[1]), 0); // Child: close parent end TestOtherProcess(dirname, lockname, fd[0]); } BOOST_CHECK_EQUAL(close(fd[0]), 0); // Parent: close child end #endif // Lock on non-existent directory should fail BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname), false); fs::create_directories(dirname); // Probing lock on new directory should succeed BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true); // Persistent lock on new directory should succeed BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname), true); // Another lock on the directory from the same thread should succeed BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname), true); // Another lock on the directory from a different thread within the same process should succeed bool threadresult; std::thread thr(TestOtherThread, dirname, lockname, &threadresult); thr.join(); BOOST_CHECK_EQUAL(threadresult, true); #ifndef WIN32 // Try to acquire lock in child process while we're holding it, this should fail. char ch; BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1); BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1); BOOST_CHECK_EQUAL((bool)ch, false); // Give up our lock ReleaseDirectoryLocks(); // Probing lock from our side now should succeed, but not hold on to the lock. BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true); // Try to acquire the lock in the child process, this should be successful. BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1); BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1); BOOST_CHECK_EQUAL((bool)ch, true); // When we try to probe the lock now, it should fail. BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), false); // Unlock the lock in the child process BOOST_CHECK_EQUAL(write(fd[1], &UnlockCommand, 1), 1); BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1); BOOST_CHECK_EQUAL((bool)ch, true); // When we try to probe the lock now, it should succeed. BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true); // Re-lock the lock in the child process, then wait for it to exit, check // successful return. After that, we check that exiting the process // has released the lock as we would expect by probing it. int processstatus; BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1); BOOST_CHECK_EQUAL(write(fd[1], &ExitCommand, 1), 1); BOOST_CHECK_EQUAL(waitpid(pid, &processstatus, 0), pid); BOOST_CHECK_EQUAL(processstatus, 0); BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true); // Restore SIGCHLD signal(SIGCHLD, old_handler); BOOST_CHECK_EQUAL(close(fd[1]), 0); // Close our side of the socketpair #endif // Clean up ReleaseDirectoryLocks(); fs::remove_all(dirname); } BOOST_AUTO_TEST_CASE(test_DirIsWritable) { // Should be able to write to the system tmp dir. fs::path tmpdirname = fs::temp_directory_path(); BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), true); // Should not be able to write to a non-existent dir. tmpdirname = fs::temp_directory_path() / fs::unique_path(); BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), false); fs::create_directory(tmpdirname); // Should be able to write to it now. BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), true); fs::remove(tmpdirname); } BOOST_AUTO_TEST_SUITE_END() ",16187,False,2327.824001203645,median "// rijndael.cpp - modified by Chris Morgan // and Wei Dai from Paulo Baretto's Rijndael implementation // The original code and all modifications are in the public domain. // use ""cl /EP /P /DCRYPTOPP_GENERATE_X64_MASM rijndael.cpp"" to generate MASM code /* July 2018: Added support for ARMv7 AES instructions via Cryptogams ASM. See the head notes in aes_armv4.S for copyright and license. */ /* September 2017: Added support for Power8 AES instructions via compiler intrinsics. */ /* July 2017: Added support for ARMv8 AES instructions via compiler intrinsics. */ /* July 2010: Added support for AES-NI instructions via compiler intrinsics. */ /* Feb 2009: The x86/x64 assembly code was rewritten in by Wei Dai to do counter mode caching, which was invented by Hongjun Wu and popularized by Daniel J. Bernstein and Peter Schwabe in their paper ""New AES software speed records"". The round function was also modified to include a trick similar to one in Brian Gladman's x86 assembly code, doing an 8-bit register move to minimize the number of register spills. Also switched to compressed tables and copying round keys to the stack. The C++ implementation uses compressed tables if CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS is defined. It is defined on x86 platforms by default but no others. */ /* July 2006: Defense against timing attacks was added in by Wei Dai. The code now uses smaller tables in the first and last rounds, and preloads them into L1 cache before usage (by loading at least one element in each cache line). We try to delay subsequent accesses to each table (used in the first and last rounds) until all of the table has been preloaded. Hopefully the compiler isn't smart enough to optimize that code away. After preloading the table, we also try not to access any memory location other than the table and the stack, in order to prevent table entries from being unloaded from L1 cache, until that round is finished. (Some popular CPUs have 2-way associative caches.) */ // This is the original introductory comment: /** * version 3.0 (December 2000) * * Optimised ANSI C code for the Rijndael cipher (now AES) * * author Vincent Rijmen * author Antoon Bosselaers * author Paulo Barreto * * This code is hereby placed in the public domain. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include ""pch.h"" #include ""config.h"" #ifndef CRYPTOPP_IMPORTS #ifndef CRYPTOPP_GENERATE_X64_MASM #include ""rijndael.h"" #include ""misc.h"" #include ""cpu.h"" // VS2017 and global optimization bug. TODO, figure out when // we can re-enable full optimizations for VS2017. Also see // https://github.com/weidai11/cryptopp/issues/649 #if (_MSC_VER >= 1910) # ifndef CRYPTOPP_DEBUG # pragma optimize("""", off) # pragma optimize(""ts"", on) # endif #endif NAMESPACE_BEGIN(CryptoPP) // Hack for http://github.com/weidai11/cryptopp/issues/42 and http://github.com/weidai11/cryptopp/issues/132 #if (CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) # define CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS 1 #endif // Clang intrinsic casts #define M128I_CAST(x) ((__m128i *)(void *)(x)) #define CONST_M128I_CAST(x) ((const __m128i *)(const void *)(x)) #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) # if (CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) namespace rdtable {CRYPTOPP_ALIGN_DATA(16) word64 Te[256+2];} using namespace rdtable; # else static word64 Te[256]; # endif static word64 Td[256]; #else // Not CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS # if defined(CRYPTOPP_X64_MASM_AVAILABLE) // Unused; avoids linker error on Microsoft X64 non-AESNI platforms namespace rdtable {CRYPTOPP_ALIGN_DATA(16) word64 Te[256+2];} # endif CRYPTOPP_ALIGN_DATA(16) static word32 Te[256*4]; CRYPTOPP_ALIGN_DATA(16) static word32 Td[256*4]; #endif // CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS static volatile bool s_TeFilled = false, s_TdFilled = false; ANONYMOUS_NAMESPACE_BEGIN #if CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86 // Determine whether the range between begin and end overlaps // with the same 4k block offsets as the Te table. Logically, // the code is trying to create the condition: // // Two sepearate memory pages: // // +-----+ +-----+ // |XXXXX| |YYYYY| // |XXXXX| |YYYYY| // | | | | // | | | | // +-----+ +-----+ // Te Table Locals // // Have a logical cache view of (X and Y may be inverted): // // +-----+ // |XXXXX| // |XXXXX| // |YYYYY| // |YYYYY| // +-----+ // static inline bool AliasedWithTable(const byte *begin, const byte *end) { ptrdiff_t s0 = uintptr_t(begin)%4096, s1 = uintptr_t(end)%4096; ptrdiff_t t0 = uintptr_t(Te)%4096, t1 = (uintptr_t(Te)+sizeof(Te))%4096; if (t1 > t0) return (s0 >= t0 && s0 < t1) || (s1 > t0 && s1 <= t1); else return (s0 < t1 || s1 <= t1) || (s0 >= t0 || s1 > t0); } struct Locals { word32 subkeys[4*12], workspace[8]; const byte *inBlocks, *inXorBlocks, *outXorBlocks; byte *outBlocks; size_t inIncrement, inXorIncrement, outXorIncrement, outIncrement; size_t regSpill, lengthAndCounterFlag, keysBegin; }; const size_t s_aliasPageSize = 4096; const size_t s_aliasBlockSize = 256; const size_t s_sizeToAllocate = s_aliasPageSize + s_aliasBlockSize + sizeof(Locals); #endif // CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86 ANONYMOUS_NAMESPACE_END // ************************* Portable Code ************************************ #define QUARTER_ROUND(L, T, t, a, b, c, d) \\ a ^= L(T, 3, byte(t)); t >>= 8;\\ b ^= L(T, 2, byte(t)); t >>= 8;\\ c ^= L(T, 1, byte(t)); t >>= 8;\\ d ^= L(T, 0, t); #define QUARTER_ROUND_LE(t, a, b, c, d) \\ tempBlock[a] = ((byte *)(Te+byte(t)))[1]; t >>= 8;\\ tempBlock[b] = ((byte *)(Te+byte(t)))[1]; t >>= 8;\\ tempBlock[c] = ((byte *)(Te+byte(t)))[1]; t >>= 8;\\ tempBlock[d] = ((byte *)(Te+t))[1]; #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) #define QUARTER_ROUND_LD(t, a, b, c, d) \\ tempBlock[a] = ((byte *)(Td+byte(t)))[GetNativeByteOrder()*7]; t >>= 8;\\ tempBlock[b] = ((byte *)(Td+byte(t)))[GetNativeByteOrder()*7]; t >>= 8;\\ tempBlock[c] = ((byte *)(Td+byte(t)))[GetNativeByteOrder()*7]; t >>= 8;\\ tempBlock[d] = ((byte *)(Td+t))[GetNativeByteOrder()*7]; #else #define QUARTER_ROUND_LD(t, a, b, c, d) \\ tempBlock[a] = Sd[byte(t)]; t >>= 8;\\ tempBlock[b] = Sd[byte(t)]; t >>= 8;\\ tempBlock[c] = Sd[byte(t)]; t >>= 8;\\ tempBlock[d] = Sd[t]; #endif #define QUARTER_ROUND_E(t, a, b, c, d) QUARTER_ROUND(TL_M, Te, t, a, b, c, d) #define QUARTER_ROUND_D(t, a, b, c, d) QUARTER_ROUND(TL_M, Td, t, a, b, c, d) #if (CRYPTOPP_LITTLE_ENDIAN) #define QUARTER_ROUND_FE(t, a, b, c, d) QUARTER_ROUND(TL_F, Te, t, d, c, b, a) #define QUARTER_ROUND_FD(t, a, b, c, d) QUARTER_ROUND(TL_F, Td, t, d, c, b, a) #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) #define TL_F(T, i, x) (*(word32 *)(void *)((byte *)T + x*8 + (6-i)%4+1)) #define TL_M(T, i, x) (*(word32 *)(void *)((byte *)T + x*8 + (i+3)%4+1)) #else #define TL_F(T, i, x) rotrFixed(T[x], (3-i)*8) #define TL_M(T, i, x) T[i*256 + x] #endif #else #define QUARTER_ROUND_FE(t, a, b, c, d) QUARTER_ROUND(TL_F, Te, t, a, b, c, d) #define QUARTER_ROUND_FD(t, a, b, c, d) QUARTER_ROUND(TL_F, Td, t, a, b, c, d) #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) #define TL_F(T, i, x) (*(word32 *)(void *)((byte *)T + x*8 + (4-i)%4)) #define TL_M TL_F #else #define TL_F(T, i, x) rotrFixed(T[x], i*8) #define TL_M(T, i, x) T[i*256 + x] #endif #endif #define f2(x) ((x<<1)^(((x>>7)&1)*0x11b)) #define f4(x) ((x<<2)^(((x>>6)&1)*0x11b)^(((x>>6)&2)*0x11b)) #define f8(x) ((x<<3)^(((x>>5)&1)*0x11b)^(((x>>5)&2)*0x11b)^(((x>>5)&4)*0x11b)) #define f3(x) (f2(x) ^ x) #define f9(x) (f8(x) ^ x) #define fb(x) (f8(x) ^ f2(x) ^ x) #define fd(x) (f8(x) ^ f4(x) ^ x) #define fe(x) (f8(x) ^ f4(x) ^ f2(x)) unsigned int Rijndael::Base::OptimalDataAlignment() const { #if (CRYPTOPP_AESNI_AVAILABLE) if (HasAESNI()) return 1; #endif #if (CRYPTOPP_ARM_AES_AVAILABLE) if (HasAES()) return 1; #endif #if (CRYPTOGAMS_ARM_AES) if (HasARMv7()) return 1; #endif #if (CRYPTOPP_POWER8_AES_AVAILABLE) if (HasAES()) return 1; #endif return BlockTransformation::OptimalDataAlignment(); } void Rijndael::Base::FillEncTable() { for (int i=0; i<256; i++) { byte x = Se[i]; #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) word32 y = word32(x)<<8 | word32(x)<<16 | word32(f2(x))<<24; Te[i] = word64(y | f3(x))<<32 | y; #else word32 y = f3(x) | word32(x)<<8 | word32(x)<<16 | word32(f2(x))<<24; for (int j=0; j<4; j++) { Te[i+j*256] = y; y = rotrConstant<8>(y); } #endif } #if (CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) Te[256] = Te[257] = 0; #endif s_TeFilled = true; } void Rijndael::Base::FillDecTable() { for (int i=0; i<256; i++) { byte x = Sd[i]; #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) word32 y = word32(fd(x))<<8 | word32(f9(x))<<16 | word32(fe(x))<<24; Td[i] = word64(y | fb(x))<<32 | y | x; #else word32 y = fb(x) | word32(fd(x))<<8 | word32(f9(x))<<16 | word32(fe(x))<<24; for (int j=0; j<4; j++) { Td[i+j*256] = y; y = rotrConstant<8>(y); } #endif } s_TdFilled = true; } #if (CRYPTOPP_AESNI_AVAILABLE) extern void Rijndael_UncheckedSetKey_SSE4_AESNI(const byte *userKey, size_t keyLen, word32* rk); extern void Rijndael_UncheckedSetKeyRev_AESNI(word32 *key, unsigned int rounds); extern size_t Rijndael_Enc_AdvancedProcessBlocks_AESNI(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); extern size_t Rijndael_Dec_AdvancedProcessBlocks_AESNI(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); #endif #if (CRYPTOPP_ARM_AES_AVAILABLE) extern size_t Rijndael_Enc_AdvancedProcessBlocks_ARMV8(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); extern size_t Rijndael_Dec_AdvancedProcessBlocks_ARMV8(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); #endif #if (CRYPTOGAMS_ARM_AES) extern ""C"" int AES_set_encrypt_key(const unsigned char *userKey, const int bitLen, word32 *rkey); extern ""C"" int AES_set_decrypt_key(const unsigned char *userKey, const int bitLen, word32 *rkey); extern ""C"" void AES_encrypt(const unsigned char in[16], unsigned char out[16], const word32 *rkey); extern ""C"" void AES_decrypt(const unsigned char in[16], unsigned char out[16], const word32 *rkey); #endif #if (CRYPTOPP_POWER8_AES_AVAILABLE) extern void Rijndael_UncheckedSetKey_POWER8(const byte* userKey, size_t keyLen, word32* rk, const byte* Se); extern size_t Rijndael_Enc_AdvancedProcessBlocks128_6x1_ALTIVEC(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); extern size_t Rijndael_Dec_AdvancedProcessBlocks128_6x1_ALTIVEC(const word32 *subkeys, size_t rounds, const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags); #endif #if (CRYPTOGAMS_ARM_AES) int CRYPTOGAMS_set_encrypt_key(const byte *userKey, const int bitLen, word32 *rkey) { return AES_set_encrypt_key(userKey, bitLen, rkey); } int CRYPTOGAMS_set_decrypt_key(const byte *userKey, const int bitLen, word32 *rkey) { return AES_set_decrypt_key(userKey, bitLen, rkey); } void CRYPTOGAMS_encrypt(const byte *inBlock, const byte *xorBlock, byte *outBlock, const word32 *rkey) { AES_encrypt(inBlock, outBlock, rkey); if (xorBlock) xorbuf (outBlock, xorBlock, 16); } void CRYPTOGAMS_decrypt(const byte *inBlock, const byte *xorBlock, byte *outBlock, const word32 *rkey) { AES_decrypt(inBlock, outBlock, rkey); if (xorBlock) xorbuf (outBlock, xorBlock, 16); } #endif std::string Rijndael::Base::AlgorithmProvider() const { #if (CRYPTOPP_AESNI_AVAILABLE) if (HasAESNI()) return ""AESNI""; #endif #if CRYPTOPP_SSE2_ASM_AVAILABLE && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) if (HasSSE2()) return ""SSE2""; #endif #if (CRYPTOPP_ARM_AES_AVAILABLE) if (HasAES()) return ""ARMv8""; #endif #if (CRYPTOGAMS_ARM_AES) if (HasARMv7()) return ""ARMv7""; #endif #if (CRYPTOPP_POWER8_AES_AVAILABLE) if (HasAES()) return ""Power8""; #endif return ""C++""; } void Rijndael::Base::UncheckedSetKey(const byte *userKey, unsigned int keyLen, const NameValuePairs &) { AssertValidKeyLength(keyLen); #if (CRYPTOGAMS_ARM_AES) if (HasARMv7()) { m_rounds = keyLen/4 + 6; m_key.New(4*(15+1)+4); if (IsForwardTransformation()) CRYPTOGAMS_set_encrypt_key(userKey, keyLen*8, m_key.begin()); else CRYPTOGAMS_set_decrypt_key(userKey, keyLen*8, m_key.begin()); return; } #endif #if CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86 m_aliasBlock.New(s_sizeToAllocate); // The alias block is only used on IA-32 when unaligned data access is in effect. // Setting the low water mark to 0 avoids zeroization when m_aliasBlock is unused. m_aliasBlock.SetMark(0); #endif m_rounds = keyLen/4 + 6; m_key.New(4*(m_rounds+1)); word32 *rk = m_key; #if (CRYPTOPP_AESNI_AVAILABLE && CRYPTOPP_SSE41_AVAILABLE && (!defined(_MSC_VER) || _MSC_VER >= 1600 || CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32)) // MSVC 2008 SP1 generates bad code for _mm_extract_epi32() when compiling for X64 if (HasAESNI() && HasSSE41()) { // TODO: Add non-SSE4.1 variant for low-end Atoms. The low-end // Atoms have SSE2-SSSE3 and AES-NI, but not SSE4.1 or SSE4.2. Rijndael_UncheckedSetKey_SSE4_AESNI(userKey, keyLen, rk); if (!IsForwardTransformation()) Rijndael_UncheckedSetKeyRev_AESNI(m_key, m_rounds); return; } #endif #if CRYPTOPP_POWER8_AES_AVAILABLE if (HasAES()) { // We still need rcon and Se to fallback to C/C++ for AES-192 and AES-256. // The IBM docs on AES sucks. Intel's docs on AESNI puts IBM to shame. Rijndael_UncheckedSetKey_POWER8(userKey, keyLen, rk, Se); return; } #endif GetUserKey(BIG_ENDIAN_ORDER, rk, keyLen/4, userKey, keyLen); const word32 *rc = rcon; word32 temp; while (true) { temp = rk[keyLen/4-1]; word32 x = (word32(Se[GETBYTE(temp, 2)]) << 24) ^ (word32(Se[GETBYTE(temp, 1)]) << 16) ^ (word32(Se[GETBYTE(temp, 0)]) << 8) ^ Se[GETBYTE(temp, 3)]; rk[keyLen/4] = rk[0] ^ x ^ *(rc++); rk[keyLen/4+1] = rk[1] ^ rk[keyLen/4]; rk[keyLen/4+2] = rk[2] ^ rk[keyLen/4+1]; rk[keyLen/4+3] = rk[3] ^ rk[keyLen/4+2]; if (rk + keyLen/4 + 4 == m_key.end()) break; if (keyLen == 24) { rk[10] = rk[ 4] ^ rk[ 9]; rk[11] = rk[ 5] ^ rk[10]; } else if (keyLen == 32) { temp = rk[11]; rk[12] = rk[ 4] ^ (word32(Se[GETBYTE(temp, 3)]) << 24) ^ (word32(Se[GETBYTE(temp, 2)]) << 16) ^ (word32(Se[GETBYTE(temp, 1)]) << 8) ^ Se[GETBYTE(temp, 0)]; rk[13] = rk[ 5] ^ rk[12]; rk[14] = rk[ 6] ^ rk[13]; rk[15] = rk[ 7] ^ rk[14]; } rk += keyLen/4; } rk = m_key; if (IsForwardTransformation()) { if (!s_TeFilled) FillEncTable(); ConditionalByteReverse(BIG_ENDIAN_ORDER, rk, rk, 16); ConditionalByteReverse(BIG_ENDIAN_ORDER, rk + m_rounds*4, rk + m_rounds*4, 16); } else { if (!s_TdFilled) FillDecTable(); #define InverseMixColumn(x) \\ TL_M(Td, 0, Se[GETBYTE(x, 3)]) ^ TL_M(Td, 1, Se[GETBYTE(x, 2)]) ^ \\ TL_M(Td, 2, Se[GETBYTE(x, 1)]) ^ TL_M(Td, 3, Se[GETBYTE(x, 0)]) unsigned int i, j; for (i = 4, j = 4*m_rounds-4; i < j; i += 4, j -= 4) { temp = InverseMixColumn(rk[i ]); rk[i ] = InverseMixColumn(rk[j ]); rk[j ] = temp; temp = InverseMixColumn(rk[i + 1]); rk[i + 1] = InverseMixColumn(rk[j + 1]); rk[j + 1] = temp; temp = InverseMixColumn(rk[i + 2]); rk[i + 2] = InverseMixColumn(rk[j + 2]); rk[j + 2] = temp; temp = InverseMixColumn(rk[i + 3]); rk[i + 3] = InverseMixColumn(rk[j + 3]); rk[j + 3] = temp; } rk[i+0] = InverseMixColumn(rk[i+0]); rk[i+1] = InverseMixColumn(rk[i+1]); rk[i+2] = InverseMixColumn(rk[i+2]); rk[i+3] = InverseMixColumn(rk[i+3]); temp = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[0]); rk[0] = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[4*m_rounds+0]); rk[4*m_rounds+0] = temp; temp = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[1]); rk[1] = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[4*m_rounds+1]); rk[4*m_rounds+1] = temp; temp = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[2]); rk[2] = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[4*m_rounds+2]); rk[4*m_rounds+2] = temp; temp = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[3]); rk[3] = ConditionalByteReverse(BIG_ENDIAN_ORDER, rk[4*m_rounds+3]); rk[4*m_rounds+3] = temp; } #if CRYPTOPP_AESNI_AVAILABLE if (HasAESNI()) ConditionalByteReverse(BIG_ENDIAN_ORDER, rk+4, rk+4, (m_rounds-1)*16); #endif #if CRYPTOPP_ARM_AES_AVAILABLE if (HasAES()) ConditionalByteReverse(BIG_ENDIAN_ORDER, rk+4, rk+4, (m_rounds-1)*16); #endif } void Rijndael::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const { #if CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE) || CRYPTOPP_AESNI_AVAILABLE # if (CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) if (HasSSE2()) # else if (HasAESNI()) # endif { (void)Rijndael::Enc::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif #if (CRYPTOPP_ARM_AES_AVAILABLE) if (HasAES()) { (void)Rijndael::Enc::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif #if (CRYPTOGAMS_ARM_AES) if (HasARMv7()) { CRYPTOGAMS_encrypt(inBlock, xorBlock, outBlock, m_key.begin()); return; } #endif #if (CRYPTOPP_POWER8_AES_AVAILABLE) if (HasAES()) { (void)Rijndael::Enc::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif typedef BlockGetAndPut Block; word32 s0, s1, s2, s3, t0, t1, t2, t3; Block::Get(inBlock)(s0)(s1)(s2)(s3); const word32 *rk = m_key; s0 ^= rk[0]; s1 ^= rk[1]; s2 ^= rk[2]; s3 ^= rk[3]; t0 = rk[4]; t1 = rk[5]; t2 = rk[6]; t3 = rk[7]; rk += 8; // timing attack countermeasure. see comments at top for more details. // also see http://github.com/weidai11/cryptopp/issues/146 const int cacheLineSize = GetCacheLineSize(); unsigned int i; volatile word32 _u = 0; word32 u = _u; #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) for (i=0; i<2048; i+=cacheLineSize) #else for (i=0; i<1024; i+=cacheLineSize) #endif u &= *(const word32 *)(const void *)(((const byte *)Te)+i); u &= Te[255]; s0 |= u; s1 |= u; s2 |= u; s3 |= u; QUARTER_ROUND_FE(s3, t0, t1, t2, t3) QUARTER_ROUND_FE(s2, t3, t0, t1, t2) QUARTER_ROUND_FE(s1, t2, t3, t0, t1) QUARTER_ROUND_FE(s0, t1, t2, t3, t0) // Nr - 2 full rounds: unsigned int r = m_rounds/2 - 1; do { s0 = rk[0]; s1 = rk[1]; s2 = rk[2]; s3 = rk[3]; QUARTER_ROUND_E(t3, s0, s1, s2, s3) QUARTER_ROUND_E(t2, s3, s0, s1, s2) QUARTER_ROUND_E(t1, s2, s3, s0, s1) QUARTER_ROUND_E(t0, s1, s2, s3, s0) t0 = rk[4]; t1 = rk[5]; t2 = rk[6]; t3 = rk[7]; QUARTER_ROUND_E(s3, t0, t1, t2, t3) QUARTER_ROUND_E(s2, t3, t0, t1, t2) QUARTER_ROUND_E(s1, t2, t3, t0, t1) QUARTER_ROUND_E(s0, t1, t2, t3, t0) rk += 8; } while (--r); word32 tbw[4]; byte *const tempBlock = (byte *)tbw; QUARTER_ROUND_LE(t2, 15, 2, 5, 8) QUARTER_ROUND_LE(t1, 11, 14, 1, 4) QUARTER_ROUND_LE(t0, 7, 10, 13, 0) QUARTER_ROUND_LE(t3, 3, 6, 9, 12) Block::Put(xorBlock, outBlock)(tbw[0]^rk[0])(tbw[1]^rk[1])(tbw[2]^rk[2])(tbw[3]^rk[3]); } void Rijndael::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const { #if CRYPTOPP_AESNI_AVAILABLE if (HasAESNI()) { (void)Rijndael::Dec::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif #if (CRYPTOPP_ARM_AES_AVAILABLE) if (HasAES()) { (void)Rijndael::Dec::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif #if (CRYPTOGAMS_ARM_AES) if (HasARMv7()) { CRYPTOGAMS_decrypt(inBlock, xorBlock, outBlock, m_key.begin()); return; } #endif #if (CRYPTOPP_POWER8_AES_AVAILABLE) if (HasAES()) { (void)Rijndael::Dec::AdvancedProcessBlocks(inBlock, xorBlock, outBlock, 16, 0); return; } #endif typedef BlockGetAndPut Block; word32 s0, s1, s2, s3, t0, t1, t2, t3; Block::Get(inBlock)(s0)(s1)(s2)(s3); const word32 *rk = m_key; s0 ^= rk[0]; s1 ^= rk[1]; s2 ^= rk[2]; s3 ^= rk[3]; t0 = rk[4]; t1 = rk[5]; t2 = rk[6]; t3 = rk[7]; rk += 8; // timing attack countermeasure. see comments at top for more details. // also see http://github.com/weidai11/cryptopp/issues/146 const int cacheLineSize = GetCacheLineSize(); unsigned int i; volatile word32 _u = 0; word32 u = _u; #if defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS) for (i=0; i<2048; i+=cacheLineSize) #else for (i=0; i<1024; i+=cacheLineSize) #endif u &= *(const word32 *)(const void *)(((const byte *)Td)+i); u &= Td[255]; s0 |= u; s1 |= u; s2 |= u; s3 |= u; QUARTER_ROUND_FD(s3, t2, t1, t0, t3) QUARTER_ROUND_FD(s2, t1, t0, t3, t2) QUARTER_ROUND_FD(s1, t0, t3, t2, t1) QUARTER_ROUND_FD(s0, t3, t2, t1, t0) // Nr - 2 full rounds: unsigned int r = m_rounds/2 - 1; do { s0 = rk[0]; s1 = rk[1]; s2 = rk[2]; s3 = rk[3]; QUARTER_ROUND_D(t3, s2, s1, s0, s3) QUARTER_ROUND_D(t2, s1, s0, s3, s2) QUARTER_ROUND_D(t1, s0, s3, s2, s1) QUARTER_ROUND_D(t0, s3, s2, s1, s0) t0 = rk[4]; t1 = rk[5]; t2 = rk[6]; t3 = rk[7]; QUARTER_ROUND_D(s3, t2, t1, t0, t3) QUARTER_ROUND_D(s2, t1, t0, t3, t2) QUARTER_ROUND_D(s1, t0, t3, t2, t1) QUARTER_ROUND_D(s0, t3, t2, t1, t0) rk += 8; } while (--r); #if !(defined(CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS)) // timing attack countermeasure. see comments at top for more details // If CRYPTOPP_ALLOW_RIJNDAEL_UNALIGNED_DATA_ACCESS is defined, // QUARTER_ROUND_LD will use Td, which is already preloaded. u = _u; for (i=0; i<256; i+=cacheLineSize) u &= *(const word32 *)(const void *)(Sd+i); u &= *(const word32 *)(const void *)(Sd+252); t0 |= u; t1 |= u; t2 |= u; t3 |= u; #endif word32 tbw[4]; byte *const tempBlock = (byte *)tbw; QUARTER_ROUND_LD(t2, 7, 2, 13, 8) QUARTER_ROUND_LD(t1, 3, 14, 9, 4) QUARTER_ROUND_LD(t0, 15, 10, 5, 0) QUARTER_ROUND_LD(t3, 11, 6, 1, 12) Block::Put(xorBlock, outBlock)(tbw[0]^rk[0])(tbw[1]^rk[1])(tbw[2]^rk[2])(tbw[3]^rk[3]); } // ************************* Assembly Code ************************************ #if CRYPTOPP_MSC_VERSION # pragma warning(disable: 4731) // frame pointer register 'ebp' modified by inline assembly code #endif #endif // #ifndef CRYPTOPP_GENERATE_X64_MASM #if CRYPTOPP_SSE2_ASM_AVAILABLE && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) CRYPTOPP_NAKED void CRYPTOPP_FASTCALL Rijndael_Enc_AdvancedProcessBlocks_SSE2(void *locals, const word32 *k) { CRYPTOPP_UNUSED(locals); CRYPTOPP_UNUSED(k); #if CRYPTOPP_BOOL_X86 #define L_REG esp #define L_INDEX(i) (L_REG+768+i) #define L_INXORBLOCKS L_INBLOCKS+4 #define L_OUTXORBLOCKS L_INBLOCKS+8 #define L_OUTBLOCKS L_INBLOCKS+12 #define L_INCREMENTS L_INDEX(16*15) #define L_SP L_INDEX(16*16) #define L_LENGTH L_INDEX(16*16+4) #define L_KEYS_BEGIN L_INDEX(16*16+8) #define MOVD movd #define MM(i) mm##i #define MXOR(a,b,c) \\ AS2( movzx esi, b)\\ AS2( movd mm7, DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ AS2( pxor MM(a), mm7)\\ #define MMOV(a,b,c) \\ AS2( movzx esi, b)\\ AS2( movd MM(a), DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ #else #define L_REG r8 #define L_INDEX(i) (L_REG+i) #define L_INXORBLOCKS L_INBLOCKS+8 #define L_OUTXORBLOCKS L_INBLOCKS+16 #define L_OUTBLOCKS L_INBLOCKS+24 #define L_INCREMENTS L_INDEX(16*16) #define L_LENGTH L_INDEX(16*18+8) #define L_KEYS_BEGIN L_INDEX(16*19) #define MOVD mov #define MM_0 r9d #define MM_1 r12d #ifdef __GNUC__ #define MM_2 r11d #else #define MM_2 r10d #endif #define MM(i) MM_##i #define MXOR(a,b,c) \\ AS2( movzx esi, b)\\ AS2( xor MM(a), DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ #define MMOV(a,b,c) \\ AS2( movzx esi, b)\\ AS2( mov MM(a), DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ #endif #define L_SUBKEYS L_INDEX(0) #define L_SAVED_X L_SUBKEYS #define L_KEY12 L_INDEX(16*12) #define L_LASTROUND L_INDEX(16*13) #define L_INBLOCKS L_INDEX(16*14) #define MAP0TO4(i) (ASM_MOD(i+3,4)+1) #define XOR(a,b,c) \\ AS2( movzx esi, b)\\ AS2( xor a, DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ #define MOV(a,b,c) \\ AS2( movzx esi, b)\\ AS2( mov a, DWORD PTR [AS_REG_7+8*WORD_REG(si)+MAP0TO4(c)])\\ #ifdef CRYPTOPP_GENERATE_X64_MASM ALIGN 8 Rijndael_Enc_AdvancedProcessBlocks PROC FRAME rex_push_reg rsi push_reg rdi push_reg rbx push_reg r12 .endprolog mov L_REG, rcx mov AS_REG_7, ?Te@rdtable@CryptoPP@@3PA_KA mov edi, DWORD PTR [?g_cacheLineSize@CryptoPP@@3IA] #elif defined(__GNUC__) __asm__ __volatile__ ( INTEL_NOPREFIX #if CRYPTOPP_BOOL_X64 AS2( mov L_REG, rcx) #endif AS_PUSH_IF86(bx) AS_PUSH_IF86(bp) AS2( mov AS_REG_7, WORD_REG(si)) #else AS_PUSH_IF86(si) AS_PUSH_IF86(di) AS_PUSH_IF86(bx) AS_PUSH_IF86(bp) AS2( lea AS_REG_7, [Te]) AS2( mov edi, [g_cacheLineSize]) #endif #if CRYPTOPP_BOOL_X86 AS2( mov [ecx+16*12+16*4], esp) // save esp to L_SP AS2( lea esp, [ecx-768]) #endif // copy subkeys to stack AS2( mov WORD_REG(si), [L_KEYS_BEGIN]) AS2( mov WORD_REG(ax), 16) AS2( and WORD_REG(ax), WORD_REG(si)) AS2( movdqa xmm3, XMMWORD_PTR [WORD_REG(dx)+16+WORD_REG(ax)]) // subkey 1 (non-counter) or 2 (counter) AS2( movdqa [L_KEY12], xmm3) AS2( lea WORD_REG(ax), [WORD_REG(dx)+WORD_REG(ax)+2*16]) AS2( sub WORD_REG(ax), WORD_REG(si)) ASL(0) AS2( movdqa xmm0, [WORD_REG(ax)+WORD_REG(si)]) AS2( movdqa XMMWORD_PTR [L_SUBKEYS+WORD_REG(si)], xmm0) AS2( add WORD_REG(si), 16) AS2( cmp WORD_REG(si), 16*12) ATT_NOPREFIX ASJ( jl, 0, b) INTEL_NOPREFIX // read subkeys 0, 1 and last AS2( movdqa xmm4, [WORD_REG(ax)+WORD_REG(si)]) // last subkey AS2( movdqa xmm1, [WORD_REG(dx)]) // subkey 0 AS2( MOVD MM(1), [WORD_REG(dx)+4*4]) // 0,1,2,3 AS2( mov ebx, [WORD_REG(dx)+5*4]) // 4,5,6,7 AS2( mov ecx, [WORD_REG(dx)+6*4]) // 8,9,10,11 AS2( mov edx, [WORD_REG(dx)+7*4]) // 12,13,14,15 // load table into cache AS2( xor WORD_REG(ax), WORD_REG(ax)) ASL(9) AS2( mov esi, [AS_REG_7+WORD_REG(ax)]) AS2( add WORD_REG(ax), WORD_REG(di)) AS2( mov esi, [AS_REG_7+WORD_REG(ax)]) AS2( add WORD_REG(ax), WORD_REG(di)) AS2( mov esi, [AS_REG_7+WORD_REG(ax)]) AS2( add WORD_REG(ax), WORD_REG(di)) AS2( mov esi, [AS_REG_7+WORD_REG(ax)]) AS2( add WORD_REG(ax), WORD_REG(di)) AS2( cmp WORD_REG(ax), 2048) ATT_NOPREFIX ASJ( jl, 9, b) INTEL_NOPREFIX AS1( lfence) AS2( test DWORD PTR [L_LENGTH], 1) ATT_NOPREFIX ASJ( jz, 8, f) INTEL_NOPREFIX // counter mode one-time setup AS2( mov WORD_REG(si), [L_INBLOCKS]) AS2( movdqu xmm2, [WORD_REG(si)]) // counter AS2( pxor xmm2, xmm1) AS2( psrldq xmm1, 14) AS2( movd eax, xmm1) AS2( mov al, BYTE PTR [WORD_REG(si)+15]) AS2( MOVD MM(2), eax) #if CRYPTOPP_BOOL_X86 AS2( mov eax, 1) AS2( movd mm3, eax) #endif // partial first round, in: xmm2(15,14,13,12;11,10,9,8;7,6,5,4;3,2,1,0), out: mm1, ebx, ecx, edx AS2( movd eax, xmm2) AS2( psrldq xmm2, 4) AS2( movd edi, xmm2) AS2( psrldq xmm2, 4) MXOR( 1, al, 0) // 0 XOR( edx, ah, 1) // 1 AS2( shr eax, 16) XOR( ecx, al, 2) // 2 XOR( ebx, ah, 3) // 3 AS2( mov eax, edi) AS2( movd edi, xmm2) AS2( psrldq xmm2, 4) XOR( ebx, al, 0) // 4 MXOR( 1, ah, 1) // 5 AS2( shr eax, 16) XOR( edx, al, 2) // 6 XOR( ecx, ah, 3) // 7 AS2( mov eax, edi) AS2( movd edi, xmm2) XOR( ecx, al, 0) // 8 XOR( ebx, ah, 1) // 9 AS2( shr eax, 16) MXOR( 1, al, 2) // 10 XOR( edx, ah, 3) // 11 AS2( mov eax, edi) XOR( edx, al, 0) // 12 XOR( ecx, ah, 1) // 13 AS2( shr eax, 16) XOR( ebx, al, 2) // 14 AS2( psrldq xmm2, 3) // partial second round, in: ebx(4,5,6,7), ecx(8,9,10,11), edx(12,13,14,15), out: eax, ebx, edi, mm0 AS2( mov eax, [L_KEY12+0*4]) AS2( mov edi, [L_KEY12+2*4]) AS2( MOVD MM(0), [L_KEY12+3*4]) MXOR( 0, cl, 3) /* 11 */ XOR( edi, bl, 3) /* 7 */ MXOR( 0, bh, 2) /* 6 */ AS2( shr ebx, 16) /* 4,5 */ XOR( eax, bl, 1) /* 5 */ MOV( ebx, bh, 0) /* 4 */ AS2( xor ebx, [L_KEY12+1*4]) XOR( eax, ch, 2) /* 10 */ AS2( shr ecx, 16) /* 8,9 */ XOR( eax, dl, 3) /* 15 */ XOR( ebx, dh, 2) /* 14 */ AS2( shr edx, 16) /* 12,13 */ XOR( edi, ch, 0) /* 8 */ XOR( ebx, cl, 1) /* 9 */ XOR( edi, dl, 1) /* 13 */ MXOR( 0, dh, 0) /* 12 */ AS2( movd ecx, xmm2) AS2( MOVD edx, MM(1)) AS2( MOVD [L_SAVED_X+3*4], MM(0)) AS2( mov [L_SAVED_X+0*4], eax) AS2( mov [L_SAVED_X+1*4], ebx) AS2( mov [L_SAVED_X+2*4], edi) ATT_NOPREFIX ASJ( jmp, 5, f) INTEL_NOPREFIX ASL(3) // non-counter mode per-block setup AS2( MOVD MM(1), [L_KEY12+0*4]) // 0,1,2,3 AS2( mov ebx, [L_KEY12+1*4]) // 4,5,6,7 AS2( mov ecx, [L_KEY12+2*4]) // 8,9,10,11 AS2( mov edx, [L_KEY12+3*4]) // 12,13,14,15 ASL(8) AS2( mov WORD_REG(ax), [L_INBLOCKS]) AS2( movdqu xmm2, [WORD_REG(ax)]) AS2( mov WORD_REG(si), [L_INXORBLOCKS]) AS2( movdqu xmm5, [WORD_REG(si)]) AS2( pxor xmm2, xmm1) AS2( pxor xmm2, xmm5) // first round, in: xmm2(15,14,13,12;11,10,9,8;7,6,5,4;3,2,1,0), out: eax, ebx, ecx, edx AS2( movd eax, xmm2) AS2( psrldq xmm2, 4) AS2( movd edi, xmm2) AS2( psrldq xmm2, 4) MXOR( 1, al, 0) // 0 XOR( edx, ah, 1) // 1 AS2( shr eax, 16) XOR( ecx, al, 2) // 2 XOR( ebx, ah, 3) // 3 AS2( mov eax, edi) AS2( movd edi, xmm2) AS2( psrldq xmm2, 4) XOR( ebx, al, 0) // 4 MXOR( 1, ah, 1) // 5 AS2( shr eax, 16) XOR( edx, al, 2) // 6 XOR( ecx, ah, 3) // 7 AS2( mov eax, edi) AS2( movd edi, xmm2) XOR( ecx, al, 0) // 8 XOR( ebx, ah, 1) // 9 AS2( shr eax, 16) MXOR( 1, al, 2) // 10 XOR( edx, ah, 3) // 11 AS2( mov eax, edi) XOR( edx, al, 0) // 12 XOR( ecx, ah, 1) // 13 AS2( shr eax, 16) XOR( ebx, al, 2) // 14 MXOR( 1, ah, 3) // 15 AS2( MOVD eax, MM(1)) AS2( add L_REG, [L_KEYS_BEGIN]) AS2( add L_REG, 4*16) ATT_NOPREFIX ASJ( jmp, 2, f) INTEL_NOPREFIX ASL(1) // counter-mode per-block setup AS2( MOVD ecx, MM(2)) AS2( MOVD edx, MM(1)) AS2( mov eax, [L_SAVED_X+0*4]) AS2( mov ebx, [L_SAVED_X+1*4]) AS2( xor cl, ch) AS2( and WORD_REG(cx), 255) ASL(5) #if CRYPTOPP_BOOL_X86 AS2( paddb MM(2), mm3) #else AS2( add MM(2), 1) #endif // remaining part of second round, in: edx(previous round),esi(keyed counter byte) eax,ebx,[L_SAVED_X+2*4],[L_SAVED_X+3*4], out: eax,ebx,ecx,edx AS2( xor edx, DWORD PTR [AS_REG_7+WORD_REG(cx)*8+3]) XOR( ebx, dl, 3) MOV( ecx, dh, 2) AS2( shr edx, 16) AS2( xor ecx, [L_SAVED_X+2*4]) XOR( eax, dh, 0) MOV( edx, dl, 1) AS2( xor edx, [L_SAVED_X+3*4]) AS2( add L_REG, [L_KEYS_BEGIN]) AS2( add L_REG, 3*16) ATT_NOPREFIX ASJ( jmp, 4, f) INTEL_NOPREFIX // in: eax(0,1,2,3), ebx(4,5,6,7), ecx(8,9,10,11), edx(12,13,14,15) // out: eax, ebx, edi, mm0 #define ROUND() \\ MXOR( 0, cl, 3) /* 11 */\\ AS2( mov cl, al) /* 8,9,10,3 */\\ XOR( edi, ah, 2) /* 2 */\\ AS2( shr eax, 16) /* 0,1 */\\ XOR( edi, bl, 3) /* 7 */\\ MXOR( 0, bh, 2) /* 6 */\\ AS2( shr ebx, 16) /* 4,5 */\\ MXOR( 0, al, 1) /* 1 */\\ MOV( eax, ah, 0) /* 0 */\\ XOR( eax, bl, 1) /* 5 */\\ MOV( ebx, bh, 0) /* 4 */\\ XOR( eax, ch, 2) /* 10 */\\ XOR( ebx, cl, 3) /* 3 */\\ AS2( shr ecx, 16) /* 8,9 */\\ XOR( eax, dl, 3) /* 15 */\\ XOR( ebx, dh, 2) /* 14 */\\ AS2( shr edx, 16) /* 12,13 */\\ XOR( edi, ch, 0) /* 8 */\\ XOR( ebx, cl, 1) /* 9 */\\ XOR( edi, dl, 1) /* 13 */\\ MXOR( 0, dh, 0) /* 12 */\\ ASL(2) // 2-round loop AS2( MOVD MM(0), [L_SUBKEYS-4*16+3*4]) AS2( mov edi, [L_SUBKEYS-4*16+2*4]) ROUND() AS2( mov ecx, edi) AS2( xor eax, [L_SUBKEYS-4*16+0*4]) AS2( xor ebx, [L_SUBKEYS-4*16+1*4]) AS2( MOVD edx, MM(0)) ASL(4) AS2( MOVD MM(0), [L_SUBKEYS-4*16+7*4]) AS2( mov edi, [L_SUBKEYS-4*16+6*4]) ROUND() AS2( mov ecx, edi) AS2( xor eax, [L_SUBKEYS-4*16+4*4]) AS2( xor ebx, [L_SUBKEYS-4*16+5*4]) AS2( MOVD edx, MM(0)) AS2( add L_REG, 32) AS2( test L_REG, 255) ATT_NOPREFIX ASJ( jnz, 2, b) INTEL_NOPREFIX AS2( sub L_REG, 16*16) #define LAST(a, b, c) \\ AS2( movzx esi, a )\\ AS2( movzx edi, BYTE PTR [AS_REG_7+WORD_REG(si)*8+1] )\\ AS2( movzx esi, b )\\ AS2( xor edi, DWORD PTR [AS_REG_7+WORD_REG(si)*8+0] )\\ AS2( mov WORD PTR [L_LASTROUND+c], di )\\ // last round LAST(ch, dl, 2) LAST(dh, al, 6) AS2( shr edx, 16) LAST(ah, bl, 10) AS2( shr eax, 16) LAST(bh, cl, 14) AS2( shr ebx, 16) LAST(dh, al, 12) AS2( shr ecx, 16) LAST(ah, bl, 0) LAST(bh, cl, 4) LAST(ch, dl, 8) AS2( mov WORD_REG(ax), [L_OUTXORBLOCKS]) AS2( mov WORD_REG(bx), [L_OUTBLOCKS]) AS2( mov WORD_REG(cx), [L_LENGTH]) AS2( sub WORD_REG(cx), 16) AS2( movdqu xmm2, [WORD_REG(ax)]) AS2( pxor xmm2, xmm4) #if CRYPTOPP_BOOL_X86 AS2( movdqa xmm0, [L_INCREMENTS]) AS2( paddd xmm0, [L_INBLOCKS]) AS2( movdqa [L_INBLOCKS], xmm0) #else AS2( movdqa xmm0, [L_INCREMENTS+16]) AS2( paddq xmm0, [L_INBLOCKS+16]) AS2( movdqa [L_INBLOCKS+16], xmm0) #endif AS2( pxor xmm2, [L_LASTROUND]) AS2( movdqu [WORD_REG(bx)], xmm2) ATT_NOPREFIX ASJ( jle, 7, f) INTEL_NOPREFIX AS2( mov [L_LENGTH], WORD_REG(cx)) AS2( test WORD_REG(cx), 1) ATT_NOPREFIX ASJ( jnz, 1, b) INTEL_NOPREFIX #if CRYPTOPP_BOOL_X64 AS2( movdqa xmm0, [L_INCREMENTS]) AS2( paddq xmm0, [L_INBLOCKS]) AS2( movdqa [L_INBLOCKS], xmm0) #endif ATT_NOPREFIX ASJ( jmp, 3, b) INTEL_NOPREFIX ASL(7) // erase keys on stack AS2( xorps xmm0, xmm0) AS2( lea WORD_REG(ax), [L_SUBKEYS+7*16]) AS2( movaps [WORD_REG(ax)-7*16], xmm0) AS2( movaps [WORD_REG(ax)-6*16], xmm0) AS2( movaps [WORD_REG(ax)-5*16], xmm0) AS2( movaps [WORD_REG(ax)-4*16], xmm0) AS2( movaps [WORD_REG(ax)-3*16], xmm0) AS2( movaps [WORD_REG(ax)-2*16], xmm0) AS2( movaps [WORD_REG(ax)-1*16], xmm0) AS2( movaps [WORD_REG(ax)+0*16], xmm0) AS2( movaps [WORD_REG(ax)+1*16], xmm0) AS2( movaps [WORD_REG(ax)+2*16], xmm0) AS2( movaps [WORD_REG(ax)+3*16], xmm0) AS2( movaps [WORD_REG(ax)+4*16], xmm0) AS2( movaps [WORD_REG(ax)+5*16], xmm0) AS2( movaps [WORD_REG(ax)+6*16], xmm0) #if CRYPTOPP_BOOL_X86 AS2( mov esp, [L_SP]) AS1( emms) #endif AS_POP_IF86(bp) AS_POP_IF86(bx) #if defined(_MSC_VER) && CRYPTOPP_BOOL_X86 AS_POP_IF86(di) AS_POP_IF86(si) AS1(ret) #endif #ifdef CRYPTOPP_GENERATE_X64_MASM pop r12 pop rbx pop rdi pop rsi ret Rijndael_Enc_AdvancedProcessBlocks ENDP #endif #ifdef __GNUC__ ATT_PREFIX : : ""c"" (locals), ""d"" (k), ""S"" (Te), ""D"" (g_cacheLineSize) : ""memory"", ""cc"", ""%eax"" #if CRYPTOPP_BOOL_X64 , ""%rbx"", ""%r8"", ""%r9"", ""%r10"", ""%r11"", ""%r12"" #endif ); #endif } #endif #ifndef CRYPTOPP_GENERATE_X64_MASM #ifdef CRYPTOPP_X64_MASM_AVAILABLE extern ""C"" { void Rijndael_Enc_AdvancedProcessBlocks_SSE2(void *locals, const word32 *k); } #endif #if CRYPTOPP_RIJNDAEL_ADVANCED_PROCESS_BLOCKS size_t Rijndael::Enc::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const { #if CRYPTOPP_AESNI_AVAILABLE if (HasAESNI()) return Rijndael_Enc_AdvancedProcessBlocks_AESNI(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif #if CRYPTOPP_ARM_AES_AVAILABLE if (HasAES()) return Rijndael_Enc_AdvancedProcessBlocks_ARMV8(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif #if CRYPTOPP_POWER8_AES_AVAILABLE if (HasAES()) return Rijndael_Enc_AdvancedProcessBlocks128_6x1_ALTIVEC(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif #if (CRYPTOPP_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)) && !defined(CRYPTOPP_DISABLE_RIJNDAEL_ASM) if (HasSSE2()) { if (length < BLOCKSIZE) return length; static const byte *zeros = (const byte*)(Te+256); m_aliasBlock.SetMark(m_aliasBlock.size()); byte *space = NULLPTR, *originalSpace = const_cast(m_aliasBlock.data()); // round up to nearest 256 byte boundary space = originalSpace + (s_aliasBlockSize - (uintptr_t)originalSpace % s_aliasBlockSize) % s_aliasBlockSize; while (AliasedWithTable(space, space + sizeof(Locals))) { space += 256; CRYPTOPP_ASSERT(space < (originalSpace + s_aliasPageSize)); } size_t increment = BLOCKSIZE; if (flags & BT_ReverseDirection) { CRYPTOPP_ASSERT(length % BLOCKSIZE == 0); inBlocks += length - BLOCKSIZE; xorBlocks += length - BLOCKSIZE; outBlocks += length - BLOCKSIZE; increment = 0-increment; } Locals &locals = *(Locals *)(void *)space; locals.inBlocks = inBlocks; locals.inXorBlocks = (flags & BT_XorInput) && xorBlocks ? xorBlocks : zeros; locals.outXorBlocks = (flags & BT_XorInput) || !xorBlocks ? zeros : xorBlocks; locals.outBlocks = outBlocks; locals.inIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : increment; locals.inXorIncrement = (flags & BT_XorInput) && xorBlocks ? increment : 0; locals.outXorIncrement = (flags & BT_XorInput) || !xorBlocks ? 0 : increment; locals.outIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : increment; locals.lengthAndCounterFlag = length - (length%16) - bool(flags & BT_InBlockIsCounter); int keysToCopy = m_rounds - (flags & BT_InBlockIsCounter ? 3 : 2); locals.keysBegin = (12-keysToCopy)*16; Rijndael_Enc_AdvancedProcessBlocks_SSE2(&locals, m_key); return length % BLOCKSIZE; } #endif return BlockTransformation::AdvancedProcessBlocks(inBlocks, xorBlocks, outBlocks, length, flags); } size_t Rijndael::Dec::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const { #if CRYPTOPP_AESNI_AVAILABLE if (HasAESNI()) return Rijndael_Dec_AdvancedProcessBlocks_AESNI(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif #if CRYPTOPP_ARM_AES_AVAILABLE if (HasAES()) return Rijndael_Dec_AdvancedProcessBlocks_ARMV8(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif #if CRYPTOPP_POWER8_AES_AVAILABLE if (HasAES()) return Rijndael_Dec_AdvancedProcessBlocks128_6x1_ALTIVEC(m_key, m_rounds, inBlocks, xorBlocks, outBlocks, length, flags); #endif return BlockTransformation::AdvancedProcessBlocks(inBlocks, xorBlocks, outBlocks, length, flags); } #endif // CRYPTOPP_RIJNDAEL_ADVANCED_PROCESS_BLOCKS NAMESPACE_END #endif #endif ",16143,True,2870.142471117738,median "/********************************************************************** * File: oldbasel.cpp (Formerly oldbl.c) * Description: A re-implementation of the old baseline algorithm. * Author: Ray Smith * Created: Wed Oct 6 09:41:48 BST 1993 * * (C) Copyright 1993, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the ""License""); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an ""AS IS"" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include ""ccstruct.h"" #include ""statistc.h"" #include ""quadlsq.h"" #include ""detlinefit.h"" #include ""makerow.h"" #include ""drawtord.h"" #include ""oldbasel.h"" #include ""textord.h"" #include ""tprintf.h"" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include ""config_auto.h"" #endif #define EXTERN EXTERN BOOL_VAR (textord_really_old_xheight, FALSE, ""Use original wiseowl xheight""); EXTERN BOOL_VAR (textord_oldbl_debug, FALSE, ""Debug old baseline generation""); EXTERN BOOL_VAR (textord_debug_baselines, FALSE, ""Debug baseline generation""); EXTERN BOOL_VAR (textord_oldbl_paradef, TRUE, ""Use para default mechanism""); EXTERN BOOL_VAR (textord_oldbl_split_splines, TRUE, ""Split stepped splines""); EXTERN BOOL_VAR (textord_oldbl_merge_parts, TRUE, ""Merge suspect partitions""); EXTERN BOOL_VAR (oldbl_corrfix, TRUE, ""Improve correlation of heights""); EXTERN BOOL_VAR (oldbl_xhfix, FALSE, ""Fix bug in modes threshold for xheights""); EXTERN BOOL_VAR(textord_ocropus_mode, FALSE, ""Make baselines for ocropus""); EXTERN double_VAR (oldbl_xhfract, 0.4, ""Fraction of est allowed in calc""); EXTERN INT_VAR (oldbl_holed_losscount, 10, ""Max lost before fallback line used""); EXTERN double_VAR (oldbl_dot_error_size, 1.26, ""Max aspect ratio of a dot""); EXTERN double_VAR (textord_oldbl_jumplimit, 0.15, ""X fraction for new partition""); #define TURNLIMIT 1 /*min size for turning point */ #define X_HEIGHT_FRACTION 0.7 /*x-height/caps height */ #define DESCENDER_FRACTION 0.5 /*descender/x-height */ #define MIN_ASC_FRACTION 0.20 /*min size of ascenders */ #define MIN_DESC_FRACTION 0.25 /*min size of descenders */ #define MINASCRISE 2.0 /*min ascender/desc step */ #define MAXHEIGHTVARIANCE 0.15 /*accepted variation in x-height */ #define MAXHEIGHT 300 /*max blob height */ #define MAXOVERLAP 0.1 /*max 10% missed overlap */ #define MAXBADRUN 2 /*max non best for failed */ #define HEIGHTBUCKETS 200 /* Num of buckets */ #define DELTAHEIGHT 5.0 /* Small amount of diff */ #define GOODHEIGHT 5 #define MAXLOOPS 10 #define MODENUM 10 #define MAXPARTS 6 #define SPLINESIZE 23 #define ABS(x) ((x)<0 ? (-(x)) : (x)) namespace tesseract { /********************************************************************** * make_old_baselines * * Top level function to make baselines the old way. **********************************************************************/ void Textord::make_old_baselines(TO_BLOCK *block, // block to do BOOL8 testing_on, // correct orientation float gradient) { QSPLINE *prev_baseline; // baseline of previous row TO_ROW *row; // current row TO_ROW_IT row_it = block->get_rows(); BLOBNBOX_IT blob_it; prev_baseline = NULL; // nothing yet for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) { row = row_it.data(); find_textlines(block, row, 2, NULL); if (row->xheight <= 0 && prev_baseline != NULL) find_textlines(block, row, 2, prev_baseline); if (row->xheight > 0) { // was a good one prev_baseline = &row->baseline; } else { prev_baseline = NULL; blob_it.set_to_list(row->blob_list()); if (textord_debug_baselines) tprintf(""Row baseline generation failed on row at (%d,%d)\\n"", blob_it.data()->bounding_box().left(), blob_it.data()->bounding_box().bottom()); } } correlate_lines(block, gradient); block->block->set_xheight(block->xheight); } /********************************************************************** * correlate_lines * * Correlate the x-heights and ascender heights of a block to fill-in * the ascender height and descender height for rows without one. * Also fix baselines of rows without a decent fit. **********************************************************************/ void Textord::correlate_lines(TO_BLOCK *block, float gradient) { TO_ROW **rows; //array of ptrs int rowcount; /*no of rows to do */ int rowindex; /*no of row */ // iterator TO_ROW_IT row_it = block->get_rows (); rowcount = row_it.length (); if (rowcount == 0) { //default value block->xheight = block->line_size; return; /*none to do */ } rows = (TO_ROW **) alloc_mem (rowcount * sizeof (TO_ROW *)); rowindex = 0; for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) //make array rows[rowindex++] = row_it.data (); /*try to fix bad lines */ correlate_neighbours(block, rows, rowcount); if (textord_really_old_xheight || textord_old_xheight) { block->xheight = (float) correlate_with_stats(rows, rowcount, block); if (block->xheight <= 0) block->xheight = block->line_size * tesseract::CCStruct::kXHeightFraction; if (block->xheight < textord_min_xheight) block->xheight = (float) textord_min_xheight; } else { compute_block_xheight(block, gradient); } free_mem(rows); } /********************************************************************** * correlate_neighbours * * Try to fix rows that had a bad spline fit by using neighbours. **********************************************************************/ void Textord::correlate_neighbours(TO_BLOCK *block, // block rows are in. TO_ROW **rows, // rows of block. int rowcount) { // no of rows to do. TO_ROW *row; /*current row */ int rowindex; /*no of row */ int otherrow; /*second row */ int upperrow; /*row above to use */ int lowerrow; /*row below to use */ float biggest; for (rowindex = 0; rowindex < rowcount; rowindex++) { row = rows[rowindex]; /*current row */ if (row->xheight < 0) { /*quadratic failed */ for (otherrow = rowindex - 2; otherrow >= 0 && (rows[otherrow]->xheight < 0.0 || !row->baseline.overlap (&rows[otherrow]->baseline, MAXOVERLAP)); otherrow--); upperrow = otherrow; /*decent row above */ for (otherrow = rowindex + 1; otherrow < rowcount && (rows[otherrow]->xheight < 0.0 || !row->baseline.overlap (&rows[otherrow]->baseline, MAXOVERLAP)); otherrow++); lowerrow = otherrow; /*decent row below */ if (upperrow >= 0) find_textlines(block, row, 2, &rows[upperrow]->baseline); if (row->xheight < 0 && lowerrow < rowcount) find_textlines(block, row, 2, &rows[lowerrow]->baseline); if (row->xheight < 0) { if (upperrow >= 0) find_textlines(block, row, 1, &rows[upperrow]->baseline); else if (lowerrow < rowcount) find_textlines(block, row, 1, &rows[lowerrow]->baseline); } } } for (biggest = 0.0f, rowindex = 0; rowindex < rowcount; rowindex++) { row = rows[rowindex]; /*current row */ if (row->xheight < 0) /*linear failed */ /*make do */ row->xheight = -row->xheight; biggest = MAX (biggest, row->xheight); } } /********************************************************************** * correlate_with_stats * * correlate the x-heights and ascender heights of a block to fill-in * the ascender height and descender height for rows without one. **********************************************************************/ int Textord::correlate_with_stats(TO_ROW **rows, // rows of block. int rowcount, // no of rows to do. TO_BLOCK* block) { TO_ROW *row; /*current row */ int rowindex; /*no of row */ float lineheight; /*mean x-height */ float ascheight; /*average ascenders */ float minascheight; /*min allowed ascheight */ int xcount; /*no of samples for xheight */ float fullheight; /*mean top height */ int fullcount; /*no of samples */ float descheight; /*mean descender drop */ float mindescheight; /*min allowed descheight */ int desccount; /*no of samples */ /*no samples */ xcount = fullcount = desccount = 0; lineheight = ascheight = fullheight = descheight = 0.0; for (rowindex = 0; rowindex < rowcount; rowindex++) { row = rows[rowindex]; /*current row */ if (row->ascrise > 0.0) { /*got ascenders? */ lineheight += row->xheight;/*average x-heights */ ascheight += row->ascrise; /*average ascenders */ xcount++; } else { fullheight += row->xheight;/*assume full height */ fullcount++; } if (row->descdrop < 0.0) { /*got descenders? */ /*average descenders */ descheight += row->descdrop; desccount++; } } if (xcount > 0 && (!oldbl_corrfix || xcount >= fullcount)) { lineheight /= xcount; /*average x-height */ /*average caps height */ fullheight = lineheight + ascheight / xcount; /*must be decent size */ if (fullheight < lineheight * (1 + MIN_ASC_FRACTION)) fullheight = lineheight * (1 + MIN_ASC_FRACTION); } else { fullheight /= fullcount; /*average max height */ /*guess x-height */ lineheight = fullheight * X_HEIGHT_FRACTION; } if (desccount > 0 && (!oldbl_corrfix || desccount >= rowcount / 2)) descheight /= desccount; /*average descenders */ else /*guess descenders */ descheight = -lineheight * DESCENDER_FRACTION; if (lineheight > 0.0f) block->block->set_cell_over_xheight((fullheight - descheight) / lineheight); minascheight = lineheight * MIN_ASC_FRACTION; mindescheight = -lineheight * MIN_DESC_FRACTION; for (rowindex = 0; rowindex < rowcount; rowindex++) { row = rows[rowindex]; /*do each row */ row->all_caps = FALSE; if (row->ascrise / row->xheight < MIN_ASC_FRACTION) { /*no ascenders */ if (row->xheight >= lineheight * (1 - MAXHEIGHTVARIANCE) && row->xheight <= lineheight * (1 + MAXHEIGHTVARIANCE)) { row->ascrise = fullheight - lineheight; /*set to average */ row->xheight = lineheight; } else if (row->xheight >= fullheight * (1 - MAXHEIGHTVARIANCE) && row->xheight <= fullheight * (1 + MAXHEIGHTVARIANCE)) { row->ascrise = row->xheight - lineheight; /*set to average */ row->xheight = lineheight; row->all_caps = TRUE; } else { row->ascrise = (fullheight - lineheight) * row->xheight / fullheight; /*scale it */ row->xheight -= row->ascrise; row->all_caps = TRUE; } if (row->ascrise < minascheight) row->ascrise = row->xheight * ((1.0 - X_HEIGHT_FRACTION) / X_HEIGHT_FRACTION); } if (row->descdrop > mindescheight) { if (row->xheight >= lineheight * (1 - MAXHEIGHTVARIANCE) && row->xheight <= lineheight * (1 + MAXHEIGHTVARIANCE)) /*set to average */ row->descdrop = descheight; else row->descdrop = -row->xheight * DESCENDER_FRACTION; } } return (int) lineheight; //block xheight } /********************************************************************** * find_textlines * * Compute the baseline for the given row. **********************************************************************/ void Textord::find_textlines(TO_BLOCK *block, // block row is in TO_ROW *row, // row to do int degree, // required approximation QSPLINE *spline) { // starting spline int partcount; /*no of partitions of */ BOOL8 holed_line = FALSE; //lost too many blobs int bestpart; /*biggest partition */ char *partids; /*partition no of each blob */ int partsizes[MAXPARTS]; /*no in each partition */ int lineheight; /*guessed x-height */ float jumplimit; /*allowed delta change */ int *xcoords; /*useful sample points */ int *ycoords; /*useful sample points */ TBOX *blobcoords; /*edges of blob rectangles */ int blobcount; /*no of blobs on line */ float *ydiffs; /*diffs from 1st approx */ int pointcount; /*no of coords */ int xstarts[SPLINESIZE + 1]; //segment boundaries int segments; //no of segments //no of blobs in row blobcount = row->blob_list ()->length (); partids = (char *) alloc_mem (blobcount * sizeof (char)); xcoords = (int *) alloc_mem (blobcount * sizeof (int)); ycoords = (int *) alloc_mem (blobcount * sizeof (int)); blobcoords = (TBOX *) alloc_mem (blobcount * sizeof (TBOX)); ydiffs = (float *) alloc_mem (blobcount * sizeof (float)); lineheight = get_blob_coords (row, (int) block->line_size, blobcoords, holed_line, blobcount); /*limit for line change */ jumplimit = lineheight * textord_oldbl_jumplimit; if (jumplimit < MINASCRISE) jumplimit = MINASCRISE; if (textord_oldbl_debug) { tprintf (""\\nInput height=%g, Estimate x-height=%d pixels, jumplimit=%.2f\\n"", block->line_size, lineheight, jumplimit); } if (holed_line) make_holed_baseline (blobcoords, blobcount, spline, &row->baseline, row->line_m ()); else make_first_baseline (blobcoords, blobcount, xcoords, ycoords, spline, &row->baseline, jumplimit); #ifndef GRAPHICS_DISABLED if (textord_show_final_rows) row->baseline.plot (to_win, ScrollView::GOLDENROD); #endif if (blobcount > 1) { bestpart = partition_line (blobcoords, blobcount, &partcount, partids, partsizes, &row->baseline, jumplimit, ydiffs); pointcount = partition_coords (blobcoords, blobcount, partids, bestpart, xcoords, ycoords); segments = segment_spline (blobcoords, blobcount, xcoords, ycoords, degree, pointcount, xstarts); if (!holed_line) { do { row->baseline = QSPLINE (xstarts, segments, xcoords, ycoords, pointcount, degree); } while (textord_oldbl_split_splines && split_stepped_spline (&row->baseline, jumplimit / 2, xcoords, xstarts, segments)); } find_lesser_parts(row, blobcoords, blobcount, partids, partsizes, partcount, bestpart); } else { row->xheight = -1.0f; /*failed */ row->descdrop = 0.0f; row->ascrise = 0.0f; } row->baseline.extrapolate (row->line_m (), block->block->bounding_box ().left (), block->block->bounding_box ().right ()); if (textord_really_old_xheight) { old_first_xheight (row, blobcoords, lineheight, blobcount, &row->baseline, jumplimit); } else if (textord_old_xheight) { make_first_xheight (row, blobcoords, lineheight, (int) block->line_size, blobcount, &row->baseline, jumplimit); } else { compute_row_xheight(row, block->block->classify_rotation(), row->line_m(), block->line_size); } free_mem(partids); free_mem(xcoords); free_mem(ycoords); free_mem(blobcoords); free_mem(ydiffs); } } // namespace tesseract. /********************************************************************** * get_blob_coords * * Fill the blobcoords array with the coordinates of the blobs * in the row. The return value is the first guess at the line height. **********************************************************************/ int get_blob_coords( //get boxes TO_ROW *row, //row to use inT32 lineheight, //block level TBOX *blobcoords, //ouput boxes BOOL8 &holed_line, //lost a lot of blobs int &outcount //no of real blobs ) { //blobs BLOBNBOX_IT blob_it = row->blob_list (); int blobindex; /*no along text line */ int losscount; //lost blobs int maxlosscount; //greatest lost blobs /*height stat collection */ STATS heightstat (0, MAXHEIGHT); if (blob_it.empty ()) return 0; //none maxlosscount = 0; losscount = 0; blob_it.mark_cycle_pt (); blobindex = 0; do { blobcoords[blobindex] = box_next_pre_chopped (&blob_it); if (blobcoords[blobindex].height () > lineheight * 0.25) heightstat.add (blobcoords[blobindex].height (), 1); if (blobindex == 0 || blobcoords[blobindex].height () > lineheight * 0.25 || blob_it.cycled_list ()) { blobindex++; /*no of merged blobs */ losscount = 0; } else { if (blobcoords[blobindex].height () < blobcoords[blobindex].width () * oldbl_dot_error_size && blobcoords[blobindex].width () < blobcoords[blobindex].height () * oldbl_dot_error_size) { //counts as dot blobindex++; losscount = 0; } else { losscount++; //lost it if (losscount > maxlosscount) //remember max maxlosscount = losscount; } } } while (!blob_it.cycled_list ()); holed_line = maxlosscount > oldbl_holed_losscount; outcount = blobindex; /*total blobs */ if (heightstat.get_total () > 1) /*guess x-height */ return (int) heightstat.ile (0.25); else return blobcoords[0].height (); } /********************************************************************** * make_first_baseline * * Make the first estimate at a baseline, either by shifting * a supplied previous spline, or by doing a piecewise linear * approximation using all the blobs. **********************************************************************/ void make_first_baseline ( //initial approximation TBOX blobcoords[], /*blob bounding boxes */ int blobcount, /*no of blobcoords */ int xcoords[], /*coords for spline */ int ycoords[], /*approximator */ QSPLINE * spline, /*initial spline */ QSPLINE * baseline, /*output spline */ float jumplimit /*guess half descenders */ ) { int leftedge; /*left edge of line */ int rightedge; /*right edge of line */ int blobindex; /*current blob */ int segment; /*current segment */ float prevy, thisy, nexty; /*3 y coords */ float y1, y2, y3; /*3 smooth blobs */ float maxmax, minmin; /*absolute limits */ int x2 = 0; /*right edge of old y3 */ int ycount; /*no of ycoords in use */ float yturns[SPLINESIZE]; /*y coords of turn pts */ int xturns[SPLINESIZE]; /*xcoords of turn pts */ int xstarts[SPLINESIZE + 1]; int segments; //no of segments ICOORD shift; //shift of spline prevy = 0; /*left edge of row */ leftedge = blobcoords[0].left (); /*right edge of line */ rightedge = blobcoords[blobcount - 1].right (); if (spline == NULL /*no given spline */ || spline->segments < 3 /*or trivial */ /*or too non-overlap */ || spline->xcoords[1] > leftedge + MAXOVERLAP * (rightedge - leftedge) || spline->xcoords[spline->segments - 1] < rightedge - MAXOVERLAP * (rightedge - leftedge)) { if (textord_oldbl_paradef) return; //use default xstarts[0] = blobcoords[0].left () - 1; for (blobindex = 0; blobindex < blobcount; blobindex++) { xcoords[blobindex] = (blobcoords[blobindex].left () + blobcoords[blobindex].right ()) / 2; ycoords[blobindex] = blobcoords[blobindex].bottom (); } xstarts[1] = blobcoords[blobcount - 1].right () + 1; segments = 1; /*no of segments */ /*linear */ *baseline = QSPLINE (xstarts, segments, xcoords, ycoords, blobcount, 1); if (blobcount >= 3) { y1 = y2 = y3 = 0.0f; ycount = 0; segment = 0; /*no of segments */ maxmax = minmin = 0.0f; thisy = ycoords[0] - baseline->y (xcoords[0]); nexty = ycoords[1] - baseline->y (xcoords[1]); for (blobindex = 2; blobindex < blobcount; blobindex++) { prevy = thisy; /*shift ycoords */ thisy = nexty; nexty = ycoords[blobindex] - baseline->y (xcoords[blobindex]); /*middle of smooth y */ if (ABS (thisy - prevy) < jumplimit && ABS (thisy - nexty) < jumplimit) { y1 = y2; /*shift window */ y2 = y3; y3 = thisy; /*middle point */ ycount++; /*local max */ if (ycount >= 3 && ((y1 < y2 && y2 >= y3) /*local min */ || (y1 > y2 && y2 <= y3))) { if (segment < SPLINESIZE - 2) { /*turning pt */ xturns[segment] = x2; yturns[segment] = y2; segment++; /*no of spline segs */ } } if (ycount == 1) { maxmax = minmin = y3;/*initialise limits */ } else { if (y3 > maxmax) maxmax = y3; /*biggest max */ if (y3 < minmin) minmin = y3; /*smallest min */ } /*possible turning pt */ x2 = blobcoords[blobindex - 1].right (); } } jumplimit *= 1.2; /*must be wavy */ if (maxmax - minmin > jumplimit) { ycount = segment; /*no of segments */ for (blobindex = 0, segment = 1; blobindex < ycount; blobindex++) { if (yturns[blobindex] > minmin + jumplimit || yturns[blobindex] < maxmax - jumplimit) { /*significant peak */ if (segment == 1 || yturns[blobindex] > prevy + jumplimit || yturns[blobindex] < prevy - jumplimit) { /*different to previous */ xstarts[segment] = xturns[blobindex]; segment++; prevy = yturns[blobindex]; } /*bigger max */ else if ((prevy > minmin + jumplimit && yturns[blobindex] > prevy) /*smaller min */ || (prevy < maxmax - jumplimit && yturns[blobindex] < prevy)) { xstarts[segment - 1] = xturns[blobindex]; /*improved previous */ prevy = yturns[blobindex]; } } } xstarts[segment] = blobcoords[blobcount - 1].right () + 1; segments = segment; /*no of segments */ /*linear */ *baseline = QSPLINE (xstarts, segments, xcoords, ycoords, blobcount, 1); } } } else { *baseline = *spline; /*copy it */ shift = ICOORD (0, (inT16) (blobcoords[0].bottom () - spline->y (blobcoords[0].right ()))); baseline->move (shift); } } /********************************************************************** * make_holed_baseline * * Make the first estimate at a baseline, either by shifting * a supplied previous spline, or by doing a piecewise linear * approximation using all the blobs. **********************************************************************/ void make_holed_baseline ( //initial approximation TBOX blobcoords[], /*blob bounding boxes */ int blobcount, /*no of blobcoords */ QSPLINE * spline, /*initial spline */ QSPLINE * baseline, /*output spline */ float gradient //of line ) { int leftedge; /*left edge of line */ int rightedge; /*right edge of line */ int blobindex; /*current blob */ float x; //centre of row ICOORD shift; //shift of spline tesseract::DetLineFit lms; // straight baseline inT32 xstarts[2]; //straight line double coeffs[3]; float c; //line parameter /*left edge of row */ leftedge = blobcoords[0].left (); /*right edge of line */ rightedge = blobcoords[blobcount - 1].right(); for (blobindex = 0; blobindex < blobcount; blobindex++) { lms.Add(ICOORD((blobcoords[blobindex].left() + blobcoords[blobindex].right()) / 2, blobcoords[blobindex].bottom())); } lms.ConstrainedFit(gradient, &c); xstarts[0] = leftedge; xstarts[1] = rightedge; coeffs[0] = 0; coeffs[1] = gradient; coeffs[2] = c; *baseline = QSPLINE (1, xstarts, coeffs); if (spline != NULL /*no given spline */ && spline->segments >= 3 /*or trivial */ /*or too non-overlap */ && spline->xcoords[1] <= leftedge + MAXOVERLAP * (rightedge - leftedge) && spline->xcoords[spline->segments - 1] >= rightedge - MAXOVERLAP * (rightedge - leftedge)) { *baseline = *spline; /*copy it */ x = (leftedge + rightedge) / 2.0; shift = ICOORD (0, (inT16) (gradient * x + c - spline->y (x))); baseline->move (shift); } } /********************************************************************** * partition_line * * Partition a row of blobs into different groups of continuous * y position. jumplimit specifies the max allowable limit on a jump * before a new partition is started. * The return value is the biggest partition **********************************************************************/ int partition_line ( //partition blobs TBOX blobcoords[], //bounding boxes int blobcount, /*no of blobs on row */ int *numparts, /*number of partitions */ char partids[], /*partition no of each blob */ int partsizes[], /*no in each partition */ QSPLINE * spline, /*curve to fit to */ float jumplimit, /*allowed delta change */ float ydiffs[] /*diff from spline */ ) { int blobindex; /*no along text line */ int bestpart; /*best new partition */ int biggestpart; /*part with most members */ float diff; /*difference from line */ int startx; /*index of start blob */ float partdiffs[MAXPARTS]; /*step between parts */ for (bestpart = 0; bestpart < MAXPARTS; bestpart++) partsizes[bestpart] = 0; /*zero them all */ startx = get_ydiffs (blobcoords, blobcount, spline, ydiffs); *numparts = 1; /*1 partition */ bestpart = -1; /*first point */ float drift = 0.0f; float last_delta = 0.0f; for (blobindex = startx; blobindex < blobcount; blobindex++) { /*do each blob in row */ diff = ydiffs[blobindex]; /*diff from line */ if (textord_oldbl_debug) { tprintf (""%d(%d,%d), "", blobindex, blobcoords[blobindex].left (), blobcoords[blobindex].bottom ()); } bestpart = choose_partition(diff, partdiffs, bestpart, jumplimit, &drift, &last_delta, numparts); /*record partition */ partids[blobindex] = bestpart; partsizes[bestpart]++; /*another in it */ } bestpart = -1; /*first point */ drift = 0.0f; last_delta = 0.0f; partsizes[0]--; /*doing 1st pt again */ /*do each blob in row */ for (blobindex = startx; blobindex >= 0; blobindex--) { diff = ydiffs[blobindex]; /*diff from line */ if (textord_oldbl_debug) { tprintf (""%d(%d,%d), "", blobindex, blobcoords[blobindex].left (), blobcoords[blobindex].bottom ()); } bestpart = choose_partition(diff, partdiffs, bestpart, jumplimit, &drift, &last_delta, numparts); /*record partition */ partids[blobindex] = bestpart; partsizes[bestpart]++; /*another in it */ } for (biggestpart = 0, bestpart = 1; bestpart < *numparts; bestpart++) if (partsizes[bestpart] >= partsizes[biggestpart]) biggestpart = bestpart; /*new biggest */ if (textord_oldbl_merge_parts) merge_oldbl_parts(blobcoords, blobcount, partids, partsizes, biggestpart, jumplimit); return biggestpart; /*biggest partition */ } /********************************************************************** * merge_oldbl_parts * * For any adjacent group of blobs in a different part, put them in the * main part if they fit closely to neighbours in the main part. **********************************************************************/ void merge_oldbl_parts ( //partition blobs TBOX blobcoords[], //bounding boxes int blobcount, /*no of blobs on row */ char partids[], /*partition no of each blob */ int partsizes[], /*no in each partition */ int biggestpart, //major partition float jumplimit /*allowed delta change */ ) { BOOL8 found_one; //found a bestpart blob BOOL8 close_one; //found was close enough int blobindex; /*no along text line */ int prevpart; //previous iteration int runlength; //no in this part float diff; /*difference from line */ int startx; /*index of start blob */ int test_blob; //another index FCOORD coord; //blob coordinate float m, c; //fitted line QLSQ stats; //line stuff prevpart = biggestpart; runlength = 0; startx = 0; for (blobindex = 0; blobindex < blobcount; blobindex++) { if (partids[blobindex] != prevpart) { // tprintf(""Partition change at (%d,%d) from %d to %d after run of %d\\n"", // blobcoords[blobindex].left(),blobcoords[blobindex].bottom(), // prevpart,partids[blobindex],runlength); if (prevpart != biggestpart && runlength > MAXBADRUN) { stats.clear (); for (test_blob = startx; test_blob < blobindex; test_blob++) { coord = FCOORD ((blobcoords[test_blob].left () + blobcoords[test_blob].right ()) / 2.0, blobcoords[test_blob].bottom ()); stats.add (coord.x (), coord.y ()); } stats.fit (1); m = stats.get_b (); c = stats.get_c (); if (textord_oldbl_debug) tprintf (""Fitted line y=%g x + %g\\n"", m, c); found_one = FALSE; close_one = FALSE; for (test_blob = 1; !found_one && (startx - test_blob >= 0 || blobindex + test_blob <= blobcount); test_blob++) { if (startx - test_blob >= 0 && partids[startx - test_blob] == biggestpart) { found_one = TRUE; coord = FCOORD ((blobcoords[startx - test_blob].left () + blobcoords[startx - test_blob].right ()) / 2.0, blobcoords[startx - test_blob].bottom ()); diff = m * coord.x () + c - coord.y (); if (textord_oldbl_debug) tprintf (""Diff of common blob to suspect part=%g at (%g,%g)\\n"", diff, coord.x (), coord.y ()); if (diff < jumplimit && -diff < jumplimit) close_one = TRUE; } if (blobindex + test_blob <= blobcount && partids[blobindex + test_blob - 1] == biggestpart) { found_one = TRUE; coord = FCOORD ((blobcoords[blobindex + test_blob - 1]. left () + blobcoords[blobindex + test_blob - 1].right ()) / 2.0, blobcoords[blobindex + test_blob - 1].bottom ()); diff = m * coord.x () + c - coord.y (); if (textord_oldbl_debug) tprintf (""Diff of common blob to suspect part=%g at (%g,%g)\\n"", diff, coord.x (), coord.y ()); if (diff < jumplimit && -diff < jumplimit) close_one = TRUE; } } if (close_one) { if (textord_oldbl_debug) tprintf (""Merged %d blobs back into part %d from %d starting at (%d,%d)\\n"", runlength, biggestpart, prevpart, blobcoords[startx].left (), blobcoords[startx].bottom ()); //switch sides partsizes[prevpart] -= runlength; for (test_blob = startx; test_blob < blobindex; test_blob++) partids[test_blob] = biggestpart; } } prevpart = partids[blobindex]; runlength = 1; startx = blobindex; } else runlength++; } } /********************************************************************** * get_ydiffs * * Get the differences between the blobs and the spline, * putting them in ydiffs. The return value is the index * of the blob in the middle of the ""best behaved"" region **********************************************************************/ int get_ydiffs ( //evaluate differences TBOX blobcoords[], //bounding boxes int blobcount, /*no of blobs */ QSPLINE * spline, /*approximating spline */ float ydiffs[] /*output */ ) { int blobindex; /*current blob */ int xcentre; /*xcoord */ int lastx; /*last xcentre */ float diffsum; /*sum of diffs */ float diff; /*current difference */ float drift; /*sum of spline steps */ float bestsum; /*smallest diffsum */ int bestindex; /*index of bestsum */ diffsum = 0.0f; bestindex = 0; bestsum = (float) MAX_INT32; drift = 0.0f; lastx = blobcoords[0].left (); /*do each blob in row */ for (blobindex = 0; blobindex < blobcount; blobindex++) { /*centre of blob */ xcentre = (blobcoords[blobindex].left () + blobcoords[blobindex].right ()) >> 1; //step functions in spline drift += spline->step (lastx, xcentre); lastx = xcentre; diff = blobcoords[blobindex].bottom (); diff -= spline->y (xcentre); diff += drift; ydiffs[blobindex] = diff; /*store difference */ if (blobindex > 2) /*remove old one */ diffsum -= ABS (ydiffs[blobindex - 3]); diffsum += ABS (diff); /*add new one */ if (blobindex >= 2 && diffsum < bestsum) { bestsum = diffsum; /*find min sum */ bestindex = blobindex - 1; /*middle of set */ } } return bestindex; } /********************************************************************** * choose_partition * * Choose a partition for the point and return the index. **********************************************************************/ int choose_partition ( //select partition register float diff, /*diff from spline */ float partdiffs[], /*diff on all parts */ int lastpart, /*last assigned partition */ float jumplimit, /*new part threshold */ float* drift, float* lastdelta, int *partcount /*no of partitions */ ) { int partition; /*partition no */ int bestpart; /*best new partition */ float bestdelta; /*best gap from a part */ float delta; /*diff from part */ if (lastpart < 0) { partdiffs[0] = diff; lastpart = 0; /*first point */ *drift = 0.0f; *lastdelta = 0.0f; } /*adjusted diff from part */ delta = diff - partdiffs[lastpart] - *drift; if (textord_oldbl_debug) { tprintf (""Diff=%.2f, Delta=%.3f, Drift=%.3f, "", diff, delta, *drift); } if (ABS (delta) > jumplimit / 2) { /*delta on part 0 */ bestdelta = diff - partdiffs[0] - *drift; bestpart = 0; /*0 best so far */ for (partition = 1; partition < *partcount; partition++) { delta = diff - partdiffs[partition] - *drift; if (ABS (delta) < ABS (bestdelta)) { bestdelta = delta; bestpart = partition; /*part with nearest jump */ } } delta = bestdelta; /*too far away */ if (ABS (bestdelta) > jumplimit && *partcount < MAXPARTS) { /*and spare part left */ bestpart = (*partcount)++; /*best was new one */ /*start new one */ partdiffs[bestpart] = diff - *drift; delta = 0.0f; } } else { bestpart = lastpart; /*best was last one */ } if (bestpart == lastpart && (ABS (delta - *lastdelta) < jumplimit / 2 || ABS (delta) < jumplimit / 2)) /*smooth the drift */ *drift = (3 * *drift + delta) / 3; *lastdelta = delta; if (textord_oldbl_debug) { tprintf (""P=%d\\n"", bestpart); } return bestpart; } /********************************************************************** * partition_coords * * Get the x,y coordinates of all points in the bestpart and put them * in xcoords,ycoords. Return the number of points found. **********************************************************************/ int partition_coords ( //find relevant coords TBOX blobcoords[], //bounding boxes int blobcount, /*no of blobs in row */ char partids[], /*partition no of each blob */ int bestpart, /*best new partition */ int xcoords[], /*points to work on */ int ycoords[] /*points to work on */ ) { int blobindex; /*no along text line */ int pointcount; /*no of points */ pointcount = 0; for (blobindex = 0; blobindex < blobcount; blobindex++) { if (partids[blobindex] == bestpart) { /*centre of blob */ xcoords[pointcount] = (blobcoords[blobindex].left () + blobcoords[blobindex].right ()) >> 1; ycoords[pointcount++] = blobcoords[blobindex].bottom (); } } return pointcount; /*no of points found */ } /********************************************************************** * segment_spline * * Segment the row at midpoints between maxima and minima of the x,y pairs. * The xstarts of the segments are returned and the number found. **********************************************************************/ int segment_spline ( //make xstarts TBOX blobcoords[], //boundign boxes int blobcount, /*no of blobs in row */ int xcoords[], /*points to work on */ int ycoords[], /*points to work on */ int degree, int pointcount, /*no of points */ int xstarts[] //result ) { int ptindex; /*no along text line */ int segment; /*partition no */ int lastmin, lastmax; /*possible turn points */ int turnpoints[SPLINESIZE]; /*good turning points */ int turncount; /*no of turning points */ int max_x; //max specified coord xstarts[0] = xcoords[0] - 1; //leftmost defined pt max_x = xcoords[pointcount - 1] + 1; if (degree < 2) pointcount = 0; turncount = 0; /*no turning points yet */ if (pointcount > 3) { ptindex = 1; lastmax = lastmin = 0; /*start with first one */ while (ptindex < pointcount - 1 && turncount < SPLINESIZE - 1) { /*minimum */ if (ycoords[ptindex - 1] > ycoords[ptindex] && ycoords[ptindex] <= ycoords[ptindex + 1]) { if (ycoords[ptindex] < ycoords[lastmax] - TURNLIMIT) { if (turncount == 0 || turnpoints[turncount - 1] != lastmax) /*new max point */ turnpoints[turncount++] = lastmax; lastmin = ptindex; /*latest minimum */ } else if (ycoords[ptindex] < ycoords[lastmin]) { lastmin = ptindex; /*lower minimum */ } } /*maximum */ if (ycoords[ptindex - 1] < ycoords[ptindex] && ycoords[ptindex] >= ycoords[ptindex + 1]) { if (ycoords[ptindex] > ycoords[lastmin] + TURNLIMIT) { if (turncount == 0 || turnpoints[turncount - 1] != lastmin) /*new min point */ turnpoints[turncount++] = lastmin; lastmax = ptindex; /*latest maximum */ } else if (ycoords[ptindex] > ycoords[lastmax]) { lastmax = ptindex; /*higher maximum */ } } ptindex++; } /*possible global min */ if (ycoords[ptindex] < ycoords[lastmax] - TURNLIMIT && (turncount == 0 || turnpoints[turncount - 1] != lastmax)) { if (turncount < SPLINESIZE - 1) /*2 more turns */ turnpoints[turncount++] = lastmax; if (turncount < SPLINESIZE - 1) turnpoints[turncount++] = ptindex; } else if (ycoords[ptindex] > ycoords[lastmin] + TURNLIMIT /*possible global max */ && (turncount == 0 || turnpoints[turncount - 1] != lastmin)) { if (turncount < SPLINESIZE - 1) /*2 more turns */ turnpoints[turncount++] = lastmin; if (turncount < SPLINESIZE - 1) turnpoints[turncount++] = ptindex; } else if (turncount > 0 && turnpoints[turncount - 1] == lastmin && turncount < SPLINESIZE - 1) { if (ycoords[ptindex] > ycoords[lastmax]) turnpoints[turncount++] = ptindex; else turnpoints[turncount++] = lastmax; } else if (turncount > 0 && turnpoints[turncount - 1] == lastmax && turncount < SPLINESIZE - 1) { if (ycoords[ptindex] < ycoords[lastmin]) turnpoints[turncount++] = ptindex; else turnpoints[turncount++] = lastmin; } } if (textord_oldbl_debug && turncount > 0) tprintf (""First turn is %d at (%d,%d)\\n"", turnpoints[0], xcoords[turnpoints[0]], ycoords[turnpoints[0]]); for (segment = 1; segment < turncount; segment++) { /*centre y coord */ lastmax = (ycoords[turnpoints[segment - 1]] + ycoords[turnpoints[segment]]) / 2; /* fix alg so that it works with both rising and falling sections */ if (ycoords[turnpoints[segment - 1]] < ycoords[turnpoints[segment]]) /*find rising y centre */ for (ptindex = turnpoints[segment - 1] + 1; ptindex < turnpoints[segment] && ycoords[ptindex + 1] <= lastmax; ptindex++); else /*find falling y centre */ for (ptindex = turnpoints[segment - 1] + 1; ptindex < turnpoints[segment] && ycoords[ptindex + 1] >= lastmax; ptindex++); /*centre x */ xstarts[segment] = (xcoords[ptindex - 1] + xcoords[ptindex] + xcoords[turnpoints[segment - 1]] + xcoords[turnpoints[segment]] + 2) / 4; /*halfway between turns */ if (textord_oldbl_debug) tprintf (""Turn %d is %d at (%d,%d), mid pt is %d@%d, final @%d\\n"", segment, turnpoints[segment], xcoords[turnpoints[segment]], ycoords[turnpoints[segment]], ptindex - 1, xcoords[ptindex - 1], xstarts[segment]); } xstarts[segment] = max_x; return segment; /*no of splines */ } /********************************************************************** * split_stepped_spline * * Re-segment the spline in cases where there is a big step function. * Return TRUE if any were done. **********************************************************************/ BOOL8 split_stepped_spline ( //make xstarts QSPLINE * baseline, //current shot float jumplimit, //max step fuction int xcoords[], /*points to work on */ int xstarts[], //result int &segments //no of segments ) { BOOL8 doneany; //return value int segment; /*partition no */ int startindex, centreindex, endindex; float leftcoord, rightcoord; int leftindex, rightindex; float step; //spline step doneany = FALSE; startindex = 0; for (segment = 1; segment < segments - 1; segment++) { step = baseline->step ((xstarts[segment - 1] + xstarts[segment]) / 2.0, (xstarts[segment] + xstarts[segment + 1]) / 2.0); if (step < 0) step = -step; if (step > jumplimit) { while (xcoords[startindex] < xstarts[segment - 1]) startindex++; centreindex = startindex; while (xcoords[centreindex] < xstarts[segment]) centreindex++; endindex = centreindex; while (xcoords[endindex] < xstarts[segment + 1]) endindex++; if (segments >= SPLINESIZE) { if (textord_debug_baselines) tprintf (""Too many segments to resegment spline!!\\n""); } else if (endindex - startindex >= textord_spline_medianwin * 3) { while (centreindex - startindex < textord_spline_medianwin * 3 / 2) centreindex++; while (endindex - centreindex < textord_spline_medianwin * 3 / 2) centreindex--; leftindex = (startindex + startindex + centreindex) / 3; rightindex = (centreindex + endindex + endindex) / 3; leftcoord = (xcoords[startindex] * 2 + xcoords[centreindex]) / 3.0; rightcoord = (xcoords[centreindex] + xcoords[endindex] * 2) / 3.0; while (xcoords[leftindex] > leftcoord && leftindex - startindex > textord_spline_medianwin) leftindex--; while (xcoords[leftindex] < leftcoord && centreindex - leftindex > textord_spline_medianwin / 2) leftindex++; if (xcoords[leftindex] - leftcoord > leftcoord - xcoords[leftindex - 1]) leftindex--; while (xcoords[rightindex] > rightcoord && rightindex - centreindex > textord_spline_medianwin / 2) rightindex--; while (xcoords[rightindex] < rightcoord && endindex - rightindex > textord_spline_medianwin) rightindex++; if (xcoords[rightindex] - rightcoord > rightcoord - xcoords[rightindex - 1]) rightindex--; if (textord_debug_baselines) tprintf (""Splitting spline at %d with step %g at (%d,%d)\\n"", xstarts[segment], baseline-> step ((xstarts[segment - 1] + xstarts[segment]) / 2.0, (xstarts[segment] + xstarts[segment + 1]) / 2.0), (xcoords[leftindex - 1] + xcoords[leftindex]) / 2, (xcoords[rightindex - 1] + xcoords[rightindex]) / 2); insert_spline_point (xstarts, segment, (xcoords[leftindex - 1] + xcoords[leftindex]) / 2, (xcoords[rightindex - 1] + xcoords[rightindex]) / 2, segments); doneany = TRUE; } else if (textord_debug_baselines) { tprintf (""Resegmenting spline failed - insufficient pts (%d,%d,%d,%d)\\n"", startindex, centreindex, endindex, (inT32) textord_spline_medianwin); } } // else tprintf(""Spline step at %d is %g\\n"", // xstarts[segment], // baseline->step((xstarts[segment-1]+xstarts[segment])/2.0, // (xstarts[segment]+xstarts[segment+1])/2.0)); } return doneany; } /********************************************************************** * insert_spline_point * * Insert a new spline point and shuffle up the others. **********************************************************************/ void insert_spline_point ( //get descenders int xstarts[], //starts to shuffle int segment, //insertion pt int coord1, //coords to add int coord2, int &segments //total segments ) { int index; //for shuffling for (index = segments; index > segment; index--) xstarts[index + 1] = xstarts[index]; segments++; xstarts[segment] = coord1; xstarts[segment + 1] = coord2; } /********************************************************************** * find_lesser_parts * * Average the step from the spline for the other partitions * and find the commonest partition which has a descender. **********************************************************************/ void find_lesser_parts ( //get descenders TO_ROW * row, //row to process TBOX blobcoords[], //bounding boxes int blobcount, /*no of blobs */ char partids[], /*partition of each blob */ int partsizes[], /*size of each part */ int partcount, /*no of partitions */ int bestpart /*biggest partition */ ) { int blobindex; /*index of blob */ int partition; /*current partition */ int xcentre; /*centre of blob */ int poscount; /*count of best up step */ int negcount; /*count of best down step */ float partsteps[MAXPARTS]; /*average step to part */ float bestneg; /*best down step */ int runlength; /*length of bad run */ int biggestrun; /*biggest bad run */ biggestrun = 0; for (partition = 0; partition < partcount; partition++) partsteps[partition] = 0.0; /*zero accumulators */ for (runlength = 0, blobindex = 0; blobindex < blobcount; blobindex++) { xcentre = (blobcoords[blobindex].left () + blobcoords[blobindex].right ()) >> 1; /*in other parts */ int part_id = static_cast(static_cast(partids[blobindex])); if (part_id != bestpart) { runlength++; /*run of non bests */ if (runlength > biggestrun) biggestrun = runlength; partsteps[part_id] += blobcoords[blobindex].bottom() - row->baseline.y(xcentre); } else runlength = 0; } if (biggestrun > MAXBADRUN) row->xheight = -1.0f; /*failed */ else row->xheight = 1.0f; /*success */ poscount = negcount = 0; bestneg = 0.0; /*no step yet */ for (partition = 0; partition < partcount; partition++) { if (partition != bestpart) { // by jetsoft divide by zero possible if (partsizes[partition] == 0) partsteps[partition] = 0; else partsteps[partition] /= partsizes[partition]; // if (partsteps[partition] >= MINASCRISE && partsizes[partition] > poscount) { poscount = partsizes[partition]; } if (partsteps[partition] <= -MINASCRISE && partsizes[partition] > negcount) { /*ascender rise */ bestneg = partsteps[partition]; /*2nd most popular */ negcount = partsizes[partition]; } } } /*average x-height */ partsteps[bestpart] /= blobcount; row->descdrop = bestneg; } /********************************************************************** * old_first_xheight * * Makes an x-height spline by copying the baseline and shifting it. * It estimates the x-height across the line to use as the shift. * It also finds the ascender height if it can. **********************************************************************/ void old_first_xheight ( //the wiseowl way TO_ROW * row, /*current row */ TBOX blobcoords[], /*blob bounding boxes */ int initialheight, //initial guess int blobcount, /*blobs in blobcoords */ QSPLINE * baseline, /*established */ float jumplimit /*min ascender height */ ) { int blobindex; /*current blob */ /*height statistics */ STATS heightstat (0, MAXHEIGHT); int height; /*height of blob */ int xcentre; /*centre of blob */ int lineheight; /*approx xheight */ float ascenders; /*ascender sum */ int asccount; /*no of ascenders */ float xsum; /*xheight sum */ int xcount; /*xheight count */ float diff; /*height difference */ if (blobcount > 1) { for (blobindex = 0; blobindex < blobcount; blobindex++) { xcentre = (blobcoords[blobindex].left () + blobcoords[blobindex].right ()) / 2; /*height of blob */ height = (int) (blobcoords[blobindex].top () - baseline->y (xcentre) + 0.5); if (height > initialheight * oldbl_xhfract && height > textord_min_xheight) heightstat.add (height, 1); } if (heightstat.get_total () > 3) { lineheight = (int) heightstat.ile (0.25); if (lineheight <= 0) lineheight = (int) heightstat.ile (0.5); } else lineheight = initialheight; } else { lineheight = (int) (blobcoords[0].top () - baseline->y ((blobcoords[0].left () + blobcoords[0].right ()) / 2) + 0.5); } xsum = 0.0f; xcount = 0; for (ascenders = 0.0f, asccount = 0, blobindex = 0; blobindex < blobcount; blobindex++) { xcentre = (blobcoords[blobindex].left () + blobcoords[blobindex].right ()) / 2; diff = blobcoords[blobindex].top () - baseline->y (xcentre); /*is it ascender */ if (diff > lineheight + jumplimit) { ascenders += diff; asccount++; /*count ascenders */ } else if (diff > lineheight - jumplimit) { xsum += diff; /*mean xheight */ xcount++; } } if (xcount > 0) xsum /= xcount; /*average xheight */ else xsum = (float) lineheight; /*guess it */ row->xheight *= xsum; if (asccount > 0) row->ascrise = ascenders / asccount - xsum; else row->ascrise = 0.0f; /*had none */ if (row->xheight == 0) row->xheight = -1.0f; } /********************************************************************** * make_first_xheight * * Makes an x-height spline by copying the baseline and shifting it. * It estimates the x-height across the line to use as the shift. * It also finds the ascender height if it can. **********************************************************************/ void make_first_xheight ( //find xheight TO_ROW * row, /*current row */ TBOX blobcoords[], /*blob bounding boxes */ int lineheight, //initial guess int init_lineheight, //block level guess int blobcount, /*blobs in blobcoords */ QSPLINE * baseline, /*established */ float jumplimit /*min ascender height */ ) { STATS heightstat (0, HEIGHTBUCKETS); int lefts[HEIGHTBUCKETS]; int rights[HEIGHTBUCKETS]; int modelist[MODENUM]; int blobindex; int mode_count; //blobs to count in thr int sign_bit; int mode_threshold; const int kBaselineTouch = 2; // This really should change with resolution. const int kGoodStrength = 8; // Strength of baseline-touching heights. const float kMinHeight = 0.25; // Min fraction of lineheight to use. sign_bit = row->xheight > 0 ? 1 : -1; memset(lefts, 0, HEIGHTBUCKETS * sizeof(lefts[0])); memset(rights, 0, HEIGHTBUCKETS * sizeof(rights[0])); mode_count = 0; for (blobindex = 0; blobindex < blobcount; blobindex++) { int xcenter = (blobcoords[blobindex].left () + blobcoords[blobindex].right ()) / 2; float base = baseline->y(xcenter); float bottomdiff = fabs(base - blobcoords[blobindex].bottom()); int strength = textord_ocropus_mode && bottomdiff <= kBaselineTouch ? kGoodStrength : 1; int height = static_cast(blobcoords[blobindex].top () - base + 0.5); if (blobcoords[blobindex].height () > init_lineheight * kMinHeight) { if (height > lineheight * oldbl_xhfract && height > textord_min_xheight) { heightstat.add (height, strength); if (height < HEIGHTBUCKETS) { if (xcenter > rights[height]) rights[height] = xcenter; if (xcenter > 0 && (lefts[height] == 0 || xcenter < lefts[height])) lefts[height] = xcenter; } } mode_count += strength; } } mode_threshold = (int) (blobcount * 0.1); if (oldbl_dot_error_size > 1 || oldbl_xhfix) mode_threshold = (int) (mode_count * 0.1); if (textord_oldbl_debug) { tprintf (""blobcount=%d, mode_count=%d, mode_t=%d\\n"", blobcount, mode_count, mode_threshold); } find_top_modes(&heightstat, HEIGHTBUCKETS, modelist, MODENUM); if (textord_oldbl_debug) { for (blobindex = 0; blobindex < MODENUM; blobindex++) tprintf (""mode[%d]=%d "", blobindex, modelist[blobindex]); tprintf (""\\n""); } pick_x_height(row, modelist, lefts, rights, &heightstat, mode_threshold); if (textord_oldbl_debug) tprintf (""Output xheight=%g\\n"", row->xheight); if (row->xheight < 0 && textord_oldbl_debug) tprintf (""warning: Row Line height < 0; %4.2f\\n"", row->xheight); if (sign_bit < 0) row->xheight = -row->xheight; } /********************************************************************** * find_top_modes * * Fill the input array with the indices of the top ten modes of the * input distribution. **********************************************************************/ const int kMinModeFactorOcropus = 32; const int kMinModeFactor = 12; void find_top_modes ( //get modes STATS * stats, //stats to hack int statnum, //no of piles int modelist[], int modenum //no of modes to get ) { int mode_count; int last_i = 0; int last_max = MAX_INT32; int i; int mode; int total_max = 0; int mode_factor = textord_ocropus_mode ? kMinModeFactorOcropus : kMinModeFactor; for (mode_count = 0; mode_count < modenum; mode_count++) { mode = 0; for (i = 0; i < statnum; i++) { if (stats->pile_count (i) > stats->pile_count (mode)) { if ((stats->pile_count (i) < last_max) || ((stats->pile_count (i) == last_max) && (i > last_i))) { mode = i; } } } last_i = mode; last_max = stats->pile_count (last_i); total_max += last_max; if (last_max <= total_max / mode_factor) mode = 0; modelist[mode_count] = mode; } } /********************************************************************** * pick_x_height * * Choose based on the height modes the best x height value. **********************************************************************/ void pick_x_height(TO_ROW * row, //row to do int modelist[], int lefts[], int rights[], STATS * heightstat, int mode_threshold) { int x; int y; int z; float ratio; int found_one_bigger = FALSE; int best_x_height = 0; int best_asc = 0; int num_in_best; for (x = 0; x < MODENUM; x++) { for (y = 0; y < MODENUM; y++) { /* Check for two modes */ if (modelist[x] && modelist[y] && heightstat->pile_count (modelist[x]) > mode_threshold && (!textord_ocropus_mode || MIN(rights[modelist[x]], rights[modelist[y]]) > MAX(lefts[modelist[x]], lefts[modelist[y]]))) { ratio = (float) modelist[y] / (float) modelist[x]; if (1.2 < ratio && ratio < 1.8) { /* Two modes found */ best_x_height = modelist[x]; num_in_best = heightstat->pile_count (modelist[x]); /* Try to get one higher */ do { found_one_bigger = FALSE; for (z = 0; z < MODENUM; z++) { if (modelist[z] == best_x_height + 1 && (!textord_ocropus_mode || MIN(rights[modelist[x]], rights[modelist[y]]) > MAX(lefts[modelist[x]], lefts[modelist[y]]))) { ratio = (float) modelist[y] / (float) modelist[z]; if ((1.2 < ratio && ratio < 1.8) && /* Should be half of best */ heightstat->pile_count (modelist[z]) > num_in_best * 0.5) { best_x_height++; found_one_bigger = TRUE; break; } } } } while (found_one_bigger); /* try to get a higher ascender */ best_asc = modelist[y]; num_in_best = heightstat->pile_count (modelist[y]); /* Try to get one higher */ do { found_one_bigger = FALSE; for (z = 0; z < MODENUM; z++) { if (modelist[z] > best_asc && (!textord_ocropus_mode || MIN(rights[modelist[x]], rights[modelist[y]]) > MAX(lefts[modelist[x]], lefts[modelist[y]]))) { ratio = (float) modelist[z] / (float) best_x_height; if ((1.2 < ratio && ratio < 1.8) && /* Should be half of best */ heightstat->pile_count (modelist[z]) > num_in_best * 0.5) { best_asc = modelist[z]; found_one_bigger = TRUE; break; } } } } while (found_one_bigger); row->xheight = (float) best_x_height; row->ascrise = (float) best_asc - best_x_height; return; } } } } best_x_height = modelist[0]; /* Single Mode found */ num_in_best = heightstat->pile_count (best_x_height); do { /* Try to get one higher */ found_one_bigger = FALSE; for (z = 1; z < MODENUM; z++) { /* Should be half of best */ if ((modelist[z] == best_x_height + 1) && (heightstat->pile_count (modelist[z]) > num_in_best * 0.5)) { best_x_height++; found_one_bigger = TRUE; break; } } } while (found_one_bigger); row->ascrise = 0.0f; row->xheight = (float) best_x_height; if (row->xheight == 0) row->xheight = -1.0f; } ",16287,True,2952.7087977900987,median "// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include ""lib/mirrors.h"" #include ""lib/invocation_mirror.h"" #include ""vm/bootstrap_natives.h"" #include ""vm/class_finalizer.h"" #include ""vm/dart_api_impl.h"" #include ""vm/dart_entry.h"" #include ""vm/exceptions.h"" #include ""vm/kernel.h"" #include ""vm/object_store.h"" #include ""vm/parser.h"" #include ""vm/port.h"" #include ""vm/symbols.h"" namespace dart { #if !defined(DART_PRECOMPILED_RUNTIME) #define RETURN_OR_PROPAGATE(expr) \\ RawObject* result = expr; \\ if (RawObject::IsErrorClassId(result->GetClassIdMayBeSmi())) { \\ Exceptions::PropagateError(Error::Handle(Error::RawCast(result))); \\ } \\ return result; static RawInstance* CreateMirror(const String& mirror_class_name, const Array& constructor_arguments) { const Library& mirrors_lib = Library::Handle(Library::MirrorsLibrary()); const String& constructor_name = Symbols::DotUnder(); const Object& result = Object::Handle(DartLibraryCalls::InstanceCreate( mirrors_lib, mirror_class_name, constructor_name, constructor_arguments)); if (result.IsError()) { Exceptions::PropagateError(Error::Cast(result)); } return Instance::Cast(result).raw(); } // Conventions: // * For throwing a NSM in a class klass we use its runtime type as receiver, // i.e., klass.RareType(). // * For throwing a NSM in a library, we just pass the null instance as // receiver. static void ThrowNoSuchMethod(const Instance& receiver, const String& function_name, const Array& arguments, const Array& argument_names, const InvocationMirror::Level level, const InvocationMirror::Kind kind) { const Smi& invocation_type = Smi::Handle(Smi::New(InvocationMirror::EncodeType(level, kind))); const Array& args = Array::Handle(Array::New(6)); args.SetAt(0, receiver); args.SetAt(1, function_name); args.SetAt(2, invocation_type); // TODO(regis): Support invocation of generic functions with type arguments. args.SetAt(3, Object::null_type_arguments()); args.SetAt(4, arguments); args.SetAt(5, argument_names); const Library& libcore = Library::Handle(Library::CoreLibrary()); const Class& NoSuchMethodError = Class::Handle(libcore.LookupClass(Symbols::NoSuchMethodError())); const Function& throwNew = Function::Handle( NoSuchMethodError.LookupFunctionAllowPrivate(Symbols::ThrowNew())); const Object& result = Object::Handle(DartEntry::InvokeFunction(throwNew, args)); ASSERT(result.IsError()); Exceptions::PropagateError(Error::Cast(result)); UNREACHABLE(); } static void EnsureConstructorsAreCompiled(const Function& func) { // Only generative constructors can have initializing formals. if (!func.IsGenerativeConstructor()) return; Thread* thread = Thread::Current(); Zone* zone = thread->zone(); const Class& cls = Class::Handle(zone, func.Owner()); const Error& error = Error::Handle(zone, cls.EnsureIsFinalized(thread)); if (!error.IsNull()) { Exceptions::PropagateError(error); UNREACHABLE(); } func.EnsureHasCode(); } static RawInstance* CreateParameterMirrorList(const Function& func, const Instance& owner_mirror) { HANDLESCOPE(Thread::Current()); const intptr_t implicit_param_count = func.NumImplicitParameters(); const intptr_t non_implicit_param_count = func.NumParameters() - implicit_param_count; const intptr_t index_of_first_optional_param = non_implicit_param_count - func.NumOptionalParameters(); const intptr_t index_of_first_named_param = non_implicit_param_count - func.NumOptionalNamedParameters(); const Array& results = Array::Handle(Array::New(non_implicit_param_count)); const Array& args = Array::Handle(Array::New(9)); Smi& pos = Smi::Handle(); String& name = String::Handle(); Instance& param = Instance::Handle(); Bool& is_final = Bool::Handle(); Object& default_value = Object::Handle(); Object& metadata = Object::Handle(); // We force compilation of constructors to ensure the types of initializing // formals have been corrected. We do not force the compilation of all types // of functions because some have no body, e.g. signature functions. EnsureConstructorsAreCompiled(func); bool has_extra_parameter_info = true; if (non_implicit_param_count == 0) { has_extra_parameter_info = false; } if (func.IsImplicitConstructor()) { // This covers the default constructor and forwarding constructors. has_extra_parameter_info = false; } if (func.IsSignatureFunction() && (func.token_pos() == TokenPosition::kNoSource)) { // Signature functions (except those describing typedefs) get canonicalized, // hence do not have a token position, and therefore cannot be reparsed. has_extra_parameter_info = false; } Array& param_descriptor = Array::Handle(); if (has_extra_parameter_info) { // Reparse the function for the following information: // * The default value of a parameter. // * Whether a parameters has been declared as final. // * Any metadata associated with the parameter. Object& result = Object::Handle(kernel::BuildParameterDescriptor(func)); if (result.IsError()) { Exceptions::PropagateError(Error::Cast(result)); UNREACHABLE(); } param_descriptor ^= result.raw(); ASSERT(param_descriptor.Length() == (Parser::kParameterEntrySize * non_implicit_param_count)); } args.SetAt(0, MirrorReference::Handle(MirrorReference::New(func))); args.SetAt(2, owner_mirror); if (!has_extra_parameter_info) { is_final = Bool::True().raw(); default_value = Object::null(); metadata = Object::null(); } for (intptr_t i = 0; i < non_implicit_param_count; i++) { pos = Smi::New(i); name = func.ParameterNameAt(implicit_param_count + i); if (has_extra_parameter_info) { is_final ^= param_descriptor.At(i * Parser::kParameterEntrySize + Parser::kParameterIsFinalOffset); default_value = param_descriptor.At(i * Parser::kParameterEntrySize + Parser::kParameterDefaultValueOffset); metadata = param_descriptor.At(i * Parser::kParameterEntrySize + Parser::kParameterMetadataOffset); } ASSERT(default_value.IsNull() || default_value.IsInstance()); // Arguments 0 (referent) and 2 (owner) are the same for all parameters. See // above. args.SetAt(1, name); args.SetAt(3, pos); args.SetAt(4, Bool::Get(i >= index_of_first_optional_param)); args.SetAt(5, Bool::Get(i >= index_of_first_named_param)); args.SetAt(6, is_final); args.SetAt(7, default_value); args.SetAt(8, metadata); param = CreateMirror(Symbols::_ParameterMirror(), args); results.SetAt(i, param); } results.MakeImmutable(); return results.raw(); } static RawInstance* CreateTypeVariableMirror(const TypeParameter& param, const Instance& owner_mirror) { const Array& args = Array::Handle(Array::New(3)); args.SetAt(0, param); args.SetAt(1, String::Handle(param.name())); args.SetAt(2, owner_mirror); return CreateMirror(Symbols::_TypeVariableMirror(), args); } // We create a list in native code and let Dart code create the type mirror // object and the ordered map. static RawInstance* CreateTypeVariableList(const Class& cls) { const TypeArguments& args = TypeArguments::Handle(cls.type_parameters()); if (args.IsNull()) { return Object::empty_array().raw(); } const Array& result = Array::Handle(Array::New(args.Length() * 2)); TypeParameter& type = TypeParameter::Handle(); String& name = String::Handle(); for (intptr_t i = 0; i < args.Length(); i++) { type ^= args.TypeAt(i); ASSERT(type.IsTypeParameter()); ASSERT(type.IsFinalized()); name = type.name(); result.SetAt(2 * i, name); result.SetAt(2 * i + 1, type); } return result.raw(); } static RawInstance* CreateTypedefMirror(const Class& cls, const AbstractType& type, const Bool& is_declaration, const Instance& owner_mirror) { const Array& args = Array::Handle(Array::New(6)); args.SetAt(0, MirrorReference::Handle(MirrorReference::New(cls))); args.SetAt(1, type); args.SetAt(2, String::Handle(cls.Name())); args.SetAt(3, Bool::Get(cls.IsGeneric())); args.SetAt(4, cls.IsGeneric() ? is_declaration : Bool::False()); args.SetAt(5, owner_mirror); return CreateMirror(Symbols::_TypedefMirror(), args); } static RawInstance* CreateFunctionTypeMirror(const AbstractType& type) { ASSERT(type.IsFunctionType()); const Class& cls = Class::Handle(Type::Cast(type).type_class()); const Function& func = Function::Handle(Type::Cast(type).signature()); const Array& args = Array::Handle(Array::New(3)); args.SetAt(0, MirrorReference::Handle(MirrorReference::New(cls))); args.SetAt(1, MirrorReference::Handle(MirrorReference::New(func))); args.SetAt(2, type); return CreateMirror(Symbols::_FunctionTypeMirror(), args); } static RawInstance* CreateMethodMirror(const Function& func, const Instance& owner_mirror, const AbstractType& instantiator) { const Array& args = Array::Handle(Array::New(6)); args.SetAt(0, MirrorReference::Handle(MirrorReference::New(func))); String& name = String::Handle(func.name()); name = String::ScrubNameRetainPrivate(name, func.is_extension_member()); args.SetAt(1, name); args.SetAt(2, owner_mirror); args.SetAt(3, instantiator); args.SetAt(4, Bool::Get(func.is_static())); intptr_t kind_flags = 0; kind_flags |= (static_cast(func.is_abstract()) << Mirrors::kAbstract); kind_flags |= (static_cast(func.IsGetterFunction()) << Mirrors::kGetter); kind_flags |= (static_cast(func.IsSetterFunction()) << Mirrors::kSetter); bool is_ctor = (func.kind() == RawFunction::kConstructor); kind_flags |= (static_cast(is_ctor) << Mirrors::kConstructor); kind_flags |= (static_cast(is_ctor && func.is_const()) << Mirrors::kConstCtor); kind_flags |= (static_cast(is_ctor && func.IsGenerativeConstructor()) << Mirrors::kGenerativeCtor); kind_flags |= (static_cast(is_ctor && func.is_redirecting()) << Mirrors::kRedirectingCtor); kind_flags |= (static_cast(is_ctor && func.IsFactory()) << Mirrors::kFactoryCtor); kind_flags |= (static_cast(func.is_external()) << Mirrors::kExternal); bool is_synthetic = func.is_no_such_method_forwarder(); kind_flags |= (static_cast(is_synthetic) << Mirrors::kSynthetic); kind_flags |= (static_cast(func.is_extension_member()) << Mirrors::kExtensionMember); args.SetAt(5, Smi::Handle(Smi::New(kind_flags))); return CreateMirror(Symbols::_MethodMirror(), args); } static RawInstance* CreateVariableMirror(const Field& field, const Instance& owner_mirror) { const MirrorReference& field_ref = MirrorReference::Handle(MirrorReference::New(field)); const String& name = String::Handle(field.name()); const Array& args = Array::Handle(Array::New(8)); args.SetAt(0, field_ref); args.SetAt(1, name); args.SetAt(2, owner_mirror); args.SetAt(3, Object::null_instance()); // Null for type. args.SetAt(4, Bool::Get(field.is_static())); args.SetAt(5, Bool::Get(field.is_final())); args.SetAt(6, Bool::Get(field.is_const())); args.SetAt(7, Bool::Get(field.is_extension_member())); return CreateMirror(Symbols::_VariableMirror(), args); } static RawInstance* CreateClassMirror(const Class& cls, const AbstractType& type, const Bool& is_declaration, const Instance& owner_mirror) { if (type.IsTypeRef()) { AbstractType& ref_type = AbstractType::Handle(TypeRef::Cast(type).type()); ASSERT(!ref_type.IsTypeRef()); ASSERT(ref_type.IsCanonical()); return CreateClassMirror(cls, ref_type, is_declaration, owner_mirror); } ASSERT(!cls.IsDynamicClass() && !cls.IsVoidClass()); ASSERT(!type.IsNull()); ASSERT(type.IsFinalized()); if (cls.IsTypedefClass()) { return CreateTypedefMirror(cls, type, is_declaration, owner_mirror); } const Array& args = Array::Handle(Array::New(9)); args.SetAt(0, MirrorReference::Handle(MirrorReference::New(cls))); args.SetAt(1, type); args.SetAt(2, String::Handle(cls.Name())); args.SetAt(3, owner_mirror); args.SetAt(4, Bool::Get(cls.is_abstract())); args.SetAt(5, Bool::Get(cls.IsGeneric())); args.SetAt(6, Bool::Get(cls.is_transformed_mixin_application())); args.SetAt(7, cls.NumTypeParameters() == 0 ? Bool::False() : is_declaration); args.SetAt(8, Bool::Get(cls.is_enum_class())); return CreateMirror(Symbols::_ClassMirror(), args); } static bool IsCensoredLibrary(const String& url) { static const char* const censored_libraries[] = { ""dart:_builtin"", ""dart:_vmservice"", ""dart:vmservice_io"", }; for (const char* censored_library : censored_libraries) { if (url.Equals(censored_library)) { return true; } } if (!Api::IsFfiEnabled() && url.Equals(Symbols::DartFfi())) { return true; } return false; } static RawInstance* CreateLibraryMirror(Thread* thread, const Library& lib) { Zone* zone = thread->zone(); ASSERT(!lib.IsNull()); const Array& args = Array::Handle(zone, Array::New(3)); args.SetAt(0, MirrorReference::Handle(zone, MirrorReference::New(lib))); String& str = String::Handle(zone); str = lib.name(); args.SetAt(1, str); str = lib.url(); if (IsCensoredLibrary(str)) { // Censored library (grumble). return Instance::null(); } args.SetAt(2, str); return CreateMirror(Symbols::_LibraryMirror(), args); } static RawInstance* CreateCombinatorMirror(const Object& identifiers, bool is_show) { const Array& args = Array::Handle(Array::New(2)); args.SetAt(0, identifiers); args.SetAt(1, Bool::Get(is_show)); return CreateMirror(Symbols::_CombinatorMirror(), args); } static RawInstance* CreateLibraryDependencyMirror(Thread* thread, const Instance& importer, const Library& importee, const Array& show_names, const Array& hide_names, const Object& metadata, const LibraryPrefix& prefix, const String& prefix_name, const bool is_import, const bool is_deferred) { const Instance& importee_mirror = Instance::Handle(CreateLibraryMirror(thread, importee)); if (importee_mirror.IsNull()) { // Imported library is censored: censor the import. return Instance::null(); } intptr_t n = show_names.IsNull() ? 0 : show_names.Length(); intptr_t m = hide_names.IsNull() ? 0 : hide_names.Length(); const Array& combinators = Array::Handle(Array::New(n + m)); Object& t = Object::Handle(); intptr_t i = 0; for (intptr_t j = 0; j < n; j++) { t = show_names.At(j); t = CreateCombinatorMirror(t, true); combinators.SetAt(i++, t); } for (intptr_t j = 0; j < m; j++) { t = hide_names.At(j); t = CreateCombinatorMirror(t, false); combinators.SetAt(i++, t); } const Array& args = Array::Handle(Array::New(7)); args.SetAt(0, importer); if (importee.Loaded() || prefix.IsNull()) { // A native extension is never ""loaded"" by the embedder. Use the fact that // it doesn't have an prefix where asa deferred import does to distinguish // it from a deferred import. It will appear like an empty library. args.SetAt(1, importee_mirror); } else { args.SetAt(1, prefix); } args.SetAt(2, combinators); args.SetAt(3, prefix_name); args.SetAt(4, Bool::Get(is_import)); args.SetAt(5, Bool::Get(is_deferred)); args.SetAt(6, metadata); return CreateMirror(Symbols::_LibraryDependencyMirror(), args); } static RawInstance* CreateLibraryDependencyMirror(Thread* thread, const Instance& importer, const Namespace& ns, const LibraryPrefix& prefix, const bool is_import, const bool is_deferred) { const Library& importee = Library::Handle(ns.library()); const Array& show_names = Array::Handle(ns.show_names()); const Array& hide_names = Array::Handle(ns.hide_names()); Object& metadata = Object::Handle(ns.GetMetadata()); if (metadata.IsError()) { Exceptions::PropagateError(Error::Cast(metadata)); UNREACHABLE(); } auto& prefix_name = String::Handle(); if (!prefix.IsNull()) { prefix_name = prefix.name(); } return CreateLibraryDependencyMirror(thread, importer, importee, show_names, hide_names, metadata, prefix, prefix_name, is_import, is_deferred); } static RawGrowableObjectArray* CreateBytecodeLibraryDependencies( Thread* thread, const Library& lib, const Instance& lib_mirror) { ASSERT(lib.is_declared_in_bytecode()); // Make sure top level class (containing annotations) is fully loaded. lib.EnsureTopLevelClassIsFinalized(); const auto& deps = GrowableObjectArray::Handle(GrowableObjectArray::New()); Array& metadata = Array::Handle(lib.GetExtendedMetadata(lib, 1)); if (metadata.Length() == 0) { return deps.raw(); } // Library has the only element in the extended metadata. metadata ^= metadata.At(0); if (metadata.IsNull()) { return deps.raw(); } auto& desc = Array::Handle(); auto& target_uri = String::Handle(); auto& importee = Library::Handle(); auto& is_export = Bool::Handle(); auto& is_deferred = Bool::Handle(); auto& prefix_name = String::Handle(); auto& show_names = Array::Handle(); auto& hide_names = Array::Handle(); auto& dep_metadata = Instance::Handle(); auto& dep = Instance::Handle(); const auto& no_prefix = LibraryPrefix::Handle(); for (intptr_t i = 0, n = metadata.Length(); i < n; ++i) { desc ^= metadata.At(i); // Each dependency is represented as an array with the following layout: // [0] = target library URI (String) // [1] = is_export (bool) // [2] = is_deferred (bool) // [3] = prefix (String or null) // [4] = list of show names (List) // [5] = list of hide names (List) // [6] = annotations // The library dependencies are encoded by getLibraryAnnotations(), // pkg/vm/lib/bytecode/gen_bytecode.dart. target_uri ^= desc.At(0); is_export ^= desc.At(1); is_deferred ^= desc.At(2); prefix_name ^= desc.At(3); show_names ^= desc.At(4); hide_names ^= desc.At(5); dep_metadata ^= desc.At(6); importee = Library::LookupLibrary(thread, target_uri); if (importee.IsNull()) { continue; } ASSERT(importee.Loaded()); dep = CreateLibraryDependencyMirror( thread, lib_mirror, importee, show_names, hide_names, dep_metadata, no_prefix, prefix_name, !is_export.value(), is_deferred.value()); if (!dep.IsNull()) { deps.Add(dep); } } return deps.raw(); } DEFINE_NATIVE_ENTRY(LibraryMirror_fromPrefix, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(LibraryPrefix, prefix, arguments->NativeArgAt(0)); const Library& deferred_lib = Library::Handle(prefix.GetLibrary(0)); if (!deferred_lib.Loaded()) { return Instance::null(); } return CreateLibraryMirror(thread, deferred_lib); } DEFINE_NATIVE_ENTRY(LibraryMirror_libraryDependencies, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, lib_mirror, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Library& lib = Library::Handle(ref.GetLibraryReferent()); if (lib.is_declared_in_bytecode()) { return CreateBytecodeLibraryDependencies(thread, lib, lib_mirror); } Array& ports = Array::Handle(); Namespace& ns = Namespace::Handle(); Instance& dep = Instance::Handle(); LibraryPrefix& prefix = LibraryPrefix::Handle(); GrowableObjectArray& deps = GrowableObjectArray::Handle(GrowableObjectArray::New()); // Unprefixed imports. ports = lib.imports(); for (intptr_t i = 0; i < ports.Length(); i++) { ns ^= ports.At(i); if (!ns.IsNull()) { dep = CreateLibraryDependencyMirror(thread, lib_mirror, ns, prefix, true, false); if (!dep.IsNull()) { deps.Add(dep); } } } // Exports. ports = lib.exports(); for (intptr_t i = 0; i < ports.Length(); i++) { ns ^= ports.At(i); dep = CreateLibraryDependencyMirror(thread, lib_mirror, ns, prefix, false, false); if (!dep.IsNull()) { deps.Add(dep); } } // Prefixed imports. DictionaryIterator entries(lib); Object& entry = Object::Handle(); while (entries.HasNext()) { entry = entries.GetNext(); if (entry.IsLibraryPrefix()) { prefix ^= entry.raw(); ports = prefix.imports(); for (intptr_t i = 0; i < ports.Length(); i++) { ns ^= ports.At(i); if (!ns.IsNull()) { dep = CreateLibraryDependencyMirror(thread, lib_mirror, ns, prefix, true, prefix.is_deferred_load()); if (!dep.IsNull()) { deps.Add(dep); } } } } } return deps.raw(); } static RawInstance* CreateTypeMirror(const AbstractType& type) { if (type.IsTypeRef()) { AbstractType& ref_type = AbstractType::Handle(TypeRef::Cast(type).type()); ASSERT(!ref_type.IsTypeRef()); ASSERT(ref_type.IsCanonical()); return CreateTypeMirror(ref_type); } ASSERT(type.IsFinalized()); ASSERT(type.IsCanonical() || type.IsTypeParameter()); if (type.IsFunctionType()) { const Class& scope_class = Class::Handle(Type::Cast(type).type_class()); if (scope_class.IsTypedefClass()) { return CreateTypedefMirror(scope_class, type, Bool::False(), Object::null_instance()); } else { return CreateFunctionTypeMirror(type); } } if (type.HasTypeClass()) { const Class& cls = Class::Handle(type.type_class()); // Handle void and dynamic types. if (cls.IsVoidClass()) { Array& args = Array::Handle(Array::New(1)); args.SetAt(0, Symbols::Void()); return CreateMirror(Symbols::_SpecialTypeMirror(), args); } else if (cls.IsDynamicClass()) { Array& args = Array::Handle(Array::New(1)); args.SetAt(0, Symbols::Dynamic()); return CreateMirror(Symbols::_SpecialTypeMirror(), args); } // TODO(regis): Until mirrors reflect nullability, force kLegacy, except for // Null type, which should remain nullable. if (!type.IsNullType()) { const Type& legacy_type = Type::Handle( Type::Cast(type).ToNullability(Nullability::kLegacy, Heap::kOld)); return CreateClassMirror(cls, legacy_type, Bool::False(), Object::null_instance()); } return CreateClassMirror(cls, type, Bool::False(), Object::null_instance()); } else if (type.IsTypeParameter()) { // TODO(regis): Until mirrors reflect nullability, force kLegacy. const TypeParameter& legacy_type = TypeParameter::Handle(TypeParameter::Cast(type).ToNullability( Nullability::kLegacy, Heap::kOld)); return CreateTypeVariableMirror(legacy_type, Object::null_instance()); } UNREACHABLE(); return Instance::null(); } static RawInstance* CreateIsolateMirror() { Thread* thread = Thread::Current(); Isolate* isolate = thread->isolate(); const String& debug_name = String::Handle(String::New(isolate->name())); const Library& root_library = Library::Handle(thread->zone(), isolate->object_store()->root_library()); const Instance& root_library_mirror = Instance::Handle(CreateLibraryMirror(thread, root_library)); const Array& args = Array::Handle(Array::New(2)); args.SetAt(0, debug_name); args.SetAt(1, root_library_mirror); return CreateMirror(Symbols::_IsolateMirror(), args); } static void VerifyMethodKindShifts() { #ifdef DEBUG Thread* thread = Thread::Current(); Zone* zone = thread->zone(); const Library& lib = Library::Handle(zone, Library::MirrorsLibrary()); const Class& cls = Class::Handle( zone, lib.LookupClassAllowPrivate(Symbols::_MethodMirror())); Error& error = Error::Handle(zone); error ^= cls.EnsureIsFinalized(thread); ASSERT(error.IsNull()); Field& field = Field::Handle(zone); Smi& value = Smi::Handle(zone); String& fname = String::Handle(zone); #define CHECK_KIND_SHIFT(name) \\ fname ^= String::New(#name); \\ field = cls.LookupField(fname); \\ ASSERT(!field.IsNull()); \\ if (field.IsUninitialized()) { \\ error ^= field.InitializeStatic(); \\ ASSERT(error.IsNull()); \\ } \\ value ^= field.StaticValue(); \\ ASSERT(value.Value() == Mirrors::name); MIRRORS_KIND_SHIFT_LIST(CHECK_KIND_SHIFT) #undef CHECK_KIND_SHIFT #endif } static RawAbstractType* InstantiateType(const AbstractType& type, const AbstractType& instantiator) { // Generic function type parameters are not reified, but mapped to dynamic, // i.e. all function type parameters are free with a null vector. ASSERT(type.IsFinalized()); ASSERT(type.IsCanonical() || type.IsTypeParameter()); if (type.IsInstantiated()) { return type.Canonicalize(); } TypeArguments& instantiator_type_args = TypeArguments::Handle(); if (!instantiator.IsNull()) { ASSERT(instantiator.IsFinalized()); instantiator_type_args = instantiator.arguments(); } AbstractType& result = AbstractType::Handle(type.InstantiateFrom( NNBDMode::kLegacyLib_LegacyTest, instantiator_type_args, Object::null_type_arguments(), kAllFree, NULL, Heap::kOld)); ASSERT(result.IsFinalized()); return result.Canonicalize(); } DEFINE_NATIVE_ENTRY(MirrorSystem_libraries, 0, 0) { const GrowableObjectArray& libraries = GrowableObjectArray::Handle(zone, isolate->object_store()->libraries()); const intptr_t num_libraries = libraries.Length(); const GrowableObjectArray& library_mirrors = GrowableObjectArray::Handle( zone, GrowableObjectArray::New(num_libraries)); Library& library = Library::Handle(zone); Instance& library_mirror = Instance::Handle(zone); for (int i = 0; i < num_libraries; i++) { library ^= libraries.At(i); library_mirror = CreateLibraryMirror(thread, library); if (!library_mirror.IsNull() && library.Loaded()) { library_mirrors.Add(library_mirror); } } return library_mirrors.raw(); } DEFINE_NATIVE_ENTRY(MirrorSystem_isolate, 0, 0) { VerifyMethodKindShifts(); return CreateIsolateMirror(); } static void ThrowLanguageError(const char* message) { const Error& error = Error::Handle(LanguageError::New(String::Handle(String::New(message)))); Exceptions::PropagateError(error); } DEFINE_NATIVE_ENTRY(IsolateMirror_loadUri, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(String, uri, arguments->NativeArgAt(0)); if (!isolate->HasTagHandler()) { ThrowLanguageError(""no library handler registered""); } NoReloadScope no_reload(isolate, thread); // Canonicalize library URI. String& canonical_uri = String::Handle(zone); if (uri.StartsWith(Symbols::DartScheme())) { canonical_uri = uri.raw(); } else { isolate->BlockClassFinalization(); const Object& result = Object::Handle( zone, isolate->CallTagHandler( Dart_kCanonicalizeUrl, Library::Handle(zone, isolate->object_store()->root_library()), uri)); isolate->UnblockClassFinalization(); if (result.IsError()) { if (result.IsLanguageError()) { Exceptions::ThrowCompileTimeError(LanguageError::Cast(result)); } Exceptions::PropagateError(Error::Cast(result)); } else if (!result.IsString()) { ThrowLanguageError(""library handler failed URI canonicalization""); } canonical_uri ^= result.raw(); } // Return the existing library if it has already been loaded. Library& library = Library::Handle(zone, Library::LookupLibrary(thread, canonical_uri)); if (!library.IsNull()) { return CreateLibraryMirror(thread, library); } // Request the embedder to load the library. isolate->BlockClassFinalization(); Object& result = Object::Handle( zone, isolate->CallTagHandler( Dart_kImportTag, Library::Handle(zone, isolate->object_store()->root_library()), canonical_uri)); isolate->UnblockClassFinalization(); if (result.IsError()) { if (result.IsLanguageError()) { Exceptions::ThrowCompileTimeError(LanguageError::Cast(result)); } Exceptions::PropagateError(Error::Cast(result)); } // This code assumes a synchronous tag handler (which dart::bin and tonic // provide). Strictly though we should complete a future in response to // Dart_FinalizeLoading. if (!ClassFinalizer::ProcessPendingClasses()) { Exceptions::PropagateError(Error::Handle(thread->sticky_error())); } // Prefer the tag handler's idea of which library is represented by the URI. if (result.IsLibrary()) { return CreateLibraryMirror(thread, Library::Cast(result)); } if (result.IsNull()) { library = Library::LookupLibrary(thread, canonical_uri); if (!library.IsNull()) { return CreateLibraryMirror(thread, library); } } FATAL(""Non-library from tag handler""); } DEFINE_NATIVE_ENTRY(Mirrors_makeLocalClassMirror, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0)); ASSERT(type.IsFinalized()); ASSERT(type.HasTypeClass()); const Class& cls = Class::Handle(type.type_class()); ASSERT(!cls.IsNull()); if (cls.IsDynamicClass() || cls.IsVoidClass() || cls.IsTypedefClass()) { Exceptions::ThrowArgumentError(type); UNREACHABLE(); } return CreateClassMirror(cls, AbstractType::Handle(cls.DeclarationType()), Bool::True(), // is_declaration Object::null_instance()); } DEFINE_NATIVE_ENTRY(Mirrors_makeLocalTypeMirror, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0)); return CreateTypeMirror(type); } DEFINE_NATIVE_ENTRY(Mirrors_instantiateGenericType, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(Array, args, arguments->NativeArgAt(1)); ASSERT(type.HasTypeClass()); const Class& clz = Class::Handle(type.type_class()); if (!clz.IsGeneric()) { const Array& error_args = Array::Handle(Array::New(3)); error_args.SetAt(0, type); error_args.SetAt(1, String::Handle(String::New(""key""))); error_args.SetAt(2, String::Handle(String::New( ""Type must be a generic class or function.""))); Exceptions::ThrowByType(Exceptions::kArgumentValue, error_args); UNREACHABLE(); } if (clz.NumTypeParameters() != args.Length()) { const Array& error_args = Array::Handle(Array::New(3)); error_args.SetAt(0, args); error_args.SetAt(1, String::Handle(String::New(""typeArguments""))); error_args.SetAt(2, String::Handle(String::New( ""Number of type arguments does not match.""))); Exceptions::ThrowByType(Exceptions::kArgumentValue, error_args); UNREACHABLE(); } intptr_t num_expected_type_arguments = args.Length(); TypeArguments& type_args_obj = TypeArguments::Handle(); type_args_obj = TypeArguments::New(num_expected_type_arguments); AbstractType& type_arg = AbstractType::Handle(); Instance& instance = Instance::Handle(); for (intptr_t i = 0; i < args.Length(); i++) { instance ^= args.At(i); if (!instance.IsType()) { const Array& error_args = Array::Handle(Array::New(3)); error_args.SetAt(0, args); error_args.SetAt(1, String::Handle(String::New(""typeArguments""))); error_args.SetAt(2, String::Handle(String::New( ""Type arguments must be instances of Type.""))); Exceptions::ThrowByType(Exceptions::kArgumentValue, error_args); UNREACHABLE(); } type_arg ^= args.At(i); type_args_obj.SetTypeAt(i, type_arg); } Type& instantiated_type = Type::Handle(Type::New(clz, type_args_obj, TokenPosition::kNoSource)); instantiated_type ^= ClassFinalizer::FinalizeType(clz, instantiated_type); return instantiated_type.raw(); } DEFINE_NATIVE_ENTRY(Mirrors_mangleName, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(String, name, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Library& lib = Library::Handle(ref.GetLibraryReferent()); return lib.IsPrivate(name) ? lib.PrivateName(name) : name.raw(); } DEFINE_NATIVE_ENTRY(MirrorReference_equals, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, a, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, b, arguments->NativeArgAt(1)); return Bool::Get(a.referent() == b.referent()).raw(); } DEFINE_NATIVE_ENTRY(DeclarationMirror_metadata, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, reflectee, arguments->NativeArgAt(0)); Object& decl = Object::Handle(); if (reflectee.IsMirrorReference()) { const MirrorReference& decl_ref = MirrorReference::Cast(reflectee); decl = decl_ref.referent(); } else if (reflectee.IsTypeParameter()) { decl = reflectee.raw(); } else { UNREACHABLE(); } Class& klass = Class::Handle(); Library& library = Library::Handle(); if (decl.IsClass()) { klass ^= decl.raw(); library = klass.library(); } else if (decl.IsFunction() && !Function::Cast(decl).IsSignatureFunction()) { klass = Function::Cast(decl).origin(); library = klass.library(); } else if (decl.IsField()) { klass = Field::Cast(decl).Origin(); library = klass.library(); } else if (decl.IsLibrary()) { library ^= decl.raw(); } else if (decl.IsTypeParameter()) { if (TypeParameter::Cast(decl).IsFunctionTypeParameter()) { // TODO(regis): Fully support generic functions. return Object::empty_array().raw(); } klass = TypeParameter::Cast(decl).parameterized_class(); library = klass.library(); } else { return Object::empty_array().raw(); } const Object& metadata = Object::Handle(library.GetMetadata(decl)); if (metadata.IsError()) { Exceptions::PropagateError(Error::Cast(metadata)); } return metadata.raw(); } DEFINE_NATIVE_ENTRY(FunctionTypeMirror_call_method, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, owner_mirror, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); // TODO(rmacnak): Return get:call() method on class _Closure instead? // This now returns the result of invoking that call getter. const Function& func = Function::Handle(ref.GetFunctionReferent()); ASSERT(!func.IsNull()); return CreateMethodMirror(func, owner_mirror, AbstractType::Handle()); } DEFINE_NATIVE_ENTRY(FunctionTypeMirror_parameters, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, owner, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Function& func = Function::Handle(ref.GetFunctionReferent()); return CreateParameterMirrorList(func, owner); } DEFINE_NATIVE_ENTRY(FunctionTypeMirror_return_type, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0)); const Function& func = Function::Handle(ref.GetFunctionReferent()); ASSERT(!func.IsNull()); AbstractType& type = AbstractType::Handle(func.result_type()); // Signatures of function types are instantiated, but not canonical. return type.Canonicalize(); } DEFINE_NATIVE_ENTRY(ClassMirror_libraryUri, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0)); const Class& klass = Class::Handle(ref.GetClassReferent()); const Library& library = Library::Handle(klass.library()); ASSERT(!library.IsNull()); return library.url(); } DEFINE_NATIVE_ENTRY(ClassMirror_supertype, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0)); ASSERT(type.IsFinalized()); const Class& cls = Class::Handle(type.type_class()); const AbstractType& super_type = AbstractType::Handle(cls.super_type()); ASSERT(super_type.IsNull() || super_type.IsFinalized()); return super_type.raw(); } DEFINE_NATIVE_ENTRY(ClassMirror_supertype_instantiated, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0)); ASSERT(type.IsFinalized()); const Class& cls = Class::Handle(type.type_class()); const AbstractType& super_type = AbstractType::Handle(cls.super_type()); return InstantiateType(super_type, type); } DEFINE_NATIVE_ENTRY(ClassMirror_interfaces, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0)); ASSERT(type.IsFinalized()); const Class& cls = Class::Handle(type.type_class()); const Error& error = Error::Handle(cls.EnsureIsFinalized(thread)); if (!error.IsNull()) { Exceptions::PropagateError(error); } return cls.interfaces(); } DEFINE_NATIVE_ENTRY(ClassMirror_interfaces_instantiated, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0)); ASSERT(type.IsFinalized()); const Class& cls = Class::Handle(type.type_class()); const Error& error = Error::Handle(cls.EnsureIsFinalized(thread)); if (!error.IsNull()) { Exceptions::PropagateError(error); } Array& interfaces = Array::Handle(cls.interfaces()); Array& interfaces_inst = Array::Handle(Array::New(interfaces.Length())); AbstractType& interface = AbstractType::Handle(); for (int i = 0; i < interfaces.Length(); i++) { interface ^= interfaces.At(i); interface = InstantiateType(interface, type); interfaces_inst.SetAt(i, interface); } return interfaces_inst.raw(); } DEFINE_NATIVE_ENTRY(ClassMirror_mixin, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0)); ASSERT(type.IsFinalized()); const Class& cls = Class::Handle(type.type_class()); AbstractType& mixin_type = AbstractType::Handle(); if (cls.is_transformed_mixin_application()) { const Array& interfaces = Array::Handle(cls.interfaces()); mixin_type ^= interfaces.At(interfaces.Length() - 1); } ASSERT(mixin_type.IsNull() || mixin_type.IsFinalized()); return mixin_type.raw(); } DEFINE_NATIVE_ENTRY(ClassMirror_mixin_instantiated, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, instantiator, arguments->NativeArgAt(1)); ASSERT(type.IsFinalized()); const Class& cls = Class::Handle(type.type_class()); AbstractType& mixin_type = AbstractType::Handle(); if (cls.is_transformed_mixin_application()) { const Array& interfaces = Array::Handle(cls.interfaces()); mixin_type ^= interfaces.At(interfaces.Length() - 1); } if (mixin_type.IsNull()) { return mixin_type.raw(); } return InstantiateType(mixin_type, instantiator); } DEFINE_NATIVE_ENTRY(ClassMirror_members, 0, 3) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, owner_mirror, arguments->NativeArgAt(0)); GET_NATIVE_ARGUMENT(AbstractType, owner_instantiator, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(2)); const Class& klass = Class::Handle(ref.GetClassReferent()); const Error& error = Error::Handle(klass.EnsureIsFinalized(thread)); if (!error.IsNull()) { Exceptions::PropagateError(error); } const Array& fields = Array::Handle(klass.fields()); const intptr_t num_fields = fields.Length(); const Array& functions = Array::Handle(klass.functions()); const intptr_t num_functions = functions.Length(); Instance& member_mirror = Instance::Handle(); const GrowableObjectArray& member_mirrors = GrowableObjectArray::Handle( GrowableObjectArray::New(num_fields + num_functions)); Field& field = Field::Handle(); for (intptr_t i = 0; i < num_fields; i++) { field ^= fields.At(i); if (field.is_reflectable()) { member_mirror = CreateVariableMirror(field, owner_mirror); member_mirrors.Add(member_mirror); } } Function& func = Function::Handle(); for (intptr_t i = 0; i < num_functions; i++) { func ^= functions.At(i); if (func.is_reflectable() && (func.kind() == RawFunction::kRegularFunction || func.kind() == RawFunction::kGetterFunction || func.kind() == RawFunction::kSetterFunction)) { member_mirror = CreateMethodMirror(func, owner_mirror, owner_instantiator); member_mirrors.Add(member_mirror); } } return member_mirrors.raw(); } DEFINE_NATIVE_ENTRY(ClassMirror_constructors, 0, 3) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, owner_mirror, arguments->NativeArgAt(0)); GET_NATIVE_ARGUMENT(AbstractType, owner_instantiator, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(2)); const Class& klass = Class::Handle(ref.GetClassReferent()); const Error& error = Error::Handle(klass.EnsureIsFinalized(thread)); if (!error.IsNull()) { Exceptions::PropagateError(error); } const Array& functions = Array::Handle(klass.functions()); const intptr_t num_functions = functions.Length(); Instance& constructor_mirror = Instance::Handle(); const GrowableObjectArray& constructor_mirrors = GrowableObjectArray::Handle(GrowableObjectArray::New(num_functions)); Function& func = Function::Handle(); for (intptr_t i = 0; i < num_functions; i++) { func ^= functions.At(i); if (func.is_reflectable() && func.kind() == RawFunction::kConstructor) { constructor_mirror = CreateMethodMirror(func, owner_mirror, owner_instantiator); constructor_mirrors.Add(constructor_mirror); } } return constructor_mirrors.raw(); } DEFINE_NATIVE_ENTRY(LibraryMirror_members, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, owner_mirror, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Library& library = Library::Handle(zone, ref.GetLibraryReferent()); library.EnsureTopLevelClassIsFinalized(); Instance& member_mirror = Instance::Handle(zone); const GrowableObjectArray& member_mirrors = GrowableObjectArray::Handle(zone, GrowableObjectArray::New()); Object& entry = Object::Handle(zone); DictionaryIterator entries(library); Error& error = Error::Handle(zone); AbstractType& type = AbstractType::Handle(zone); while (entries.HasNext()) { entry = entries.GetNext(); if (entry.IsClass()) { const Class& klass = Class::Cast(entry); // We filter out dynamic. // TODO(12478): Should not need to filter out dynamic. if (!klass.IsDynamicClass()) { error = klass.EnsureIsFinalized(thread); if (!error.IsNull()) { Exceptions::PropagateError(error); } type = klass.DeclarationType(); member_mirror = CreateClassMirror(klass, type, Bool::True(), // is_declaration owner_mirror); member_mirrors.Add(member_mirror); } } else if (entry.IsField()) { const Field& field = Field::Cast(entry); if (field.is_reflectable()) { member_mirror = CreateVariableMirror(field, owner_mirror); member_mirrors.Add(member_mirror); } } else if (entry.IsFunction()) { const Function& func = Function::Cast(entry); if (func.is_reflectable() && (func.kind() == RawFunction::kRegularFunction || func.kind() == RawFunction::kGetterFunction || func.kind() == RawFunction::kSetterFunction)) { member_mirror = CreateMethodMirror(func, owner_mirror, AbstractType::Handle()); member_mirrors.Add(member_mirror); } } } return member_mirrors.raw(); } DEFINE_NATIVE_ENTRY(ClassMirror_type_variables, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0)); const Class& klass = Class::Handle(ref.GetClassReferent()); const Error& error = Error::Handle(zone, klass.EnsureIsFinalized(thread)); if (!error.IsNull()) { Exceptions::PropagateError(error); UNREACHABLE(); } return CreateTypeVariableList(klass); } DEFINE_NATIVE_ENTRY(ClassMirror_type_arguments, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, type, arguments->NativeArgAt(0)); const Class& cls = Class::Handle(type.type_class()); const intptr_t num_params = cls.NumTypeParameters(); if (num_params == 0) { return Object::empty_array().raw(); } const Array& result = Array::Handle(Array::New(num_params)); AbstractType& arg_type = AbstractType::Handle(); Instance& type_mirror = Instance::Handle(); const TypeArguments& args = TypeArguments::Handle(type.arguments()); // Handle argument lists that have been optimized away, because either no // arguments have been provided, or all arguments are dynamic. Return a list // of typemirrors on dynamic in this case. if (args.IsNull()) { arg_type = Object::dynamic_type().raw(); type_mirror = CreateTypeMirror(arg_type); for (intptr_t i = 0; i < num_params; i++) { result.SetAt(i, type_mirror); } return result.raw(); } ASSERT(args.Length() >= num_params); const intptr_t num_inherited_args = args.Length() - num_params; for (intptr_t i = 0; i < num_params; i++) { arg_type = args.TypeAt(i + num_inherited_args); type_mirror = CreateTypeMirror(arg_type); result.SetAt(i, type_mirror); } return result.raw(); } DEFINE_NATIVE_ENTRY(TypeVariableMirror_owner, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(TypeParameter, param, arguments->NativeArgAt(0)); Class& owner = Class::Handle(param.parameterized_class()); AbstractType& type = AbstractType::Handle(); if (owner.IsNull()) { // TODO(regis): Fully support generic functions. For now, reify function // type parameters to dynamic and map their function owner to Null class. ASSERT(param.IsFunctionTypeParameter()); type = Type::NullType(); owner = type.type_class(); } else { type = owner.DeclarationType(); } return CreateClassMirror(owner, type, Bool::True(), // is_declaration Instance::null_instance()); } DEFINE_NATIVE_ENTRY(TypeVariableMirror_upper_bound, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(TypeParameter, param, arguments->NativeArgAt(0)); return param.bound(); } DEFINE_NATIVE_ENTRY(TypedefMirror_declaration, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Type, type, arguments->NativeArgAt(0)); ASSERT(type.IsFunctionType()); const Class& cls = Class::Handle(type.type_class()); ASSERT(cls.IsTypedefClass()); return CreateTypedefMirror(cls, AbstractType::Handle(cls.DeclarationType()), Bool::True(), // is_declaration Object::null_instance()); } DEFINE_NATIVE_ENTRY(InstanceMirror_invoke, 0, 5) { // Argument 0 is the mirror, which is unused by the native. It exists // because this native is an instance method in order to be polymorphic // with its cousins. GET_NATIVE_ARGUMENT(Instance, reflectee, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(String, function_name, arguments->NativeArgAt(2)); GET_NON_NULL_NATIVE_ARGUMENT(Array, args, arguments->NativeArgAt(3)); GET_NON_NULL_NATIVE_ARGUMENT(Array, arg_names, arguments->NativeArgAt(4)); RETURN_OR_PROPAGATE(reflectee.Invoke(function_name, args, arg_names)); } DEFINE_NATIVE_ENTRY(InstanceMirror_invokeGetter, 0, 3) { // Argument 0 is the mirror, which is unused by the native. It exists // because this native is an instance method in order to be polymorphic // with its cousins. GET_NATIVE_ARGUMENT(Instance, reflectee, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(String, getter_name, arguments->NativeArgAt(2)); RETURN_OR_PROPAGATE(reflectee.InvokeGetter(getter_name)); } DEFINE_NATIVE_ENTRY(InstanceMirror_invokeSetter, 0, 4) { // Argument 0 is the mirror, which is unused by the native. It exists // because this native is an instance method in order to be polymorphic // with its cousins. GET_NATIVE_ARGUMENT(Instance, reflectee, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(String, setter_name, arguments->NativeArgAt(2)); GET_NATIVE_ARGUMENT(Instance, value, arguments->NativeArgAt(3)); RETURN_OR_PROPAGATE(reflectee.InvokeSetter(setter_name, value)); } DEFINE_NATIVE_ENTRY(InstanceMirror_computeType, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, instance, arguments->NativeArgAt(0)); const AbstractType& type = AbstractType::Handle(instance.GetType(Heap::kNew)); // The static type of null is specified to be the bottom type, however, the // runtime type of null is the Null type, which we correctly return here. return type.Canonicalize(); } DEFINE_NATIVE_ENTRY(ClosureMirror_function, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, closure, arguments->NativeArgAt(0)); ASSERT(!closure.IsNull()); Function& function = Function::Handle(); bool callable = closure.IsCallable(&function); if (callable) { const Function& parent = Function::Handle(function.parent_function()); if (function.IsImplicitClosureFunction() || parent.is_extension_member()) { // The VM uses separate Functions for tear-offs, but the mirrors consider // the tear-offs to be the same as the torn-off methods. Avoid handing out // a reference to the tear-off here to avoid a special case in the // the equality test. // In the case of extension methods also we avoid handing out a reference // to the tear-off and instead get the parent function of the // anonymous closure. function = parent.raw(); } Type& instantiator = Type::Handle(); if (closure.IsClosure()) { const TypeArguments& arguments = TypeArguments::Handle( Closure::Cast(closure).instantiator_type_arguments()); // TODO(regis): Mirrors need work to properly support generic functions. // The 'instantiator' created below should not be a type, but two type // argument vectors: instantiator_type_arguments and // function_type_arguments. const Class& cls = Class::Handle(Isolate::Current()->object_store()->object_class()); instantiator = Type::New(cls, arguments, TokenPosition::kNoSource); instantiator.SetIsFinalized(); } return CreateMethodMirror(function, Instance::null_instance(), instantiator); } return Instance::null(); } DEFINE_NATIVE_ENTRY(ClassMirror_invoke, 0, 5) { // Argument 0 is the mirror, which is unused by the native. It exists // because this native is an instance method in order to be polymorphic // with its cousins. GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Class& klass = Class::Handle(ref.GetClassReferent()); GET_NON_NULL_NATIVE_ARGUMENT(String, function_name, arguments->NativeArgAt(2)); GET_NON_NULL_NATIVE_ARGUMENT(Array, args, arguments->NativeArgAt(3)); GET_NON_NULL_NATIVE_ARGUMENT(Array, arg_names, arguments->NativeArgAt(4)); RETURN_OR_PROPAGATE(klass.Invoke(function_name, args, arg_names)); } DEFINE_NATIVE_ENTRY(ClassMirror_invokeGetter, 0, 3) { // Argument 0 is the mirror, which is unused by the native. It exists // because this native is an instance method in order to be polymorphic // with its cousins. GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Class& klass = Class::Handle(ref.GetClassReferent()); const Error& error = Error::Handle(zone, klass.EnsureIsFinalized(thread)); if (!error.IsNull()) { Exceptions::PropagateError(error); UNREACHABLE(); } GET_NON_NULL_NATIVE_ARGUMENT(String, getter_name, arguments->NativeArgAt(2)); RETURN_OR_PROPAGATE(klass.InvokeGetter(getter_name, true)); } DEFINE_NATIVE_ENTRY(ClassMirror_invokeSetter, 0, 4) { // Argument 0 is the mirror, which is unused by the native. It exists // because this native is an instance method in order to be polymorphic // with its cousins. GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Class& klass = Class::Handle(ref.GetClassReferent()); GET_NON_NULL_NATIVE_ARGUMENT(String, setter_name, arguments->NativeArgAt(2)); GET_NATIVE_ARGUMENT(Instance, value, arguments->NativeArgAt(3)); RETURN_OR_PROPAGATE(klass.InvokeSetter(setter_name, value)); } DEFINE_NATIVE_ENTRY(ClassMirror_invokeConstructor, 0, 5) { GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0)); const Class& klass = Class::Handle(ref.GetClassReferent()); GET_NATIVE_ARGUMENT(Type, type, arguments->NativeArgAt(1)); GET_NON_NULL_NATIVE_ARGUMENT(String, constructor_name, arguments->NativeArgAt(2)); GET_NON_NULL_NATIVE_ARGUMENT(Array, explicit_args, arguments->NativeArgAt(3)); GET_NON_NULL_NATIVE_ARGUMENT(Array, arg_names, arguments->NativeArgAt(4)); const Error& error = Error::Handle(zone, klass.EnsureIsFinalized(thread)); if (!error.IsNull()) { Exceptions::PropagateError(error); UNREACHABLE(); } // By convention, the static function implementing a named constructor 'C' // for class 'A' is labeled 'A.C', and the static function implementing the // unnamed constructor for class 'A' is labeled 'A.'. // This convention prevents users from explicitly calling constructors. const String& klass_name = String::Handle(klass.Name()); String& external_constructor_name = String::Handle(klass_name.raw()); String& internal_constructor_name = String::Handle(String::Concat(klass_name, Symbols::Dot())); if (!constructor_name.IsNull() && constructor_name.Length() > 0) { internal_constructor_name = String::Concat(internal_constructor_name, constructor_name); external_constructor_name = internal_constructor_name.raw(); } Function& lookup_constructor = Function::Handle(klass.LookupFunction(internal_constructor_name)); if (lookup_constructor.IsNull() || (lookup_constructor.kind() != RawFunction::kConstructor) || !lookup_constructor.is_reflectable()) { ThrowNoSuchMethod(AbstractType::Handle(klass.RareType()), external_constructor_name, explicit_args, arg_names, InvocationMirror::kConstructor, InvocationMirror::kMethod); UNREACHABLE(); } if (klass.is_abstract() && !lookup_constructor.IsFactory()) { const Array& error_args = Array::Handle(Array::New(3)); error_args.SetAt(0, klass_name); // 1 = script url // 2 = token position Exceptions::ThrowByType(Exceptions::kAbstractClassInstantiation, error_args); UNREACHABLE(); } ASSERT(!type.IsNull()); TypeArguments& type_arguments = TypeArguments::Handle(type.arguments()); if (!type.IsInstantiated()) { // Must have been a declaration type. AbstractType& rare_type = AbstractType::Handle(klass.RareType()); ASSERT(rare_type.IsInstantiated()); type_arguments = rare_type.arguments(); } Class& redirected_klass = Class::Handle(klass.raw()); Function& redirected_constructor = Function::Handle(lookup_constructor.raw()); if (lookup_constructor.IsRedirectingFactory()) { // Redirecting factory must be resolved. ASSERT(lookup_constructor.RedirectionTarget() != Function::null()); Type& redirect_type = Type::Handle(lookup_constructor.RedirectionType()); if (!redirect_type.IsInstantiated()) { // The type arguments of the redirection type are instantiated from the // type arguments of the type reflected by the class mirror. ASSERT(redirect_type.IsInstantiated(kFunctions)); redirect_type ^= redirect_type.InstantiateFrom( NNBDMode::kLegacyLib_LegacyTest, type_arguments, Object::null_type_arguments(), kNoneFree, NULL, Heap::kOld); redirect_type ^= redirect_type.Canonicalize(); } type = redirect_type.raw(); type_arguments = redirect_type.arguments(); redirected_constructor = lookup_constructor.RedirectionTarget(); ASSERT(!redirected_constructor.IsNull()); redirected_klass = type.type_class(); } const intptr_t num_explicit_args = explicit_args.Length(); const intptr_t num_implicit_args = 1; const Array& args = Array::Handle(Array::New(num_implicit_args + num_explicit_args)); // Copy over the explicit arguments. Object& explicit_argument = Object::Handle(); for (int i = 0; i < num_explicit_args; i++) { explicit_argument = explicit_args.At(i); args.SetAt(i + num_implicit_args, explicit_argument); } const int kTypeArgsLen = 0; const Array& args_descriptor_array = Array::Handle( ArgumentsDescriptor::New(kTypeArgsLen, args.Length(), arg_names)); ArgumentsDescriptor args_descriptor(args_descriptor_array); if (!redirected_constructor.AreValidArguments(NNBDMode::kLegacyLib_LegacyTest, args_descriptor, NULL)) { external_constructor_name = redirected_constructor.name(); ThrowNoSuchMethod(AbstractType::Handle(klass.RareType()), external_constructor_name, explicit_args, arg_names, InvocationMirror::kConstructor, InvocationMirror::kMethod); UNREACHABLE(); } const Object& type_error = Object::Handle(redirected_constructor.DoArgumentTypesMatch( NNBDMode::kLegacyLib_LegacyTest, args, args_descriptor, type_arguments)); if (!type_error.IsNull()) { Exceptions::PropagateError(Error::Cast(type_error)); UNREACHABLE(); } Instance& new_object = Instance::Handle(); if (redirected_constructor.IsGenerativeConstructor()) { // Constructors get the uninitialized object. // Note we have delayed allocation until after the function // type and argument matching checks. new_object = Instance::New(redirected_klass); if (!type_arguments.IsNull()) { // The type arguments will be null if the class has no type parameters, in // which case the following call would fail because there is no slot // reserved in the object for the type vector. new_object.SetTypeArguments(type_arguments); } args.SetAt(0, new_object); } else { // Factories get type arguments. args.SetAt(0, type_arguments); } // Invoke the constructor and return the new object. const Object& result = Object::Handle(DartEntry::InvokeFunction( redirected_constructor, args, args_descriptor_array)); if (result.IsError()) { Exceptions::PropagateError(Error::Cast(result)); UNREACHABLE(); } // Factories may return null. ASSERT(result.IsInstance() || result.IsNull()); if (redirected_constructor.IsGenerativeConstructor()) { return new_object.raw(); } else { return result.raw(); } } DEFINE_NATIVE_ENTRY(LibraryMirror_invoke, 0, 5) { // Argument 0 is the mirror, which is unused by the native. It exists // because this native is an instance method in order to be polymorphic // with its cousins. GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Library& library = Library::Handle(ref.GetLibraryReferent()); GET_NON_NULL_NATIVE_ARGUMENT(String, function_name, arguments->NativeArgAt(2)); GET_NON_NULL_NATIVE_ARGUMENT(Array, args, arguments->NativeArgAt(3)); GET_NON_NULL_NATIVE_ARGUMENT(Array, arg_names, arguments->NativeArgAt(4)); RETURN_OR_PROPAGATE(library.Invoke(function_name, args, arg_names)); } DEFINE_NATIVE_ENTRY(LibraryMirror_invokeGetter, 0, 3) { // Argument 0 is the mirror, which is unused by the native. It exists // because this native is an instance method in order to be polymorphic // with its cousins. GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Library& library = Library::Handle(ref.GetLibraryReferent()); GET_NON_NULL_NATIVE_ARGUMENT(String, getter_name, arguments->NativeArgAt(2)); RETURN_OR_PROPAGATE(library.InvokeGetter(getter_name, true)); } DEFINE_NATIVE_ENTRY(LibraryMirror_invokeSetter, 0, 4) { // Argument 0 is the mirror, which is unused by the native. It exists // because this native is an instance method in order to be polymorphic // with its cousins. GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Library& library = Library::Handle(ref.GetLibraryReferent()); GET_NON_NULL_NATIVE_ARGUMENT(String, setter_name, arguments->NativeArgAt(2)); GET_NATIVE_ARGUMENT(Instance, value, arguments->NativeArgAt(3)); RETURN_OR_PROPAGATE(library.InvokeSetter(setter_name, value)); } DEFINE_NATIVE_ENTRY(MethodMirror_owner, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0)); GET_NATIVE_ARGUMENT(AbstractType, instantiator, arguments->NativeArgAt(1)); const Function& func = Function::Handle(ref.GetFunctionReferent()); if (func.IsNonImplicitClosureFunction()) { return CreateMethodMirror(Function::Handle(func.parent_function()), Object::null_instance(), instantiator); } const Class& owner = Class::Handle(func.Owner()); if (owner.IsTopLevel()) { return CreateLibraryMirror(thread, Library::Handle(owner.library())); } AbstractType& type = AbstractType::Handle(owner.DeclarationType()); return CreateClassMirror(owner, type, Bool::True(), Object::null_instance()); } DEFINE_NATIVE_ENTRY(MethodMirror_parameters, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, owner, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(1)); const Function& func = Function::Handle(ref.GetFunctionReferent()); return CreateParameterMirrorList(func, owner); } DEFINE_NATIVE_ENTRY(MethodMirror_return_type, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0)); const Function& func = Function::Handle(ref.GetFunctionReferent()); GET_NATIVE_ARGUMENT(AbstractType, instantiator, arguments->NativeArgAt(1)); // We handle constructors in Dart code. ASSERT(!func.IsGenerativeConstructor()); AbstractType& type = AbstractType::Handle(func.result_type()); type = type.Canonicalize(); // Instantiated signatures are not canonical. return InstantiateType(type, instantiator); } DEFINE_NATIVE_ENTRY(MethodMirror_source, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0)); const Function& func = Function::Handle(ref.GetFunctionReferent()); return func.GetSource(); } static RawInstance* CreateSourceLocation(const String& uri, intptr_t line, intptr_t column) { const Array& args = Array::Handle(Array::New(3)); args.SetAt(0, uri); args.SetAt(1, Smi::Handle(Smi::New(line))); args.SetAt(2, Smi::Handle(Smi::New(column))); return CreateMirror(Symbols::_SourceLocation(), args); } DEFINE_NATIVE_ENTRY(DeclarationMirror_location, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Instance, reflectee, arguments->NativeArgAt(0)); Object& decl = Object::Handle(zone); if (reflectee.IsMirrorReference()) { const MirrorReference& decl_ref = MirrorReference::Cast(reflectee); decl = decl_ref.referent(); } else if (reflectee.IsTypeParameter()) { decl = reflectee.raw(); } else { UNREACHABLE(); } Script& script = Script::Handle(zone); TokenPosition token_pos = TokenPosition::kNoSource; if (decl.IsFunction()) { const Function& func = Function::Cast(decl); if (func.IsImplicitConstructor() || func.IsSignatureFunction()) { // These are synthetic methods; they have no source. return Instance::null(); } script = func.script(); token_pos = func.token_pos(); } else if (decl.IsClass()) { const Class& cls = Class::Cast(decl); const bool is_typedef = cls.IsTypedefClass(); if (cls.is_synthesized_class() && !is_typedef && !cls.is_enum_class()) { return Instance::null(); // Synthetic. } script = cls.script(); token_pos = cls.token_pos(); } else if (decl.IsField()) { const Field& field = Field::Cast(decl); script = field.Script(); token_pos = field.token_pos(); } else if (decl.IsTypeParameter()) { const TypeParameter& type_var = TypeParameter::Cast(decl); if (type_var.IsFunctionTypeParameter()) { // TODO(regis): Support generic functions. return Instance::null(); } const Class& owner = Class::Handle(zone, type_var.parameterized_class()); script = owner.script(); token_pos = type_var.token_pos(); } else if (decl.IsLibrary()) { const Library& lib = Library::Cast(decl); if (lib.raw() == Library::NativeWrappersLibrary()) { return Instance::null(); // No source. } const Array& scripts = Array::Handle(zone, lib.LoadedScripts()); ASSERT(scripts.Length() > 0); script ^= scripts.At(scripts.Length() - 1); ASSERT(!script.IsNull()); const String& uri = String::Handle(zone, script.url()); return CreateSourceLocation(uri, 1, 1); } ASSERT(!script.IsNull()); if (token_pos == TokenPosition::kNoSource) { return Instance::null(); } const String& uri = String::Handle(zone, script.url()); intptr_t from_line = 0; intptr_t from_col = 0; if (script.HasSource()) { script.GetTokenLocation(token_pos, &from_line, &from_col); } else { // Avoid the slow path of printing the token stream when precise source // information is not available. script.GetTokenLocation(token_pos, &from_line, NULL); } // We should always have at least the line number. ASSERT(from_line != 0); return CreateSourceLocation(uri, from_line, from_col); } DEFINE_NATIVE_ENTRY(TypedefMirror_referent, 0, 1) { GET_NON_NULL_NATIVE_ARGUMENT(Type, type, arguments->NativeArgAt(0)); ASSERT(type.IsFunctionType()); const Class& cls = Class::Handle(type.type_class()); ASSERT(cls.IsTypedefClass()); const Function& sig_func = Function::Handle(cls.signature_function()); Type& referent_type = Type::Handle(sig_func.SignatureType()); ASSERT(cls.raw() == referent_type.type_class()); referent_type ^= InstantiateType(referent_type, type); return CreateFunctionTypeMirror(referent_type); } DEFINE_NATIVE_ENTRY(ParameterMirror_type, 0, 3) { GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(Smi, pos, arguments->NativeArgAt(1)); GET_NATIVE_ARGUMENT(AbstractType, instantiator, arguments->NativeArgAt(2)); const Function& func = Function::Handle(ref.GetFunctionReferent()); AbstractType& type = AbstractType::Handle( func.ParameterTypeAt(func.NumImplicitParameters() + pos.Value())); type = type.Canonicalize(); // Instantiated signatures are not canonical. return InstantiateType(type, instantiator); } DEFINE_NATIVE_ENTRY(VariableMirror_type, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(MirrorReference, ref, arguments->NativeArgAt(0)); const Field& field = Field::Handle(ref.GetFieldReferent()); GET_NATIVE_ARGUMENT(AbstractType, instantiator, arguments->NativeArgAt(1)); const AbstractType& type = AbstractType::Handle(field.type()); return InstantiateType(type, instantiator); } DEFINE_NATIVE_ENTRY(TypeMirror_subtypeTest, 0, 2) { GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, a, arguments->NativeArgAt(0)); GET_NON_NULL_NATIVE_ARGUMENT(AbstractType, b, arguments->NativeArgAt(1)); return Bool::Get( a.IsSubtypeOf(NNBDMode::kLegacyLib_LegacyTest, b, Heap::kNew)) .raw(); } #endif // !DART_PRECOMPILED_RUNTIME } // namespace dart ",16271,True,3427.309823533778,median "[[webflux]] = Spring WebFlux [[webflux-introduction]] == Introduction The original web framework included in the Spring Framework, Spring Web MVC, was purpose built for the Servlet API and Servlet containers. The reactive stack, web framework, Spring WebFlux, was added later in version 5.0. It is fully non-blocking, supports http://www.reactive-streams.org/[Reactive Streams] back pressure, and runs on servers such as Netty, Undertow, and Servlet 3.1+ containers. Both web frameworks mirror the names of their source modules https://github.com/spring-projects/spring-framework/tree/master/spring-webmvc[spring-webmvc] and https://github.com/spring-projects/spring-framework/tree/master/spring-webflux[spring-webflux] and co-exist side by side in the Spring Framework. Each module is optional. Applications may use one or the other module, or in some cases both -- e.g. Spring MVC controllers with the reactive `WebClient`. [[webflux-new-framework]] === Why a new web framework? Part of the answer is the need for a non-blocking web stack to handle concurrency with a small number of threads and scale with less hardware resources. Servlet 3.1 did provide an API for non-blocking I/O. However, using it leads away from the rest of the Servlet API where contracts are synchronous (`Filter`, `Servlet`) or blocking (`getParameter`, `getPart`). This was the motivation for a new common API to serve as a foundation across any non-blocking runtime. That is important because of servers such as Netty that are well established in the async, non-blocking space. The other part of the answer is functional programming. Much like the addition of annotations in Java 5 created opportunities -- e.g. annotated REST controllers or unit tests, the addition of lambda expressions in Java 8 created opportunities for functional APIs in Java. This is a boon for non-blocking applications and continuation style APIs -- as popularized by `CompletableFuture` and http://reactivex.io/[ReactiveX], that allow declarative composition of asynchronous logic. At the programming model level Java 8 enabled Spring WebFlux to offer functional web endpoints alongside with annotated controllers. [[webflux-why-reactive]] === Reactive: what and why? We touched on non-blocking and functional but why reactive and what do we mean? The term ""reactive"" refers to programming models that are built around reacting to change -- network component reacting to I/O events, UI controller reacting to mouse events, etc. In that sense non-blocking is reactive because instead of being blocked we are now in the mode of reacting to notifications as operations complete or data becomes available. There is also another important mechanism that we on the Spring team associate with ""reactive"" and that is non-blocking back pressure. In synchronous, imperative code, blocking calls serve as a natural form of back pressure that forces the caller to wait. In non-blocking code it becomes important to control the rate of events so that a fast producer does not overwhelm its destination. Reactive Streams is a https://github.com/reactive-streams/reactive-streams-jvm/blob/v1.0.1/README.md#specification[small spec], also http://download.java.net/java/jdk9/docs/api/java/util/concurrent/Flow.html[adopted] in Java 9, that defines the interaction between asynchronous components with back pressure. For example a data repository -- acting as http://www.reactive-streams.org/reactive-streams-1.0.1-javadoc/org/reactivestreams/Publisher.html[Publisher], can produce data that an HTTP server -- acting as http://www.reactive-streams.org/reactive-streams-1.0.1-javadoc/org/reactivestreams/Subscriber.html[Subscriber], can then write to the response. The main purpose of Reactive Streams is to allow the subscriber to control how fast or how slow the publisher will produce data. [NOTE] ==== *Common question: what if a publisher can't slow down?* + The purpose of Reactive Streams is only to establish the mechanism and a boundary. If a publisher can't slow down then it has to decide whether to buffer, drop, or fail. ==== [[webflux-reactive-api]] === Reactive API Reactive Streams plays an important role for interoperability. It is of interest to libraries and infrastructure components but less useful as an application API because it is too low level. What applications need is a higher level and richer, functional API to compose async logic -- similar to the Java 8 `Stream` API but not only for collections. This is the role that reactive libraries play. https://github.com/reactor/reactor[Reactor] is the reactive library of choice for Spring WebFlux. It provides the https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html[Mono] and https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html[Flux] API types to work on data sequences of 0..1 and 0..N through a rich set of operators aligned with the ReactiveX http://reactivex.io/documentation/operators.html[vocabulary of operators]. Reactor is a Reactive Streams library and therefore all of its operators support non-blocking back pressure. Reactor has a strong focus on server-side Java. It is developed in close collaboration with Spring. WebFlux requires Reactor as a core dependency but it is interoperable with other reactive libraries via Reactive Streams. As a general rule WebFlux APIs accept a plain `Publisher` as input, adapt it to Reactor types internally, use those, and then return either `Flux` or `Mono` as output. So you can pass any `Publisher` as input and you can apply operations on the output, but you'll need to adapt the output for use with another reactive library. Whenever feasible -- e.g. annotated controllers, WebFlux adapts transparently to the use of RxJava or other reactive library. See <> for more details. [[webflux-programming-models]] === Programming models The `spring-web` module contains the reactive foundation that underlies Spring WebFlux -- HTTP abstractions, Reactive Streams server adapters, reactive codecs, and a core Web API whose role is comparable to the Servlet API but with non-blocking semantics. On that foundation Spring WebFlux provides a choice of two programming models: - <> -- consistent with Spring MVC, and based on the same annotations from the `spring-web` module. Both Spring MVC and WebFlux controllers support reactive (Reactor, RxJava) return types and as a result it is not easy to tell them apart. One notable difference is that WebFlux also supports reactive `@RequestBody` arguments. - <> -- lambda-based, lightweight, functional programming model. Think of this as a small library or a set of utilities that an application can use to route and handle requests. The big difference with annotated controllers is that the application is in charge of request handling from start to finish vs declaring intent through annotations and being called back. [[webflux-framework-choice]] === Choosing a web framework Should you use Spring MVC or WebFlux? Let's cover a few different perspectives. If you have a Spring MVC application that works fine, there is no need to change. Imperative programming is the easiest way to write, understand, and debug code. You have maximum choice of libraries since historically most are blocking. If you are already shopping for a non-blocking web stack, Spring WebFlux offers the same execution model benefits as others in this space and also provides a choice of servers -- Netty, Tomcat, Jetty, Undertow, Servlet 3.1+ containers, a choice of programming models -- annotated controllers and functional web endpoints, and a choice of reactive libraries -- Reactor, RxJava, or other. If you are interested in a lightweight, functional web framework for use with Java 8 lambdas or Kotlin then use the Spring WebFlux functional web endpoints. That can also be a good choice for smaller applications or microservices with less complex requirements that can benefit from greater transparency and control. In a microservice architecture you can have a mix of applications with either Spring MVC or Spring WebFlux controllers, or with Spring WebFlux functional endpoints. Having support for the same annotation-based programming model in both frameworks makes it easier to re-use knowledge while also selecting the right tool for the right job. AppConfig simple way to evaluate an application is to check its dependencies. If you have blocking persistence APIs (JPA, JDBC), or networking APIs to use, then Spring MVC is the best choice for common architectures at least. It is technically feasible with both Reactor and RxJava to perform blocking calls on a separate thread but you wouldn't be making the most of a non-blocking web stack. If you have a Spring MVC application with calls to remote services, try the reactive `WebClient`. You can return reactive types (Reactor, RxJava, <>) directly from Spring MVC controller methods. The greater the latency per call, or the interdependency among calls, the more dramatic the benefits. Spring MVC controllers can call other reactive components too. If you have a large team, keep in mind the steep learning curve in the shift to non-blocking, functional, and declarative programming. AppConfig practical way to start without a full switch is to use the reactive `WebClient`. Beyond that start small and measure the benefits. We expect that for a wide range of applications the shift is unnecessary. If you are unsure what benefits to look for, start by learning about how non-blocking I/O works (e.g. concurrency on single-threaded Node.js is not an oxymoron) and its effects. The tag line is ""scale with less hardware"" but that effect is not guaranteed, not without some network I/O that can be slow or unpredictable. This Netflix https://medium.com/netflix-techblog/zuul-2-the-netflix-journey-to-asynchronous-non-blocking-systems-45947377fb5c[blog post] is a good resource. [[webflux-server-choice]] === Choosing a server Spring WebFlux is supported on Netty, Undertow, Tomcat, Jetty, and Servlet 3.1+ containers. Each server is adapted to a common Reactive Streams API. The Spring WebFlux programming models are built on that common API. [NOTE] ==== *Common question: how can Tomcat and Jetty be used in both stacks?* + Tomcat and Jetty are non-blocking at their core. It's the Servlet API that adds a blocking facade. Starting in version 3.1 the Servlet API adds a choice for non-blocking I/O. However its use requires care to avoid other synchronous and blocking parts. For this reason Spring's reactive web stack has a low-level Servlet adapter to bridge to Reactive Streams but the Servlet API is otherwise not exposed for direct use. ==== Spring Boot 2 uses Netty by default with WebFlux because Netty is more widely used in the async, non-blocking space and also provides both client and server that can share resources. By comparison Servlet 3.1 non-blocking I/O hasn't seen much use because the bar to use it is so high. Spring WebFlux opens one practical path to adoption. The default server choice in Spring Boot is mainly about the out-of-the-box experience. Applications can still choose any of the other supported servers which are also highly optimized for performance, fully non-blocking, and adapted to Reactive Streams back pressure. In Spring Boot it is trivial to make the switch. [[webflux-performance]] === Performance vs scale Performance has many characteristics and meanings. Reactive and non-blocking generally do not make applications run faster. They can, in some cases, for example if using the `WebClient` to execute remote calls in parallel. On the whole it requires more work to do things the non-blocking way and that can increase slightly the required processing time. The key expected benefit of reactive and non-blocking is the ability to scale with a small, fixed number of threads and less memory. That makes applications more resilient under load because they scale in a more predictable way. In order to observe those benefits however you need to have some latency including a mix of slow and unpredictable network I/O. That's where the reactive stack begins to show its strengths and the differences can be dramatic. [[webflux-reactive-spring-web]] == Reactive Spring Web The `spring-web` module provides low level infrastructure and HTTP abstractions -- client and server, to build reactive web applications. All public APIs are build around Reactive Streams with Reactor as a backing implementation. Server support is organized in two layers: * <> and server adapters -- the most basic, common API for HTTP request handling with Reactive Streams back pressure. * <> -- slightly higher level but still general purpose server web API with filter chain style processing. [[webflux-httphandler]] === HttpHandler Every HTTP server has some API for HTTP request handling. {api-spring-framework}/http/server/reactive/HttpHandler.html[HttpHandler] is a simple contract with one method to handle a request and response. It is intentionally minimal. Its main purpose is to provide a common, Reactive Streams based API for HTTP request handling over different servers. The `spring-web` module contains adapters for every supported server. The table below shows the server APIs are used and where Reactive Streams support comes from: [cols=""1,2,2"", options=""header""] |=== |Server name|Server API used|Reactive Streams support |Netty |Netty API |https://github.com/reactor/reactor-netty[Reactor Netty] |Undertow |Undertow API |spring-web: Undertow to Reactive Streams bridge |Tomcat |Servlet 3.1 non-blocking I/O; Tomcat API to read and write ByteBuffers vs byte[] |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge |Jetty |Servlet 3.1 non-blocking I/O; Jetty API to write ByteBuffers vs byte[] |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge |Servlet 3.1 container |Servlet 3.1 non-blocking I/O |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge |=== Here are required dependencies, https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-the-Spring-Framework[supported versions], and code snippets for each server: |=== |Server name|Group id|Artifact name |Reactor Netty |io.projectreactor.ipc |reactor-netty |Undertow |io.undertow |undertow-core |Tomcat |org.apache.tomcat.embed |tomcat-embed-core |Jetty |org.eclipse.jetty |jetty-server, jetty-servlet |=== Reactor Netty: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); HttpServer.create(host, port).newHandler(adapter).block(); ---- Undertow: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... UndertowHttpHandlerAdapter adapter = new UndertowHttpHandlerAdapter(handler); Undertow server = Undertow.builder().addHttpListener(port, host).setHandler(adapter).build(); server.start(); ---- Tomcat: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... Servlet servlet = new TomcatHttpHandlerAdapter(handler); Tomcat server = new Tomcat(); File base = new File(System.getProperty(""java.io.tmpdir"")); Context rootContext = server.addContext("""", base.getAbsolutePath()); Tomcat.addServlet(rootContext, ""main"", servlet); rootContext.addServletMappingDecoded(""/"", ""main""); server.setHost(host); server.setPort(port); server.start(); ---- Jetty: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... Servlet servlet = new JettyHttpHandlerAdapter(handler); Server server = new Server(); ServletContextHandler contextHandler = new ServletContextHandler(server, """"); contextHandler.addServlet(new ServletHolder(servlet), ""/""); contextHandler.start(); ServerConnector connector = new ServerConnector(server); connector.setHost(host); connector.setPort(port); server.addConnector(connector); server.start(); ---- [NOTE] ==== To deploy as a WAR to a Servlet 3.1+ container, wrap `HttpHandler` with `ServletHttpHandlerAdapter` and register that as a `Servlet`. This can be automated through the use of {api-spring-framework}/web/server/adapter/AbstractReactiveWebInitializer.html[AbstractReactiveWebInitializer]. ==== [[webflux-web-handler-api]] === WebHandler API `HttpHandler` is the basis for running on different servers. On that base the WebHandler API provides a slightly higher level processing chain of exception handlers ({api-spring-framework}/web/server/WebExceptionHandler.html[WebExceptionHandler]), filters ({api-spring-framework}/web/server/WebFilter.html[WebFilter]), and a target handler ({api-spring-framework}/web/server/WebHandler.html[WebHandler]). All components work on `ServerWebExchange` -- a container for the HTTP request and response that also adds request attributes, session attributes, access to form data, multipart data, and more. The processing chain can be put together with `WebHttpHandlerBuilder` which builds an `HttpHandler` that in turn can be run with a <>. To use the builder either add components individually or point to an `ApplicationContext` to have the following detected: [cols=""2,2,1,3"", options=""header""] |=== |Bean name|Bean type|Count|Description |""webHandler"" |WebHandler |1 |Target handler after filters | |WebFilter |0..N |Filters | |WebExceptionHandler |0..N |Exception handlers after filter chain |""webSessionManager"" |WebSessionManager |0..1 |Custom session manager; `DefaultWebSessionManager` by default |""serverCodecConfigurer"" |ServerCodecConfigurer |0..1 |Custom form and multipart data decoders; `ServerCodecConfigurer.create()` by default |""localeContextResolver"" |LocaleContextResolver |0..1 |Custom resolver for `LocaleContext`; `AcceptHeaderLocaleContextResolver` by default |=== [[webflux-codecs]] === Codecs The `spring-web` module provides {api-spring-framework}/http/codec/HttpMessageReader.html[HttpMessageReader] and {api-spring-framework}/http/codec/HttpMessageWriter.html[HttpMessageWriter] for encoding and decoding the HTTP request and response body with Reactive Streams. It builds on lower level contracts from `spring-core`: * {api-spring-framework}/core/io/buffer/DataBuffer.html[DataBuffer] -- abstraction for byte buffers -- e.g. Netty `ByteBuf`, `java.nio.ByteBuffer`, see <>. * {api-spring-framework}/core/codec/Encoder.html[Encoder] -- serialize a stream of Objects to a stream of data buffers * {api-spring-framework}/core/codec/Decoder.html[Decoder] -- deserialize a stream of data buffers into a stream of Objects Basic `Encoder` and `Decoder` implementations exist in `spring-core` but `spring-web` adds more for JSON, XML, and other formats. You can wrap any `Encoder` and `Decoder` as a reader or writer with `EncoderHttpMessageWriter` and `DecoderHttpMessageReader`. There are some additional, web-only reader and writer implementations for server-sent events, form data, and more. Finally, `ClientCodecConfigurer` and `ServerCodecConfigurer` can be used to initialize a list of readers and writers. They include support for classpath detection and a of defaults along with the ability to override or replace those defaults. [[webflux-dispatcher-handler]] == DispatcherHandler [.small]#<># Spring WebFlux, like Spring MVC, is designed around the front controller pattern where a central `WebHandler`, the `DispatcherHandler`, provides a shared algorithm for request processing while actual work is performed by configurable, delegate components. This model is flexible and supports diverse workflows. `DispatcherHandler` discovers the delegate components it needs from Spring configuration. It is also designed to be a Spring bean itself and implements `ApplicationContextAware` for access to the context it runs in. If `DispatcherHandler` is declared with the bean name ""webHandler"" it is in turn discovered by {api-spring-framework}/web/server/adapter/WebHttpHandlerBuilder.html[WebHttpHandlerBuilder] which puts together a request processing chain as described in <>. Spring configuration in a WebFlux application typically contains: * `DispatcherHandler` with the bean name ""webHandler"" * `WebFilter` and `WebExceptionHandler` beans * <> * Others The configuration is given to `WebHttpHandlerBuilder` to build the processing chain: [source,java,indent=0] [subs=""verbatim,quotes""] ---- ApplicationContext context = ... HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context); ---- The resulting `HttpHandler` is ready for use with a <>. [[webflux-special-bean-types]] === Special bean types [.small]#<># The `DispatcherHandler` delegates to special beans to process requests and render the appropriate responses. By ""special beans"" we mean Spring-managed Object instances that implement one of the framework contracts listed in the table below. Spring WebFlux provides built-in implementations of these contracts but you can also customize, extend, or replace them. [[webflux-special-beans-table]] [cols=""1,2"", options=""header""] |=== | Bean type| Explanation | HandlerMapping | Map a request to a handler. The mapping is based on some criteria the details of which vary by `HandlerMapping` implementation -- annotated controllers, simple URL pattern mappings, etc. The main `HandlerMapping` implementations are `RequestMappingHandlerMapping` based on `@RequestMapping` annotated methods, `RouterFunctionMapping` based on functional endpoint routes, and `SimpleUrlHandlerMapping` based on explicit registrations of URI path patterns to handlers. | HandlerAdapter | Help the `DispatcherHandler` to invoke a handler mapped to a request regardless of how the handler is actually invoked. For example invoking an annotated controller requires resolving annotations. The main purpose of a `HandlerAdapter` is to shield the `DispatcherHandler` from such details. | HandlerResultHandler | Process the result from the handler invocation and finalize the response. The built-in `HandlerResultHandler` implementations are `ResponseEntityResultHandler` supporting `ResponseEntity` return values, `ResponseBodyResultHandler` supporting `@ResponseBody` methods, `ServerResponseResultHandler` supporting the `ServerResponse` returned from functional endpoints, and `ViewResolutionResultHandler` supporting rendering with a view and a model. |=== [[webflux-framework-config]] === Framework Config [.small]#<># The `DispatcherHandler` detects the special beans it needs in the `ApplicationContext`. Applications can declare the special beans they wish to have. However most applications will find a better starting point in the WebFlux Java config which provide a higher level configuration API that in turn make the necessary bean declarations. See <> for more details. [[webflux-dispatcher-handler-sequence]] === Processing [.small]#<># The `DispatcherHandler` processes requests as follows: * Each `HandlerMapping` is asked to find a matching handler and the first match is used. * If a handler is found, it is executed through an appropriate `HandlerAdapter` which exposes the return value from the execution as `HandlerResult`. * The `HandlerResult` is given to an appropriate `HandlerResultHandler` to complete processing by writing to the response directly or using a view to render. [[webflux-controller]] == Annotated Controllers [.small]#<># Spring WebFlux provides an annotation-based programming model where `@Controller` and `@RestController` components use annotations to express request mappings, request input, exception handling, and more. Annotated controllers have flexible method signatures and do not have to extend base classes nor implement specific interfaces. Here is a basic example: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @RestController public class HelloController { @GetMapping(""/hello"") public String handle() { return ""Hello WebFlux""; } } ---- In this example the methods returns a String to be written to the response body. [[webflux-ann-controller]] === @Controller [.small]#<># You can define controller beans using a standard Spring bean definition. The `@Controller` stereotype allows for auto-detection, aligned with Spring general support for detecting `@Component` classes in the classpath and auto-registering bean definitions for them. It also acts as a stereotype for the annotated class, indicating its role as a web component. To enable auto-detection of such `@Controller` beans, you can add component scanning to your Java configuration: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @ComponentScan(""org.example.web"") public class WebConfig { // ... } ---- `@RestController` is a composed annotation that is itself annotated with `@Controller` and `@ResponseBody` indicating a controller whose every method inherits the type-level `@ResponseBody` annotation and therefore writes to the response body (vs model-and-vew rendering). [[webflux-ann-requestmapping]] === Request Mapping [.small]#<># The `@RequestMapping` annotation is used to map requests to controllers methods. It has various attributes to match by URL, HTTP method, request parameters, headers, and media types. It can be used at the class-level to express shared mappings or at the method level to narrow down to a specific endpoint mapping. There are also HTTP method specific shortcut variants of `@RequestMapping`: - `@GetMapping` - `@PostMapping` - `@PutMapping` - `@DeleteMapping` - `@PatchMapping` The shortcut variants are https://github.com/spring-projects/spring-framework/wiki/Spring-Annotation-Programming-Model#composed-annotations[composed annotations] -- themselves annotated with `@RequestMapping`. They are commonly used at the method level. At the class level an `@RequestMapping` is more useful for expressing shared mappings. [source,java,indent=0] [subs=""verbatim,quotes""] ---- @RestController @RequestMapping(""/persons"") class PersonController { @GetMapping(""/{id}"") public Person getPerson(@PathVariable Long id) { // ... } @PostMapping @ResponseStatus(HttpStatus.CREATED) public void add(@RequestBody Person person) { // ... } } ---- [[webflux-ann-requestmapping-uri-templates]] ==== URI Patterns [.small]#<># You can map requests using glob patterns and wildcards: * `?` matches one character * `*` matches zero or more characters within a path segment * `**` match zero or more path segments You can also declare URI variables and access their values with `@PathVariable`: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(""/owners/{ownerId}/pets/{petId}"") public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) { // ... } ---- URI variables can be declared at the class and method level: [source,java,intent=0] [subs=""verbatim,quotes""] ---- @Controller @RequestMapping(""/owners/{ownerId}"") public class OwnerController { @GetMapping(""/pets/{petId}"") public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) { // ... } } ---- URI variables are automatically converted to the appropriate type or`TypeMismatchException` is raised. Simple types -- `int`, `long`, `Date`, are supported by default and you can register support for any other data type. // TODO: see <> and <>. URI variables can be named explicitly -- e.g. `@PathVariable(""customId"")`, but you can leave that detail out if the names are the same and your code is compiled with debugging information or with the `-parameters` compiler flag on Java 8. The syntax `{*varName}` declares a URI variable that matches zero or more remaining path segments. For example `/resources/{*path}` matches all files `/resources/` and the `""path""` variable captures the complete relative path. The syntax `{varName:regex}` declares a URI variable with a regular expressions with the syntax `{varName:regex}` -- e.g. given URL `""/spring-web-3.0.5 .jar""`, the below method extracts the name, version, and file extension: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(""/{name:[a-z-]+}-{version:\\\\d\\\\.\\\\d\\\\.\\\\d}{ext:\\\\.[a-z]+}"") public void handle(@PathVariable String version, @PathVariable String ext) { // ... } ---- URI path patterns can also have embedded `${...}` placeholders that are resolved on startup via `PropertyPlaceHolderConfigurer` against local, system, environment, and other property sources. This can be used for example to parameterize a base URL based on some external configuration. [NOTE] ==== Spring WebFlux uses `PathPattern` and the `PathPatternParser` for URI path matching support both of which are located in `spring-web` and expressly designed for use with HTTP URL paths in web applications where a large number of URI path patterns are matched at runtime. ==== Spring WebFlux does not support suffix pattern matching -- unlike Spring MVC, where a mapping such as `/person` also matches to `/person.{asterisk}`. For URL based content negotiation, if needed, we recommend using a query parameter, which is simpler, more explicit, and less vulnerable to URL path based exploits. [[webflux-ann-requestmapping-pattern-comparison]] ==== Pattern Comparison [.small]#<># When multiple patterns match a URL, they must be compared to find the best match. This is done with `PathPattern.SPECIFICITY_COMPARATOR` which looks for patterns that more specific. For every pattern, a score is computed based the number of URI variables and wildcards where a URI variable scores lower than a wildcard. AppConfig pattern with a lower total score wins. If two patterns have the same score, then the longer is chosen. Catch-all patterns, e.g. `**`, `{*varName}`, are excluded from the scoring and are always sorted last instead. If two patterns are both catch-all, the longer is chosen. [[webflux-ann-requestmapping-consumes]] ==== Consumable Media Types [.small]#<># You can narrow the request mapping based on the `Content-Type` of the request: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @PostMapping(path = ""/pets"", **consumes = ""application/json""**) public void addPet(@RequestBody Pet pet) { // ... } ---- The consumes attribute also supports negation expressions -- e.g. `!text/plain` means any content type other than ""text/plain"". You can declare a shared consumes attribute at the class level. Unlike most other request mapping attributes however when used at the class level, a method-level consumes attribute will overrides rather than extend the class level declaration. [TIP] ==== `MediaType` provides constants for commonly used media types -- e.g. `APPLICATION_JSON_VALUE`, `APPLICATION_JSON_UTF8_VALUE`. ==== [[webflux-ann-requestmapping-produces]] ==== Producible Media Types [.small]#<># You can narrow the request mapping based on the `Accept` request header and the list of content types that a controller method produces: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(path = ""/pets/{petId}"", **produces = ""application/json;charset=UTF-8""**) @ResponseBody public Pet getPet(@PathVariable String petId) { // ... } ---- The media type can specify a character set. Negated expressions are supported -- e.g. `!text/plain` means any content type other than ""text/plain"". You can declare a shared produces attribute at the class level. Unlike most other request mapping attributes however when used at the class level, a method-level produces attribute will overrides rather than extend the class level declaration. [TIP] ==== `MediaType` provides constants for commonly used media types -- e.g. `APPLICATION_JSON_VALUE`, `APPLICATION_JSON_UTF8_VALUE`. ==== [[webflux-ann-requestmapping-params-and-headers]] ==== Parameters and Headers [.small]#<># You can narrow request mappings based on query parameter conditions. You can test for the presence of a query parameter (`""myParam""`), for the absence (`""!myParam""`), or for a specific value (`""myParam=myValue""`): [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(path = ""/pets/{petId}"", **params = ""myParam=myValue""**) public void findPet(@PathVariable String petId) { // ... } ---- You can also use the same with request header conditions: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(path = ""/pets"", **headers = ""myHeader=myValue""**) public void findPet(@PathVariable String petId) { // ... } ---- [[webflux-ann-requestmapping-head-options]] ==== HTTP HEAD, OPTIONS [.small]#<># `@GetMapping` -- and also `@RequestMapping(method=HttpMethod.GET)`, support HTTP HEAD transparently for request mapping purposes. Controller methods don't need to change. AppConfig response wrapper, applied in the `HttpHandler` server adapter, ensures a `""Content-Length""` header is set to the number of bytes written and without actually writing to the response. By default HTTP OPTIONS is handled by setting the ""Allow"" response header to the list of HTTP methods listed in all `@RequestMapping` methods with matching URL patterns. For a `@RequestMapping` without HTTP method declarations, the ""Allow"" header is set to `""GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS""`. Controller methods should always declare the supported HTTP methods for example by using the HTTP method specific variants -- `@GetMapping`, `@PostMapping`, etc. `@RequestMapping` method can be explicitly mapped to HTTP HEAD and HTTP OPTIONS, but that is not necessary in the common case. [[webflux-ann-methods]] === Handler methods [.small]#<># `@RequestMapping` handler methods have a flexible signature and can choose from a range of supported controller method arguments and return values. [[webflux-ann-arguments]] ==== Method arguments [.small]#<># The table below shows supported controller method arguments. Reactive types (Reactor, RxJava, <>) are supported on arguments that require blocking I/O, e.g. reading the request body, to be resolved. This is marked in the description column. Reactive types are not expected on arguments that don't require blocking. JDK 1.8's `java.util.Optional` is supported as a method argument in combination with annotations that have a `required` attribute -- e.g. `@RequestParam`, `@RequestHeader`, etc, and is equivalent to `required=false`. [cols=""1,2"", options=""header""] |=== |Controller method argument|Description |`ServerWebExchange` |Access to the full `ServerWebExchange` -- container for the HTTP request and response, request and session attributes, `checkNotModified` methods, and others. |`ServerHttpRequest`, `ServerHttpResponse` |Access to the HTTP request or response. |`WebSession` |Access to the session; this does not forcing the start of a new session unless attributes are added. Supports reactive types. |`java.security.Principal` |Currently authenticated user; possibly a specific `Principal` implementation class if known. Supports reactive types. |`org.springframework.http.HttpMethod` |The HTTP method of the request. |`java.util.Locale` |The current request locale, determined by the most specific `LocaleResolver` available, in effect, the configured `LocaleResolver`/`LocaleContextResolver`. |Java 6+: `java.util.TimeZone` + Java 8+: `java.time.ZoneId` |The time zone associated with the current request, as determined by a `LocaleContextResolver`. |`@PathVariable` |For access to URI template variables. // TODO: See <>. |`@MatrixVariable` |For access to name-value pairs in URI path segments. // TODO: See <>. |`@RequestParam` |For access to Servlet request parameters. Parameter values are converted to the declared method argument type. // TODO: See <>. |`@RequestHeader` |For access to request headers. Header values are converted to the declared method argument type. // TODO: See <>. |`@RequestBody` |For access to the HTTP request body. Body content is converted to the declared method argument type using ``HttpMessageReader``'s. Supports reactive types. // TODO: See <>. |`HttpEntity` |For access to request headers and body. The body is converted with ``HttpMessageReader``'s. Supports reactive types. // TODO: See <>. |`@RequestPart` |For access to a part in a ""multipart/form-data"" request. Supports reactive types. // TODO: See <> and <>. |`java.util.Map`, `org.springframework.ui.Model`, `org.springframework.ui.ModelMap` |For access and updates of the implicit model that is exposed to the web view. |Command or form object (with optional `@ModelAttribute`) |Command object whose properties to bind to request parameters -- via setters or directly to fields, with customizable type conversion, depending on `@InitBinder` methods and/or the HandlerAdapter configuration (see the `webBindingInitializer` property on `RequestMappingHandlerAdapter`). Command objects along with their validation results are exposed as model attributes, by default using the command class name - e.g. model attribute ""orderAddress"" for a command object of type ""some.package.OrderAddress"". `@ModelAttribute` can be used to customize the model attribute name. Supports reactive types. |`Errors`, `BindingResult` |Validation results for the command/form object data binding; this argument must be declared immediately after the command/form object in the controller method signature. |`SessionStatus` |For marking form processing complete which triggers cleanup of session attributes declared through a class-level `@SessionAttributes` annotation. |`UriComponentsBuilder` |For preparing a URL relative to the current request's host, port, scheme, context path, and the literal part of the servlet mapping also taking into account `Forwarded` and `X-Forwarded-*` headers. |`@SessionAttribute` |For access to any session attribute; in contrast to model attributes stored in the session as a result of a class-level `@SessionAttributes` declaration. |`@RequestAttribute` |For access to request attributes. |=== [[webflux-ann-return-types]] ==== Return values [.small]#<># The table below shows supported controller method return values. Reactive types -- Reactor, RxJava, <> are supported for all return values. [cols=""1,2"", options=""header""] |=== |Controller method return value|Description |`@ResponseBody` |The return value is encoded through ``HttpMessageWriter``s and written to the response. // TODO: See <>. |`HttpEntity`, `ResponseEntity` |The return value specifies the full response including HTTP headers and body be encoded through ``HttpMessageWriter``s and written to the response. // TODO: See <>. |`HttpHeaders` |For returning a response with headers and no body. |`String` |AppConfig view name to be resolved with ``ViewResolver``'s and used together with the implicit model -- determined through command objects and `@ModelAttribute` methods. The handler method may also programmatically enrich the model by declaring a `Model` argument (see above). |`View` |AppConfig `View` instance to use for rendering together with the implicit model -- determined through command objects and `@ModelAttribute` methods. The handler method may also programmatically enrich the model by declaring a `Model` argument (see above). |`java.util.Map`, `org.springframework.ui.Model` |Attributes to be added to the implicit model with the view name implicitly determined from the request path. |`Rendering` |An API for model and view rendering scenarios. |`void` |AppConfig method with a `void`, possibly async (e.g. `Mono`), return type (or a `null` return value) is considered to have fully handled the response if it also has a `ServerHttpResponse`, or a `ServerWebExchange` argument, or an `@ResponseStatus` annotation. The same is true also if the controller has made a positive ETag or lastModified timestamp check. // TODO (see <> for details) If none of the above is true, a `void` return type may also indicate ""no response body"" for REST controllers, or default view name selection for HTML controllers. |`Flux`, `Observable`, or other reactive type |Emit server-sent events; the `SeverSentEvent` wrapper can be omitted when only data needs to be written (however `text/event-stream` must be requested or declared in the mapping through the produces attribute). |Any other return type |AppConfig single model attribute to be added to the implicit model with the view name implicitly determined through a `RequestToViewNameTranslator`; the attribute name may be specified through a method-level `@ModelAttribute` or otherwise a name is selected based on the class name of the return type. |=== include::webflux-functional.adoc[leveloffset=+1] [[webflux-config]] == WebFlux Java Config [.small]#<># The WebFlux Java config provides default configuration suitable for most applications along with a configuration API to customize it. For more advanced customizations, not available in the configuration API, see <>. You do not need to understand the underlying beans created by the Java config, but it's easy to seem them in `WebFluxConfigurationSupport`, and if you want to learn more, see <>. [[webflux-config-enable]] === Enable WebFlux config [.small]#<># Use the `@EnableWebFlux` annotation in your Java config: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig { } ---- The above registers a number of Spring WebFlux <> also adapting to dependencies available on the classpath -- for JSON, XML, etc. [[webflux-config-customize]] === WebFlux config API [.small]#<># In your Java config implement the `WebFluxConfigurer` interface: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { // Implement configuration methods... } ---- [[webflux-config-conversion]] === Conversion, formatting [.small]#<># By default formatters for `Number` and `Date` types are installed, including support for the `@NumberFormat` and `@DateTimeFormat` annotations. Full support for the Joda Time formatting library is also installed if Joda Time is present on the classpath. To register custom formatters and converters: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void addFormatters(FormatterRegistry registry) { // ... } } ---- [NOTE] ==== See <> and the `FormattingConversionServiceFactoryBean` for more information on when to use FormatterRegistrars. ==== [[webflux-config-validation]] === Validation [.small]#<># By default if <> is present on the classpath -- e.g. Hibernate Validator, the `LocalValidatorFactoryBean` is registered as a global <> for use with `@Valid` and `Validated` on `@Controller` method arguments. In your Java config, you can customize the global `Validator` instance: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public Validator getValidator(); { // ... } } ---- Note that you can also register ``Validator``'s locally: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Controller public class MyController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.addValidators(new FooValidator()); } } ---- [TIP] ==== If you need to have a `LocalValidatorFactoryBean` injected somewhere, create a bean and mark it with `@Primary` in order to avoid conflict with the one declared in the MVC config. ==== [[webflux-config-content-negotiation]] === Content type resolvers [.small]#<># You can configure how Spring WebFlux determines the requested media types for ``@Controller``'s from the request. By default only the ""Accept"" header is checked but you can also enable a query parameter based strategy. To customize the requested content type resolution: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configureContentTypeResolver(RequestedContentTypeResolverBuilder builder) { // ... } } ---- [[webflux-config-message-codecs]] === HTTP message codecs [.small]#<># To customize how the request and response body are read and written: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { // ... } } ---- `ServerCodecConfigurer` provides a set of default readers and writers. You can use it to add more readers and writers, customize the default ones, or replace the default ones completely. For Jackson JSON and XML, consider using the {api-spring-framework}/http/converter/json/Jackson2ObjectMapperBuilder.html[Jackson2ObjectMapperBuilder] which customizes Jackson's default properties with the following ones: . http://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/DeserializationFeature.html#FAIL_ON_UNKNOWN_PROPERTIES[`DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES`] is disabled. . http://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/MapperFeature.html#DEFAULT_VIEW_INCLUSION[`MapperFeature.DEFAULT_VIEW_INCLUSION`] is disabled. It also automatically registers the following well-known modules if they are detected on the classpath: . https://github.com/FasterXML/jackson-datatype-jdk7[jackson-datatype-jdk7]: support for Java 7 types like `java.nio.file.Path`. . https://github.com/FasterXML/jackson-datatype-joda[jackson-datatype-joda]: support for Joda-Time types. . https://github.com/FasterXML/jackson-datatype-jsr310[jackson-datatype-jsr310]: support for Java 8 Date & Time API types. . https://github.com/FasterXML/jackson-datatype-jdk8[jackson-datatype-jdk8]: support for other Java 8 types like `Optional`. [[webflux-config-view-resolvers]] === View resolvers [.small]#<># To configure view resolution: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configureViewResolvers(ViewResolverRegistry registry) { // ... } } ---- Note that FreeMarker also requires configuration of the underlying view technology: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { // ... @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPath(""classpath:/templates""); return configurer; } } ---- [[webflux-config-static-resources]] === Static resources [.small]#<># This option provides a convenient way to serve static resources from a list of {api-spring-framework}/core/io/Resource.html[Resource]-based locations. In the example below, given a request that starts with `""/resources""`, the relative path is used to find and serve static resources relative to `""/static""` on the classpath. Resources will be served with a 1-year future expiration to ensure maximum use of the browser cache and a reduction in HTTP requests made by the browser. The `Last-Modified` header is also evaluated and if present a `304` status code is returned. [source,java,indent=0] [subs=""verbatim""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(""/resources/**"") .addResourceLocations(""/public"", ""classpath:/static/"") .setCachePeriod(31556926); } } ---- // TODO: // See also <>. The resource handler also supports a chain of {api-spring-framework}/web/reactive/resource/ResourceResolver.html[ResourceResolver]'s and {api-spring-framework}/web/reactive/resource/ResourceTransformer.html[ResourceTransformer]'s. which can be used to create a toolchain for working with optimized resources. The `VersionResourceResolver` can be used for versioned resource URLs based on an MD5 hash computed from the content, a fixed application version, or other. AppConfig `ContentVersionStrategy` (MD5 hash) is a good choice with some notable exceptions such as JavaScript resources used with a module loader. For example in your Java config; [source,java,indent=0] [subs=""verbatim""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(""/resources/**"") .addResourceLocations(""/public/"") .resourceChain(true) .addResolver(new VersionResourceResolver().addContentVersionStrategy(""/**"")); } } ---- You can use `ResourceUrlProvider` to rewrite URLs and apply the full chain of resolvers and transformers -- e.g. to insert versions. The WebFlux config provides a `ResourceUrlProvider` so it can be injected into others. Unlike Spring MVC at present in WebFlux there is no way to transparely rewrite static resource URLs since the are no view technologies that can make use of a non-blocking chain of resolvers and transformers (e.g. resources on Amazon S3). When serving only local resources the workaround is to use `ResourceUrlProvider` directly (e.g. through a custom tag) and block for 0 seconds. http://www.webjars.org/documentation[WebJars] is also supported via `WebJarsResourceResolver` and automatically registered when `""org.webjars:webjars-locator""` is present on the classpath. The resolver can re-write URLs to include the version of the jar and can also match to incoming URLs without versions -- e.g. `""/jquery/jquery.min.js""` to `""/jquery/1.2.0/jquery.min.js""`. [[webflux-config-path-matching]] === Path Matching [.small]#<># Spring WebFlux uses parsed representation of path patterns -- i.e. `PathPattern`, and also the incoming request path -- i.e. `RequestPath`, which eliminates the need to indicate whether to decode the request path, or remove semicolon content, since `PathPattern` can now access decoded path segment values and match safely. Spring WebFlux also does not support suffix pattern matching so effectively there are only two minor options to customize related to path matching -- whether to match trailing slashes (`true` by default) and whether the match is case-sensitive (`false`). To customize those options: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { // ... } } ---- [[webflux-config-advanced-java]] === Advanced config mode [.small]#<># `@EnableWebFlux` imports `DelegatingWebFluxConfiguration` that (1) provides default Spring configuration for WebFlux applications and (2) detects and delegates to ``WebFluxConfigurer``'s to customize that configuration. For advanced mode, remove `@EnableWebFlux` and extend directly from `DelegatingWebFluxConfiguration` instead of implementing `WebFluxConfigurer`: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration public class WebConfig extends DelegatingWebFluxConfiguration { // ... } ---- You can keep existing methods in `WebConfig` but you can now also override bean declarations from the base class and you can still have any number of other ``WebMvcConfigurer``'s on the classpath. include::webflux-cors.adoc[leveloffset=+1] [[webflux-http2]] == HTTP/2 [.small]#<># Servlet 4 containers are required to support HTTP/2 and Spring Framework 5 is compatible with Servlet API 4. From a programming model perspective there is nothing specific that applications need to do. However there are considerations related to server configuration. For more details please check out the https://github.com/spring-projects/spring-framework/wiki/HTTP-2-support[HTTP/2 wiki page]. Currently Spring WebFlux does not support HTTP/2 with Netty. There is also no support for pushing resources programmatically to the client. ",12500,False,1969.7718213663186,median "// tag::HeaderFullDisplayName[] = ssis.PackageTask_Dft_Component_output_outputcolumn_src - V // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--antorareferencedlist: :ExistsProperty--antorareferencinglist: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--pk_index_guid: :ExistsProperty--pk_indexpatterncolumndatatype: :ExistsProperty--pk_indexpatterncolumnname: :ExistsProperty--referencedobjectlist: :ExistsProperty--sql_modules_definition: :ExistsProperty--FK: :ExistsProperty--AntoraIndexList: :ExistsProperty--Columns: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] 78CC7FC6-CF3F-EC11-852D-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] ssis.PackageTask_Dft_Component_output_outputcolumn_src // end::RepoObject_FullDisplayName2[] == SysObject_type // tag::SysObject_type[] V // end::SysObject_type[] == SysObject_type_name // tag::SysObject_type_name[] view // end::SysObject_type_name[] == SysObject_id // tag::SysObject_id[] 606677259 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-11-07 14:28:41 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] [discrete] == _ [#column-antoramodule] === AntoraModule [cols=""d,8a,m,m,m""] |=== |1 |*AntoraModule* |varchar(50) |NOT NULL | |=== .Referenced Columns -- * xref:ssis.package_src.adoc#column-antoramodule[+ssis.Package_src.AntoraModule+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-antoramodule[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.AntoraModule+] -- [#column-packagename] === PackageName [cols=""d,8a,m,m,m""] |=== |2 |*PackageName* |varchar(200) |NULL | |=== .Description -- (left(replace([PackagePath],[ProjectPath]+'\\',''),(200))) -- {empty} + .Referenced Columns -- * xref:ssis.package_src.adoc#column-packagename[+ssis.Package_src.PackageName+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-packagename[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.PackageName+] -- [#column-columnunderlinerefid] === Column_refId [cols=""d,8a,m,m,m""] |=== |3 |*Column_refId* |varchar(max) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlinerefid[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_refId+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlinerefid[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_refId+] -- [#column-columnunderlinedatatype] === Column_dataType [cols=""d,8a,m,m,m""] |=== | |Column_dataType |varchar(100) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlinedatatype[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_dataType+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlinedatatype[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_dataType+] -- [#column-columnunderlineerrorortruncationoperation] === Column_errorOrTruncationOperation [cols=""d,8a,m,m,m""] |=== | |Column_errorOrTruncationOperation |varchar(100) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlineerrorortruncationoperation[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_errorOrTruncationOperation+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlineerrorortruncationoperation[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_errorOrTruncationOperation+] -- [#column-columnunderlineerrorrowdisposition] === Column_errorRowDisposition [cols=""d,8a,m,m,m""] |=== | |Column_errorRowDisposition |varchar(100) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlineerrorrowdisposition[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_errorRowDisposition+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlineerrorrowdisposition[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_errorRowDisposition+] -- [#column-columnunderlineexternalmetadatacolumnid] === Column_externalMetadataColumnId [cols=""d,8a,m,m,m""] |=== | |Column_externalMetadataColumnId |varchar(max) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlineexternalmetadatacolumnid[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_externalMetadataColumnId+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlineexternalmetadatacolumnid[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_externalMetadataColumnId+] -- [#column-columnunderlinelength] === Column_length [cols=""d,8a,m,m,m""] |=== | |Column_length |int |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlinelength[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_length+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlinelength[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_length+] -- [#column-columnunderlinelineageid] === Column_lineageId [cols=""d,8a,m,m,m""] |=== | |Column_lineageId |varchar(max) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlinelineageid[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_lineageId+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlinelineageid[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_lineageId+] -- [#column-columnunderlinename] === Column_name [cols=""d,8a,m,m,m""] |=== | |Column_name |varchar(max) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlinename[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_name+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlinename[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_name+] -- [#column-columnunderlineprecision] === Column_precision [cols=""d,8a,m,m,m""] |=== | |Column_precision |int |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlineprecision[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_precision+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlineprecision[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_precision+] -- [#column-columnunderlinescale] === Column_scale [cols=""d,8a,m,m,m""] |=== | |Column_scale |int |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlinescale[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_scale+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlinescale[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_scale+] -- [#column-columnunderlinetruncationrowdisposition] === Column_truncationRowDisposition [cols=""d,8a,m,m,m""] |=== | |Column_truncationRowDisposition |varchar(max) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-columnunderlinetruncationrowdisposition[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.Column_truncationRowDisposition+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-columnunderlinetruncationrowdisposition[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Column_truncationRowDisposition+] -- [#column-componentunderlinerefid] === Component_refId [cols=""d,8a,m,m,m""] |=== | |Component_refId |varchar(max) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-refid[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.refId+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-componentunderlinerefid[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.Component_refId+] -- [#column-controlflowdetailsrowid] === ControlFlowDetailsRowID [cols=""d,8a,m,m,m""] |=== | |ControlFlowDetailsRowID |int |NOT NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-controlflowdetailsrowid[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.ControlFlowDetailsRowID+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-controlflowdetailsrowid[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.ControlFlowDetailsRowID+] -- [#column-outputunderlineiserrorout] === output_isErrorOut [cols=""d,8a,m,m,m""] |=== | |output_isErrorOut |bit |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-outputunderlineiserrorout[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.output_isErrorOut+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-outputunderlineiserrorout[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.output_isErrorOut+] -- [#column-outputunderlinename] === output_name [cols=""d,8a,m,m,m""] |=== | |output_name |varchar(500) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-outputunderlinename[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.output_name+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-outputunderlinename[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.output_name+] -- [#column-outputunderlinerefid] === output_refId [cols=""d,8a,m,m,m""] |=== | |output_refId |varchar(max) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc#column-outputunderlinerefid[+ssis_t.TblTask_Dft_Component_outputs_outputColumn_src.output_refId+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-outputunderlinerefid[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.output_refId+] -- [#column-taskpath] === TaskPath [cols=""d,8a,m,m,m""] |=== | |TaskPath |varchar(8000) |NULL | |=== .Referenced Columns -- * xref:ssis_t.tblcontrolflow.adoc#column-taskpath[+ssis_t.TblControlFlow.TaskPath+] -- .Referencing Columns -- * xref:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc#column-taskpath[+ssis.PackageTask_Dft_Component_output_outputcolumn_tgt.TaskPath+] -- // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] |1 |*<>* |varchar(50) |NOT NULL | |2 |*<>* |varchar(200) |NULL | |3 |*<>* |varchar(max) |NULL | // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] | |<> |varchar(100) |NULL | | |<> |varchar(100) |NULL | | |<> |varchar(100) |NULL | | |<> |varchar(max) |NULL | | |<> |int |NULL | | |<> |varchar(max) |NULL | | |<> |varchar(max) |NULL | | |<> |int |NULL | | |<> |int |NULL | | |<> |varchar(max) |NULL | | |<> |varchar(max) |NULL | | |<> |int |NOT NULL | | |<> |bit |NULL | | |<> |varchar(500) |NULL | | |<> |varchar(max) |NULL | | |<> |varchar(8000) |NULL | // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] [#index-pkunderlinepackagetaskunderlinedftunderlinecomponentunderlineoutputunderlineoutputcolumnunderlinesrc] === PK_PackageTask_Dft_Component_output_outputcolumn_src * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; varchar(50) * <>; varchar(200) * <>; varchar(max) -- * PK, Unique, Real: 1, 1, 0 [#index-idxunderlinepackagetaskunderlinedftunderlinecomponentunderlineoutputunderlineoutputcolumnunderlinesrcunderlineunderline2] === idx_PackageTask_Dft_Component_output_outputcolumn_src++__++2 * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; varchar(50) * <>; varchar(200) -- * PK, Unique, Real: 0, 0, 0 [#index-idxunderlinepackagetaskunderlinedftunderlinecomponentunderlineoutputunderlineoutputcolumnunderlinesrcunderlineunderline3] === idx_PackageTask_Dft_Component_output_outputcolumn_src++__++3 * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; varchar(50) -- * PK, Unique, Real: 0, 0, 0 // end::AntoraIndexList[] == AntoraMeasureDetails // tag::AntoraMeasureDetails[] // end::AntoraMeasureDetails[] == AntoraMeasureDescriptions == AntoraParameterList // tag::AntoraParameterList[] // end::AntoraParameterList[] == AntoraXrefCulturesList // tag::AntoraXrefCulturesList[] * xref:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_src.adoc[] - // end::AntoraXrefCulturesList[] == cultures_count // tag::cultures_count[] 1 // end::cultures_count[] == Other tags source: property.RepoObjectProperty_cross As rop_cross === additional_reference_csv // tag::additional_reference_csv[] // end::additional_reference_csv[] === AdocUspSteps // tag::adocuspsteps[] // end::adocuspsteps[] === AntoraReferencedList // tag::antorareferencedlist[] * xref:dhw:sqldb:ssis.package_src.adoc[] * xref:dhw:sqldb:ssis_t.tblcontrolflow.adoc[] * xref:dhw:sqldb:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc[] * xref:dhw:sqldb:ssis.usp_persist_packagetask_dft_component_output_outputcolumn_tgt.adoc[] // end::antorareferencinglist[] === Description // tag::description[] // end::description[] === exampleUsage // tag::exampleusage[] // end::exampleusage[] === exampleUsage_2 // tag::exampleusage_2[] // end::exampleusage_2[] === exampleUsage_3 // tag::exampleusage_3[] // end::exampleusage_3[] === exampleUsage_4 // tag::exampleusage_4[] // end::exampleusage_4[] === exampleUsage_5 // tag::exampleusage_5[] // end::exampleusage_5[] === exampleWrong_Usage // tag::examplewrong_usage[] // end::examplewrong_usage[] === has_execution_plan_issue // tag::has_execution_plan_issue[] // end::has_execution_plan_issue[] === has_get_referenced_issue // tag::has_get_referenced_issue[] // end::has_get_referenced_issue[] === has_history // tag::has_history[] // end::has_history[] === has_history_columns // tag::has_history_columns[] // end::has_history_columns[] === InheritanceType // tag::inheritancetype[] // end::inheritancetype[] === is_persistence // tag::is_persistence[] // end::is_persistence[] === is_persistence_check_duplicate_per_pk // tag::is_persistence_check_duplicate_per_pk[] // end::is_persistence_check_duplicate_per_pk[] === is_persistence_check_for_empty_source // tag::is_persistence_check_for_empty_source[] // end::is_persistence_check_for_empty_source[] === is_persistence_delete_changed // tag::is_persistence_delete_changed[] // end::is_persistence_delete_changed[] === is_persistence_delete_missing // tag::is_persistence_delete_missing[] // end::is_persistence_delete_missing[] === is_persistence_insert // tag::is_persistence_insert[] // end::is_persistence_insert[] === is_persistence_truncate // tag::is_persistence_truncate[] // end::is_persistence_truncate[] === is_persistence_update_changed // tag::is_persistence_update_changed[] // end::is_persistence_update_changed[] === is_repo_managed // tag::is_repo_managed[] 0 // end::is_repo_managed[] === is_ssas // tag::is_ssas[] 0 // end::is_ssas[] === microsoft_database_tools_support // tag::microsoft_database_tools_support[] // end::microsoft_database_tools_support[] === MS_Description // tag::ms_description[] // end::ms_description[] === persistence_source_RepoObject_fullname // tag::persistence_source_repoobject_fullname[] // end::persistence_source_repoobject_fullname[] === persistence_source_RepoObject_fullname2 // tag::persistence_source_repoobject_fullname2[] // end::persistence_source_repoobject_fullname2[] === persistence_source_RepoObject_guid // tag::persistence_source_repoobject_guid[] // end::persistence_source_repoobject_guid[] === persistence_source_RepoObject_xref // tag::persistence_source_repoobject_xref[] // end::persistence_source_repoobject_xref[] === pk_index_guid // tag::pk_index_guid[] EBC1C789-D13F-EC11-852D-A81E8446D5B0 // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] varchar(50),varchar(200),varchar(max) // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] AntoraModule,PackageName,Column_refId // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] * [ssis].[Package_src] * [ssis_t].[TblControlFlow] * [ssis_t].[TblTask_Dft_Component_outputs_outputColumn_src] // end::referencedobjectlist[] === usp_persistence_RepoObject_guid // tag::usp_persistence_repoobject_guid[] // end::usp_persistence_repoobject_guid[] === UspExamples // tag::uspexamples[] // end::uspexamples[] === uspgenerator_usp_id // tag::uspgenerator_usp_id[] // end::uspgenerator_usp_id[] === UspParameters // tag::uspparameters[] // end::uspparameters[] == Boolean Attributes source: property.RepoObjectProperty WHERE property_int = 1 // tag::boolean_attributes[] // end::boolean_attributes[] == PlantUML diagrams === PlantUML Entity // tag::puml_entity[] [plantuml, entity-{docname}, svg, subs=macros] .... 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_src.adoc[]"" as ssis.PackageTask_Dft_Component_output_outputcolumn_src << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) **Column_refId** : (varchar(max)) Column_dataType : (varchar(100)) Column_errorOrTruncationOperation : (varchar(100)) Column_errorRowDisposition : (varchar(100)) Column_externalMetadataColumnId : (varchar(max)) Column_length : (int) Column_lineageId : (varchar(max)) Column_name : (varchar(max)) Column_precision : (int) Column_scale : (int) Column_truncationRowDisposition : (varchar(max)) Component_refId : (varchar(max)) - ControlFlowDetailsRowID : (int) output_isErrorOut : (bit) output_name : (varchar(500)) output_refId : (varchar(max)) TaskPath : (varchar(8000)) -- } .... // end::puml_entity[] === PlantUML Entity 1 1 FK // tag::puml_entity_1_1_fk[] [plantuml, entity_1_1_fk-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_src.adoc[]"" as ssis.PackageTask_Dft_Component_output_outputcolumn_src << V >> { - **PK_PackageTask_Dft_Component_output_outputcolumn_src** .. AntoraModule; varchar(50) PackageName; varchar(200) Column_refId; varchar(max) -- - idx_PackageTask_Dft_Component_output_outputcolumn_src__2 .. AntoraModule; varchar(50) PackageName; varchar(200) -- - idx_PackageTask_Dft_Component_output_outputcolumn_src__3 .. AntoraModule; varchar(50) } footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_fk[] === PlantUML 1 1 ObjectRef // tag::puml_entity_1_1_objectref[] [plantuml, entity_1_1_objectref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:ssis.package_src.adoc[]"" as ssis.Package_src << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) -- } entity ""puml-link:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_src.adoc[]"" as ssis.PackageTask_Dft_Component_output_outputcolumn_src << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) **Column_refId** : (varchar(max)) -- } entity ""puml-link:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc[]"" as ssis.PackageTask_Dft_Component_output_outputColumn_tgt << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) **Column_refId** : (varchar(max)) -- } entity ""puml-link:dhw:sqldb:ssis.usp_persist_packagetask_dft_component_output_outputcolumn_tgt.adoc[]"" as ssis.usp_PERSIST_PackageTask_Dft_Component_output_outputColumn_tgt << P >> { -- } entity ""puml-link:dhw:sqldb:ssis_t.tblcontrolflow.adoc[]"" as ssis_t.TblControlFlow << U >> { - **ControlFlowDetailsRowID** : (int) -- } entity ""puml-link:dhw:sqldb:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc[]"" as ssis_t.TblTask_Dft_Component_outputs_outputColumn_src << V >> { -- } ssis.Package_src <.. ssis.PackageTask_Dft_Component_output_outputcolumn_src ssis.PackageTask_Dft_Component_output_outputcolumn_src <.. ssis.PackageTask_Dft_Component_output_outputcolumn_tgt ssis.PackageTask_Dft_Component_output_outputcolumn_src <.. ssis.usp_PERSIST_PackageTask_Dft_Component_output_outputColumn_tgt ssis_t.TblControlFlow <.. ssis.PackageTask_Dft_Component_output_outputcolumn_src ssis_t.TblTask_Dft_Component_outputs_outputColumn_src <.. ssis.PackageTask_Dft_Component_output_outputcolumn_src footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_objectref[] === PlantUML 30 0 ObjectRef // tag::puml_entity_30_0_objectref[] [plantuml, entity_30_0_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:ssis.package_src.adoc[]"" as ssis.Package_src << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) -- } entity ""puml-link:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_src.adoc[]"" as ssis.PackageTask_Dft_Component_output_outputcolumn_src << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) **Column_refId** : (varchar(max)) -- } entity ""puml-link:dhw:sqldb:ssis.project.adoc[]"" as ssis.Project << U >> { - **AntoraModule** : (varchar(50)) -- } entity ""puml-link:dhw:sqldb:ssis_t.pkgstats.adoc[]"" as ssis_t.pkgStats << U >> { - **RowID** : (int) -- } entity ""puml-link:dhw:sqldb:ssis_t.tblcontrolflow.adoc[]"" as ssis_t.TblControlFlow << U >> { - **ControlFlowDetailsRowID** : (int) -- } entity ""puml-link:dhw:sqldb:ssis_t.tbltask_dft_component.adoc[]"" as ssis_t.TblTask_Dft_Component << U >> { - **DftComponentId** : (int) -- } entity ""puml-link:dhw:sqldb:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc[]"" as ssis_t.TblTask_Dft_Component_outputs_outputColumn_src << V >> { -- } ssis.Package_src <.. ssis.PackageTask_Dft_Component_output_outputcolumn_src ssis.Project <.. ssis.Package_src ssis_t.pkgStats <.. ssis.Package_src ssis_t.TblControlFlow <.. ssis.PackageTask_Dft_Component_output_outputcolumn_src ssis_t.TblTask_Dft_Component <.. ssis_t.TblTask_Dft_Component_outputs_outputColumn_src ssis_t.TblTask_Dft_Component_outputs_outputColumn_src <.. ssis.PackageTask_Dft_Component_output_outputcolumn_src footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_30_0_objectref[] === PlantUML 0 30 ObjectRef // tag::puml_entity_0_30_objectref[] [plantuml, entity_0_30_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:docs.ssis_adoc.adoc[]"" as docs.ssis_Adoc << V >> { - **AntoraModule** : (varchar(50)) **PackageBasename** : (varchar(8000)) -- } entity ""puml-link:dhw:sqldb:docs.ssis_adoc_t.adoc[]"" as docs.ssis_Adoc_T << U >> { - **AntoraModule** : (varchar(50)) **PackageBasename** : (varchar(8000)) -- } entity ""puml-link:dhw:sqldb:docs.ssis_dfttaskcomponentlist.adoc[]"" as docs.ssis_DftTaskComponentList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.ssis_dfttaskcomponentoutputcolumnlist.adoc[]"" as docs.ssis_DftTaskComponentOutputColumnList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.ssis_dfttaskcomponentoutputlist.adoc[]"" as docs.ssis_DftTaskComponentOutputList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.ssis_task.adoc[]"" as docs.ssis_Task << V >> { -- } entity ""puml-link:dhw:sqldb:docs.ssis_tasklist.adoc[]"" as docs.ssis_TaskList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport.adoc[]"" as docs.usp_AntoraExport << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport_ssispartialscontent.adoc[]"" as docs.usp_AntoraExport_SsisPartialsContent << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_ssis_adoc_t.adoc[]"" as docs.usp_PERSIST_ssis_Adoc_T << P >> { -- } entity ""puml-link:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn.adoc[]"" as ssis.PackageTask_Dft_Component_output_outputcolumn << U >> { -- } entity ""puml-link:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_src.adoc[]"" as ssis.PackageTask_Dft_Component_output_outputcolumn_src << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) **Column_refId** : (varchar(max)) -- } entity ""puml-link:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc[]"" as ssis.PackageTask_Dft_Component_output_outputColumn_tgt << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) **Column_refId** : (varchar(max)) -- } entity ""puml-link:dhw:sqldb:ssis.usp_import.adoc[]"" as ssis.usp_import << P >> { -- } entity ""puml-link:dhw:sqldb:ssis.usp_persist_packagetask_dft_component_output_outputcolumn_tgt.adoc[]"" as ssis.usp_PERSIST_PackageTask_Dft_Component_output_outputColumn_tgt << P >> { -- } docs.ssis_Adoc <.. docs.usp_PERSIST_ssis_Adoc_T docs.ssis_Adoc <.. docs.ssis_Adoc_T docs.ssis_Adoc_T <.. docs.usp_PERSIST_ssis_Adoc_T docs.ssis_Adoc_T <.. docs.usp_AntoraExport_SsisPartialsContent docs.ssis_DftTaskComponentList <.. docs.ssis_Task docs.ssis_DftTaskComponentList <.. docs.ssis_TaskList docs.ssis_DftTaskComponentOutputColumnList <.. docs.ssis_DftTaskComponentOutputList docs.ssis_DftTaskComponentOutputList <.. docs.ssis_DftTaskComponentList docs.ssis_TaskList <.. docs.ssis_Adoc docs.usp_AntoraExport_SsisPartialsContent <.. docs.usp_AntoraExport docs.usp_PERSIST_ssis_Adoc_T <.. docs.usp_AntoraExport_SsisPartialsContent ssis.PackageTask_Dft_Component_output_outputcolumn <.. docs.ssis_DftTaskComponentOutputColumnList ssis.PackageTask_Dft_Component_output_outputcolumn_src <.. ssis.PackageTask_Dft_Component_output_outputcolumn_tgt ssis.PackageTask_Dft_Component_output_outputcolumn_src <.. ssis.usp_PERSIST_PackageTask_Dft_Component_output_outputColumn_tgt ssis.PackageTask_Dft_Component_output_outputColumn_tgt <.. ssis.usp_PERSIST_PackageTask_Dft_Component_output_outputColumn_tgt ssis.PackageTask_Dft_Component_output_outputcolumn_tgt <.. ssis.PackageTask_Dft_Component_output_outputcolumn ssis.usp_PERSIST_PackageTask_Dft_Component_output_outputColumn_tgt <.. ssis.usp_import footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_0_30_objectref[] === PlantUML 1 1 ColumnRef // tag::puml_entity_1_1_colref[] [plantuml, entity_1_1_colref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:ssis.package_src.adoc[]"" as ssis.Package_src << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) PackageCreationDate : (datetime) PackageCreatorComputerName : (nvarchar(500)) PackageCreatorName : (varchar(1000)) PackageDescription : (nvarchar(max)) PackageDTSID : (uniqueidentifier) PackageLastModifiedProductVersion : (nvarchar(500)) PackageLocaleID : (int) PackageObjectName : (nvarchar(500)) - PackagePath : (varchar(8000)) PackageProtectionLevel : (varchar(100)) PackageProtectionLevelName : (varchar(28)) PackageVersionGUID : (uniqueidentifier) - ProjectPath : (varchar(8000)) - RowID : (int) -- } entity ""puml-link:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_src.adoc[]"" as ssis.PackageTask_Dft_Component_output_outputcolumn_src << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) **Column_refId** : (varchar(max)) Column_dataType : (varchar(100)) Column_errorOrTruncationOperation : (varchar(100)) Column_errorRowDisposition : (varchar(100)) Column_externalMetadataColumnId : (varchar(max)) Column_length : (int) Column_lineageId : (varchar(max)) Column_name : (varchar(max)) Column_precision : (int) Column_scale : (int) Column_truncationRowDisposition : (varchar(max)) Component_refId : (varchar(max)) - ControlFlowDetailsRowID : (int) output_isErrorOut : (bit) output_name : (varchar(500)) output_refId : (varchar(max)) TaskPath : (varchar(8000)) -- } entity ""puml-link:dhw:sqldb:ssis.packagetask_dft_component_output_outputcolumn_tgt.adoc[]"" as ssis.PackageTask_Dft_Component_output_outputColumn_tgt << V >> { - **AntoraModule** : (varchar(50)) **PackageName** : (varchar(200)) **Column_refId** : (varchar(max)) Column_dataType : (varchar(100)) Column_errorOrTruncationOperation : (varchar(100)) Column_errorRowDisposition : (varchar(100)) Column_externalMetadataColumnId : (varchar(max)) Column_length : (int) Column_lineageId : (varchar(max)) Column_name : (varchar(max)) Column_precision : (int) Column_scale : (int) Column_truncationRowDisposition : (varchar(max)) Component_refId : (varchar(max)) - ControlFlowDetailsRowID : (int) output_isErrorOut : (bit) output_name : (varchar(500)) output_refId : (varchar(max)) TaskPath : (varchar(8000)) -- } entity ""puml-link:dhw:sqldb:ssis.usp_persist_packagetask_dft_component_output_outputcolumn_tgt.adoc[]"" as ssis.usp_PERSIST_PackageTask_Dft_Component_output_outputColumn_tgt << P >> { -- } entity ""puml-link:dhw:sqldb:ssis_t.tblcontrolflow.adoc[]"" as ssis_t.TblControlFlow << U >> { - **ControlFlowDetailsRowID** : (int) DelayValidationPropertyValue : (varchar(100)) DFTQuery : (xml) ExecPkgTaskQry : (xml) ExpressionValue : (varchar(5000)) IsDisabled : (varchar(10)) RowID : (int) ScriptTaskQry : (xml) SqlTaskQry : (xml) TaskDescription : (varchar(max)) TaskName : (varchar(2000)) TaskPath : (varchar(8000)) TaskType : (varchar(5000)) -- } entity ""puml-link:dhw:sqldb:ssis_t.tbltask_dft_component_outputs_outputcolumn_src.adoc[]"" as ssis_t.TblTask_Dft_Component_outputs_outputColumn_src << V >> { Column_dataType : (varchar(100)) Column_errorOrTruncationOperation : (varchar(100)) Column_errorRowDisposition : (varchar(100)) Column_externalMetadataColumnId : (varchar(max)) Column_length : (int) Column_lineageId : (varchar(max)) Column_name : (varchar(max)) Column_precision : (int) Column_refId : (varchar(max)) Column_scale : (int) Column_truncationRowDisposition : (varchar(max)) columnscontent : (xml) - ControlFlowDetailsRowID : (int) - DftComponentId : (int) nodescontent : (xml) output_isErrorOut : (bit) output_name : (varchar(500)) output_refId : (varchar(max)) refId : (varchar(max)) RowID : (int) -- } ssis.Package_src <.. ssis.PackageTask_Dft_Component_output_outputcolumn_src ssis.PackageTask_Dft_Component_output_outputcolumn_src <.. ssis.PackageTask_Dft_Component_output_outputcolumn_tgt ssis.PackageTask_Dft_Component_output_outputcolumn_src <.. ssis.usp_PERSIST_PackageTask_Dft_Component_output_outputColumn_tgt ssis_t.TblControlFlow <.. ssis.PackageTask_Dft_Component_output_outputcolumn_src ssis_t.TblTask_Dft_Component_outputs_outputColumn_src <.. ssis.PackageTask_Dft_Component_output_outputcolumn_src ""ssis.Package_src::AntoraModule"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::AntoraModule"" ""ssis.Package_src::PackageName"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::PackageName"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::AntoraModule"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::AntoraModule"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_dataType"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_dataType"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_errorOrTruncationOperation"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_errorOrTruncationOperation"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_errorRowDisposition"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_errorRowDisposition"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_externalMetadataColumnId"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_externalMetadataColumnId"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_length"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_length"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_lineageId"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_lineageId"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_name"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_name"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_precision"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_precision"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_refId"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_refId"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_scale"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_scale"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_truncationRowDisposition"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Column_truncationRowDisposition"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Component_refId"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::Component_refId"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::ControlFlowDetailsRowID"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::ControlFlowDetailsRowID"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::output_isErrorOut"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::output_isErrorOut"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::output_name"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::output_name"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::output_refId"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::output_refId"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::PackageName"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::PackageName"" ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::TaskPath"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_tgt::TaskPath"" ""ssis_t.TblControlFlow::TaskPath"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::TaskPath"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_dataType"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_dataType"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_errorOrTruncationOperation"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_errorOrTruncationOperation"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_errorRowDisposition"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_errorRowDisposition"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_externalMetadataColumnId"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_externalMetadataColumnId"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_length"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_length"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_lineageId"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_lineageId"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_name"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_name"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_precision"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_precision"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_refId"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_refId"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_scale"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_scale"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::Column_truncationRowDisposition"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Column_truncationRowDisposition"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::ControlFlowDetailsRowID"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::ControlFlowDetailsRowID"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::output_isErrorOut"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::output_isErrorOut"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::output_name"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::output_name"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::output_refId"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::output_refId"" ""ssis_t.TblTask_Dft_Component_outputs_outputColumn_src::refId"" <-- ""ssis.PackageTask_Dft_Component_output_outputcolumn_src::Component_refId"" footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_colref[] == sql_modules_definition // tag::sql_modules_definition[] [%collapsible] ======= [source,sql,numbered,indent=0] ---- CREATE View [ssis].[PackageTask_Dft_Component_output_outputColumn_src] As Select p.AntoraModule , p.PackageName , Component_refId = T3.refId , T3.output_refId , T3.output_name , T3.output_isErrorOut , T3.Column_refId , T3.Column_name , T3.Column_dataType , T3.Column_length , T3.Column_precision , T3.Column_scale , T3.Column_errorOrTruncationOperation , T3.Column_errorRowDisposition , T3.Column_externalMetadataColumnId , T3.Column_lineageId , T3.Column_truncationRowDisposition , T2.TaskPath , T3.ControlFlowDetailsRowID From ssis.Package_src As p Inner Join ssis_t.TblControlFlow As T2 On p.RowID = T2.RowID Inner Join ssis_t.TblTask_Dft_Component_outputs_outputColumn_src As T3 On T3.ControlFlowDetailsRowID = T2.ControlFlowDetailsRowID ---- ======= // end::sql_modules_definition[] ",12141,False,2399.3186557248205,median "////////////////////////////////////////// Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ////////////////////////////////////////// = Object orientation :jls: https://docs.oracle.com/javase/specs/jls/se14/html/ :javabeans: https://download.oracle.com/otndocs/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/ This chapter covers the object orientation of the Groovy programming language. == Types === Primitive types Groovy supports the same primitive types as those defined by the {jls}[Java Language Specification]: * integral types: `byte` (8 bit), `short` (16 bit), `int` (32 bit) and `long` (64 bit) * floating-point types: `float` (32 bit) and `double` (64 bit) * `boolean` type (exactly `true` or `false`) * `char` type (16 bit, usable as a numeric type, representing an UTF-16 code) While Groovy declares and stores primitive fields and variables as primitives, because it uses Objects for everything, it autowraps references to primitives. Just like Java, the wrappers it uses are [cols=""1,1"" options=""header""] .primitive wrappers |==== | Primitive type | Wrapper class | boolean | Boolean | char | Character | short | Short | int | Integer | long | Long | float | Float | double | Double |==== Here's an example using `int` [source,groovy] ---- include::../test/PrimitiveTest.groovy[tags=primitive_references,indent=0] ---- Now you may be concerned that this means every time you use a mathematical operator on a reference to a primitive that you'll incur the cost of unboxing and reboxing the primitive. But this is not the case, as Groovy will compile your operators into their link:core-operators.html#_operator-overloading[method equivalents] and uses those instead. Additionally, Groovy will automatically unbox to a primitive when calling a Java method that takes a primitive parameter and automatically box primitive method return values from Java. However, be aware there are some link:core-differences-java.html#_primitives_and_wrappers[differences] from Java's method resolution. === Class Groovy classes are very similar to Java classes, and are compatible with Java ones at JVM level. They may have methods, fields and properties (think JavaBeans properties but with less boilerplate). Classes and class members can have the same modifiers (public, protected, private, static, etc) as in Java with some minor differences at the source level which are explained shortly. The key differences between Groovy classes and their Java counterparts are: * Classes or methods with no visibility modifier are automatically public (a special annotation can be used to achieve package private visibility). * Fields with no visibility modifier are turned into properties automatically, which results in less verbose code, since explicit getter and setter methods aren't needed. More on this aspect will be covered in the <>. * Classes do not need to have the same base name as their source file definitions but it is highly recommended in most scenarios (see also the next point about scripts). * One source file may contain one or more classes (but if a file contains any code not in a class, it is considered a script). Scripts are just classes with some special conventions and will have the same name as their source file (so don't include a class definition within a script having the same name as the script source file). The following code presents an example class. [source,groovy] ---- include::../test/ClassTest.groovy[tags=class_definition,indent=0] ---- <1> class beginning, with the name `Person` <2> string field and property named `name` <3> method definition ==== Normal class Normal classes refer to classes which are top level and concrete. This means they can be instantiated without restrictions from any other classes or scripts. This way, they can only be public (even though the `public` keyword may be suppressed). Classes are instantiated by calling their constructors, using the `new` keyword, as in the following snippet. [source,groovy] ---- include::../test/ClassTest.groovy[tags=class_instantiation,indent=0] ---- ==== Inner class Inner classes are defined within another classes. The enclosing class can use the inner class as usual. On the other side, a inner class can access members of its enclosing class, even if they are private. Classes other than the enclosing class are not allowed to access inner classes. Here is an example: [source,groovy] ---- include::../test/ClassTest.groovy[tags=inner_class,indent=0] ---- <1> the inner class is instantiated and its method gets called <2> inner class definition, inside its enclosing class <3> even being private, a field of the enclosing class is accessed by the inner class There are some reasons for using inner classes: * They increase encapsulation by hiding the inner class from other classes, which do not need to know about it. This also leads to cleaner packages and workspaces. * They provide a good organization, by grouping classes that are used by only one class. * They lead to more maintainable codes, since inner classes are near the classes that use them. It is common for an inner class to be an implementation of some interface whose method(s) are needed by the outer class. The code below illustrates this typical usage pattern, here being used with threads. [source,groovy] ---- include::../test/ClassTest.groovy[tags=inner_class2,indent=0] ---- Note that the class `Inner2` is defined only to provide an implementation of the method `run` to class `Outer2`. Anonymous inner classes help to eliminate verbosity in this case. That topic is covered shortly. Groovy 3+ also supports Java syntax for non-static inner class instantiation, for example: [source,groovy] -------------------------------------- include::../test/ClassTest.groovy[tags=inner_instantiation,indent=0] -------------------------------------- ===== Anonymous inner class The earlier example of an inner class (`Inner2`) can be simplified with an anonymous inner class. The same functionality can be achieved with the following code: [source,groovy] ---- include::../test/ClassTest.groovy[tags=anonymous_inner_class,indent=0] ---- <1> comparing with the last example of previous section, the `new Inner2()` was replaced by `new Runnable()` along with all its implementation <2> the method `start` is invoked normally Thus, there was no need to define a new class to be used just once. ==== Abstract class Abstract classes represent generic concepts, thus, they cannot be instantiated, being created to be subclassed. Their members include fields/properties and abstract or concrete methods. Abstract methods do not have implementation, and must be implemented by concrete subclasses. [source,groovy] ---- include::../test/ClassTest.groovy[tags=abstract_class,indent=0] ---- <1> abstract classes must be declared with `abstract` keyword <2> abstract methods must also be declared with `abstract` keyword Abstract classes are commonly compared to interfaces. There are at least two important differences of choosing one or another. First, while abstract classes may contain fields/properties and concrete methods, interfaces may contain only abstract methods (method signatures). Moreover, one class can implement several interfaces, whereas it can extend just one class, abstract or not. === Inheritance Inheritance in Groovy resembles inheritance in Java. It provides a mechanism for a child class (or subclass) to reuse code or properties from a parent (or super class). Classes related through inheritance form an inheritance hierarchy. Common behavior and members are pushed up the hierarchy to reduce duplication. Specializations occur in child classes. Different forms of inheritance are supported: * _implementation_ inheritance where code (methods, fields or properties) from a <> or from one or more <<_traits,traits>> is reused by a child class * _contract_ inheritance where a class promises to provide particular abstract methods defined in a <>, or defined in one or more <<_traits,traits>> or <<_interface,interfaces>>. === Interface An interface defines a contract that a class needs to conform to. An interface only defines a list of methods that need to be implemented, but does not define the method's implementation. [source,groovy] ---- include::../test/ClassTest.groovy[tags=interface_def_1,indent=0] ---- <1> an interface needs to be declared using the `interface` keyword <2> an interface only defines method signatures Methods of an interface are always *public*. It is an error to use `protected` or `private` methods in interfaces: [source,groovy] ---- include::../test/ClassTest.groovy[tags=protected_forbidden,indent=0] ---- <1> Using `protected` is a compile-time error A class _implements_ an interface if it defines the interface in its `implements` list or if any of its superclasses does: [source,groovy] ---- include::../test/ClassTest.groovy[tags=class_implements,indent=0] ---- <1> The `SystemGreeter` declares the `Greeter` interface using the `implements` keyword <2> Then implements the required `greet` method <3> Any instance of `SystemGreeter` is also an instance of the `Greeter` interface An interface can extend another interface: [source,groovy] ---- include::../test/ClassTest.groovy[tags=extended_interface,indent=0] ---- <1> the `ExtendedGreeter` interface extends the `Greeter` interface using the `extends` keyword It is worth noting that for a class to be an instance of an interface, it has to be explicit. For example, the following class defines the `greet` method as it is declared in the `Greeter` interface, but does not declare `Greeter` in its interfaces: [source,groovy] ---- include::../test/ClassTest.groovy[tags=no_structural_interface,indent=0] ---- In other words, Groovy does not define structural typing. It is however possible to make an instance of an object implement an interface at runtime, using the `as` coercion operator: [source,groovy] ---- include::../test/ClassTest.groovy[tags=interface_coercion,indent=0] ---- <1> create an instance of `DefaultGreeter` that does not implement the interface <2> coerce the instance into a `Greeter` at runtime <3> the coerced instance implements the `Greeter` interface You can see that there are two distinct objects: one is the source object, a `DefaultGreeter` instance, which does not implement the interface. The other is an instance of `Greeter` that delegates to the coerced object. TIP: Groovy interfaces do not support default implementation like Java 8 interfaces. If you are looking for something similar (but not equal), <<_traits,traits>> are close to interfaces, but allow default implementation as well as other important features described in this manual. [[superclass]] === Superclass Parent classes share visible fields, properties or methods with child classes. A child class may have at most one parent class. The `extends` keyword is used immediately prior to giving the superclass type. === Constructors Constructors are special methods used to initialize an object with a specific state. As with normal methods, it is possible for a class to declare more than one constructor, so long as each constructor has a unique type signature. If an object doesn't require any parameters during construction, it may use a _no-arg_ constructor. If no constructors are supplied, an empty no-arg constructor will be provided by the Groovy compiler. Groovy supports two invocation styles: * _positional parameters_ are used in a similar to how you would use Java constructors * _named parameters_ allow you to specify parameter names when invoking the constructor. ==== Positional parameters To create an object by using positional parameters, the respective class needs to declare one or more constructors. In the case of multiple constructors, each must have a unique type signature. The constructors can also added to the class using the gapi:groovy.transform.TupleConstructor[] annotation. Typically, once at least one constructor is declared, the class can only be instantiated by having one of its constructors called. It is worth noting that, in this case, you can't normally create the class with named parameters. Groovy does support named parameters so long as the class contains a no-arg constructor or provides a constructor which takes a `Map` argument as the first (and potentially only) argument - see the next section for details. There are three forms of using a declared constructor. The first one is the normal Java way, with the `new` keyword. The others rely on coercion of lists into the desired types. In this case, it is possible to coerce with the `as` keyword and by statically typing the variable. [source,groovy] ---- include::../test/ClassTest.groovy[tags=constructor_positional_parameters,indent=0] ---- <1> Constructor declaration <2> Constructor invocation, classic Java way <3> Constructor usage, using coercion with `as` keyword <4> Constructor usage, using coercion in assignment ==== Named parameters If no (or a no-arg) constructor is declared, it is possible to create objects by passing parameters in the form of a map (property/value pairs). This can be in handy in cases where one wants to allow several combinations of parameters. Otherwise, by using traditional positional parameters it would be necessary to declare all possible constructors. Having a constructor where the first (and perhaps only) argument is a `Map` argument is also supported - such a constructor may also be added using the gapi:groovy.transform.MapConstructor[] annotation. [source,groovy] ---- include::../test/ClassTest.groovy[tags=constructor_named_parameters,indent=0] ---- <1> No constructor declared <2> No parameters given in the instantiation <3> `name` parameter given in the instantiation <4> `age` parameter given in the instantiation <5> `name` and `age` parameters given in the instantiation It is important to highlight, however, that this approach gives more power to the constructor caller, while imposing an increased responsibility on the caller to get the names and value types correct. Thus, if greater control is desired, declaring constructors using positional parameters might be preferred. Notes: * While the example above supplied no constructor, you can also supply a no-arg constructor or a constructor where the first argument is a `Map`, most typically it's the only argument. * When no (or a no-arg) constructor is declared, Groovy replaces the named constructor call by a call to the no-arg constructor followed by calls to the setter for each supplied named property. * When the first argument is a Map, Groovy combines all named parameters into a Map (regardless of ordering) and supplies the map as the first parameter. This can be a good approach if your properties are declared as `final` (since they will be set in the constructor rather than after the fact with setters). * You can support both named and positional construction by supply both positional constructors as well as a no-arg or Map constructor. * You can support hybrid construction by having a constructor where the first argument is a Map but there are also additional positional parameters. Use this style with caution. === Methods Groovy methods are quite similar to other languages. Some peculiarities will be shown in the next subsections. ==== Method definition A method is defined with a return type or with the `def` keyword, to make the return type untyped. A method can also receive any number of arguments, which may not have their types explicitly declared. Java modifiers can be used normally, and if no visibility modifier is provided, the method is public. Methods in Groovy always return some value. If no `return` statement is provided, the value evaluated in the last line executed will be returned. For instance, note that none of the following methods uses the `return` keyword. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=method_definition ,indent=0] ---- <1> Method with no return type declared and no parameter <2> Method with explicit return type and no parameter <3> Method with a parameter with no type defined <4> Static method with a String parameter ==== Named parameters Like constructors, normal methods can also be called with named parameters. To support this notation, a convention is used where the first argument to the method is a `Map`. In the method body, the parameter values can be accessed as in normal maps (`map.key`). If the method has just a single Map argument, all supplied parameters must be named. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=named_arguments ,indent=0] ---- ===== Mixing named and positional parameters Named parameters can be mixed with positional parameters. The same convention applies, in this case, in addition to the `Map` argument as the first argument, the method in question will have additional positional arguments as needed. Supplied positional parameters when calling the method must be in order. The named parameters can be in any position. They are grouped into the map and supplied as the first parameter automatically. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=named_arguments_with_additional_arguments ,indent=0] ---- <1> Method call with additional `number` argument of `Integer` type <2> Method call with changed order of arguments If we don't have the Map as the first argument, then a Map must be supplied for that argument instead of named parameters. Failure to do so will lead to `groovy.lang.MissingMethodException`: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=failed_named_arguments_with_additional_arguments ,indent=0] ---- <1> Method call throws `groovy.lang.MissingMethodException: No signature of method: foo() is applicable for argument types: (LinkedHashMap, Integer) values: [[name:Marie, age:1], 23]`, because the named argument `Map` parameter is not defined as the first argument Above exception can be avoided if we replace named arguments with an explicit `Map` argument: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=explicit_named_arguments_with_additional_arguments ,indent=0] ---- <1> Explicit `Map` argument in place of named arguments makes invocation valid TIP: Although Groovy allows you to mix named and positional parameters, it can lead to unnecessary confusion. Mix named and positional arguments with caution. ==== Default arguments Default arguments make parameters optional. If the argument is not supplied, the method assumes a default value. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=default_arguments,indent=0] ---- Parameters are dropped from the right, however mandatory parameters are never dropped. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=default_arguments2,indent=0] ---- The same rule applies to constructors as well as methods. If using `@TupleConstructor`, additional configuration options apply. ==== Varargs Groovy supports methods with a variable number of arguments. They are defined like this: `def foo(p1, ..., pn, T... args)`. Here `foo` supports `n` arguments by default, but also an unspecified number of further arguments exceeding `n`. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=varargs_example,indent=0] ---- This example defines a method `foo`, that can take any number of arguments, including no arguments at all. `args.length` will return the number of arguments given. Groovy allows `T[]` as an alternative notation to `T...`. That means any method with an array as last parameter is seen by Groovy as a method that can take a variable number of arguments. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=varargs_array_notation,indent=0] ---- If a method with varargs is called with `null` as the vararg parameter, then the argument will be `null` and not an array of length one with `null` as the only element. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=varargs_null_parameter,indent=0] ---- If a varargs method is called with an array as an argument, then the argument will be that array instead of an array of length one containing the given array as the only element. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=varargs_array_parameter,indent=0] ---- Another important point are varargs in combination with method overloading. In case of method overloading Groovy will select the most specific method. For example if a method `foo` takes a varargs argument of type `T` and another method `foo` also takes one argument of type `T`, the second method is preferred. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=varargs_method_overloading,indent=0] ---- ==== Method selection algorithm Dynamic Groovy supports https://en.wikipedia.org/wiki/Multiple_dispatch[multiple dispatch] (aka multimethods). When calling a method, the actual method invoked is determined dynamically based on the run-time type of methods arguments. First the method name and number of arguments will be considered (including allowance for varargs), and then the type of each argument. Consider the following method definitions: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_methods,indent=0] ---- Perhaps as expected, calling `method` with `String` and `Integer` parameters, invokes our third method definition. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=call_single_method,indent=0] ---- Of more interest here is when the types are not known at compile time. Perhaps the arguments are declared to be of type `Object` (a list of such objects in our case). Java would determine that the `method(Object, Object)` variant would be selected in all cases (unless casts were used) but as can be seen in the following example, Groovy uses the runtime type and will invoke each of our methods once (and normally, no casting is needed): [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=call_multi_methods,indent=0] ---- For each of the first two of our three method invocations an exact match of argument types was found. For the third invocation, an exact match of `method(Integer, Integer)` wasn't found but `method(Object, Object)` is still valid and will be selected. Method selection then is about finding the _closest fit_ from valid method candidates which have compatible parameter types. So, `method(Object, Object)` is also valid for the first two invocations but is not as close a match as the variants where types exactly match. To determine the closest fit, the runtime has a notion of the _distance_ an actual argument type is away from the declared parameter type and tries to minimise the total distance across all parameters. The following table illustrates some factors which affect the distance calculation. [cols=""1,1"" options=""header""] |==== | Aspect | Example | Directly implemented interfaces match more closely than ones from further up the inheritance hierarchy. a| Given these interface and method definitions: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_method_distance_interfaces,indent=0] ---- The directly implemented interface will match: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_method_distance_interfaces_usage,indent=0] ---- | An Object array is preferred over an Object. a| [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=object_array_over_object,indent=0] ---- | Non-vararg variants are favored over vararg variants. a| [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=non_varargs_over_vararg,indent=0] ---- | If two vararg variants are applicable, the one which uses the minimum number of vararg arguments is preferred. a| [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=minimal_varargs,indent=0] ---- | Interfaces are preferred over super classes. a| [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_method_distance_interface_over_super,indent=0] ---- | For a primitive argument type, a declared parameter type which is the same or slightly larger is preferred. a| [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=primitive_larger_over_smaller,indent=0] ---- |==== In the case where two variants have exactly the same distance, this is deemed ambiguous and will cause a runtime exception: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_method_ambiguous,indent=0] ---- Casting can be used to select the desired method: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_method_ambiguous_cast,indent=0] ---- ==== Exception declaration Groovy automatically allows you to treat checked exceptions like unchecked exceptions. This means that you don't need to declare any checked exceptions that a method may throw as shown in the following example which can throw a `FileNotFoundException` if the file isn't found: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=idiomatic_method_declaration,indent=0] ---- Nor will you be required to surround the call to the `badRead` method in the previous example within a try/catch block - though you are free to do so if you wish. If you wish to declare any exceptions that your code might throw (checked or otherwise) you are free to do so. Adding exceptions won't change how the code is used from any other Groovy code but can be seen as documentation for the human reader of your code. The exceptions will become part of the method declaration in the bytecode, so if your code might be called from Java, it might be useful to include them. Using an explicit checked exception declaration is illustrated in the following example: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=checked_method_declaration,indent=0] ---- === Fields and Properties [[fields]] ==== Fields A field is a member of a class or a trait which has: * a mandatory _access modifier_ (`public`, `protected`, or `private`) * one or more optional _modifiers_ (`static`, `final`, `synchronized`) * an optional _type_ * a mandatory _name_ [source,groovy] ---- include::../test/ClassTest.groovy[tags=field_declaration,indent=0] ---- <1> a `private` field named `id`, of type `int` <2> a `protected` field named `description`, of type `String` <3> a `public static final` field named _DEBUG_ of type `boolean` A field may be initialized directly at declaration: [source,groovy] ---- include::../test/ClassTest.groovy[tags=field_initialization,indent=0] ---- <1> the private field `id` is initialized with `IDGenerator.next()` It is possible to omit the type declaration of a field. This is however considered a bad practice and in general it is a good idea to use strong typing for fields: [source,groovy] ---- include::../test/ClassTest.groovy[tags=typing_fields,indent=0] ---- <1> the field `mapping` doesn't declare a type <2> the field `mapping` has a strong type The difference between the two is important if you want to use optional type checking later. It is also important as a way to document the class design. However, in some cases like scripting or if you want to rely on duck typing it may be useful to omit the type. [[properties]] ==== Properties A property is an externally visible feature of a class. Rather than just using a public field to represent such features (which provides a more limited abstraction and would restrict refactoring possibilities), the typical approach in Java is to follow the conventions outlined in the {javabeans}[JavaBeans Specification], i.e. represent the property using a combination of a private backing field and getters/setters. Groovy follows these same conventions but provides a simpler way to define the property. You can define a property with: * an *absent* access modifier (no `public`, `protected` or `private`) * one or more optional _modifiers_ (`static`, `final`, `synchronized`) * an optional _type_ * a mandatory _name_ Groovy will then generate the getters/setters appropriately. For example: [source,groovy] ---- include::../test/ClassTest.groovy[tags=properties_definition,indent=0] ---- <1> creates a backing `private String name` field, a `getName` and a `setName` method <2> creates a backing `private int age` field, a `getAge` and a `setAge` method If a property is declared `final`, no setter is generated: [source,groovy] ---- include::../test/ClassTest.groovy[tags=readonly_property,indent=0] ---- <1> defines a read-only property of type `String` <2> defines a read-only property of type `int` <3> assigns the `name` parameter to the `name` field <4> assigns the `age` parameter to the `age` field Properties are accessed by name and will call the getter or setter transparently, unless the code is in the class which defines the property: [source,groovy] ---- include::../test/ClassTest.groovy[tags=property_access,indent=0] ---- <1> `this.name` will directly access the field because the property is accessed from within the class that defines it <2> similarily a read access is done directly on the `name` field <3> write access to the property is done outside of the `Person` class so it will implicitly call `setName` <4> read access to the property is done outside of the `Person` class so it will implicitly call `getName` <5> this will call the `name` method on `Person` which performs a direct access to the field <6> this will call the `title` method on `Person` which performs a direct read access to the field It is worth noting that this behavior of accessing the backing field directly is done in order to prevent a stack overflow when using the property access syntax within a class that defines the property. It is possible to list the properties of a class thanks to the meta `properties` field of an instance: [source,groovy] ---- include::../test/ClassTest.groovy[tags=properties_meta,indent=0] ---- By convention, Groovy will recognize properties even if there is no backing field provided there are getters or setters that follow the Java Beans specification. For example: [source,groovy] ---- include::../test/ClassTest.groovy[tags=pseudo_properties,indent=0] ---- <1> writing `p.name` is allowed because there is a pseudo-property `name` <2> reading `p.age` is allowed because there is a pseudo-readonly property `age` <3> writing `p.groovy` is allowed because there is a pseudo-writeonly property `groovy` This syntactic sugar is at the core of many DSLs written in Groovy. ===== Property naming conventions It is generally recommended that the first two letters of a property name are lowercase and for multi-word properties that camel case is used. In those cases, generated getters and setters will have a name formed by capitalizing the property name and adding a `get` or `set` prefix (or optionally ""is"" for a boolean getter). So, `getLength` would be a getter for a `length` property and `setFirstName` a setter for a `firstName` property. `isEmpty` might be the getter method name for a property named `empty`. [NOTE] ==== Property names starting with a capital letter would have getters/setters with just the prefix added. So, the property `Foo` is allowed even though it isn't following the recommended naming conventions. For this property, the accessor methods would be `setFoo` and `getFoo`. A consequence of this is that you aren't allowed to have both a `foo` and a `Foo` property, since they would have the same named accessor methods. ==== The JavaBeans specification makes a special case for properties which typically might be acronyms. If the first two letters of a property name are uppercase, no capitalization is performed (or more importantly, no decapitalization is done if generating the property name from the accessor method name). So, `getURL` would be the getter for a `URL` property. [NOTE] ==== Because of the special ""acronym handling"" property naming logic in the JavaBeans specification, the conversion to and from a property name are non-symmetrical. This leads to some strange edge cases. Groovy adopts a naming convention that avoids one ambiguity that might seem a little strange but was popular at the time of Groovy's design and has remained (so far) for historical reasons. Groovy looks at the second letter of a property name. If that is a capital, the property is deemed to be one of the acronym style properties and no capitalization is done, otherwise normal capitalization is done. Although we _never_ recommend it, it does allow you to have what might seem like ""duplicate named"" properties, e.g. you can have `aProp` and `AProp`, or `pNAME` and `PNAME`. The getters would be `getaProp` and `getAProp`, and `getpNAME` and `getPNAME` respectively. ==== ===== Modifiers on a property We have already seen that properties are defined by omitting the visibility modifier. In general, any other modifiers, e.g. `transient` would be copied across to the field. Two special cases are worth noting: * `final`, which we saw earlier is for read-only properties, is copied onto the backing field but also causes no setter to be defined * `static` is copied onto the backing field but also causes the accessor methods to be static If you wish to have a modifier like `final` also carried over to the accessor methods, you can write your properties long hand or consider using a <>. ===== Annotations on a property Annotations, including those associated with AST transforms, are copied on to the backing field for the property. This allows AST transforms which are applicable to fields to be applied to properties, e.g.: [source,groovy] ---- include::../test/ClassTest.groovy[tags=annotated_properties,indent=0] ---- <1> Confirms no eager initialization <2> Normal property access <3> Confirms initialization upon property access [[split-properties]] ===== Split property definition with an explicit backing field Groovy's property syntax is a convenient shorthand when your class design follows certain conventions which align with common JavaBean practice. If your class doesn't exactly fit these conventions, you can certainly write the getter, setter and backing field long hand like you would in Java. However, Groovy does provide a split definition capability which still provides a shortened syntax while allowing slight adjustments to the conventions. For a split definition, you write a field and a property with the same name and type. Only one of the field or property may have an initial value. For split properties, annotations on the field remain on the backing field for the property. Annotations on the property part of the definition are copied onto the getter and setter methods. This mechanism allows a number of common variations that property users may wish to use if the standard property definition doesn't exactly fit their needs. For example, if the backing field should be `protected` rather than `private`: [source,groovy] ---- class HasPropertyWithProtectedField { protected String name // <1> String name // <2> } ---- <1> Protected backing field for name property instead of normal private one <2> Declare name property Or, the same example but with a package-private backing field: [source,groovy] ---- class HasPropertyWithPackagePrivateField { String name // <1> @PackageScope String name // <2> } ---- <1> Declare name property <2> Package-private backing field for name property instead of normal private one As a final example, we may wish to apply method-related AST transforms, or in general, any annotation to the setters/getters, e.g. to have the accessors be synchronized: [source,groovy] ---- class HasPropertyWithSynchronizedAccessorMethods { private String name // <1> @Synchronized String name // <2> } ---- <1> Backing field for name property <2> Declare name property with annotation for setter/getter ===== Explicit accessor methods The automatic generation of accessor methods doesn't occur if there is an explicit definition of the getter or setter in the class. This allows you to modify the normal behavior of such a getter or setter if needed. Inherited accessor methods aren't normally considered but if an inherited accessor method is marked final, that will also cause no generation of an additional accessor method to honor the `final` requirement of no subclassing of such methods. === Annotation [[ann-definition]] ==== Annotation definition An annotation is a kind of special interface dedicated at annotating elements of the code. An annotation is a type which superinterface is the jdk:java.lang.annotation.Annotation[Annotation] interface. Annotations are declared in a very similar way to interfaces, using the `@interface` keyword: [source,groovy] ---- include::../test/ClassTest.groovy[tags=define_annotation,indent=0] ---- An annotation may define members in the form of methods without bodies and an optional default value. The possible member types are limited to: * primitive types * jdk:java.lang.String[Strings] * jdk:java.lang.Class[Classes] * an jdk:java.lang.Enum[enumeration] * another jdk:java.lang.annotation.Annotation[annotation type] * or any array of the above For example: [source,groovy] ---- include::../test/ClassTest.groovy[tags=ann_member_string,indent=0] include::../test/ClassTest.groovy[tags=ann_member_string_default,indent=0] include::../test/ClassTest.groovy[tags=ann_member_int,indent=0] include::../test/ClassTest.groovy[tags=ann_member_class,indent=0] include::../test/ClassTest.groovy[tags=ann_member_annotation,indent=0] include::../test/ClassTest.groovy[tags=ann_member_enum,indent=0] ---- <1> an annotation defining a `value` member of type `String` <2> an annotation defining a `value` member of type `String` with a default value of `something` <3> an annotation defining a `step` member of type the primitive type `int` <4> an annotation defining a `appliesTo` member of type `Class` <5> an annotation defining a `value` member which type is an array of another annotation type <6> an annotation defining a `dayOfWeek` member which type is the enumeration type `DayOfWeek` Unlike in the Java language, in Groovy, an annotation can be used to alter the semantics of the language. It is especially true of AST transformations which will generate code based on annotations. [[ann-placement]] ==== Annotation placement An annotation can be applied on various elements of the code: [source,groovy] ---- include::../test/ClassTest.groovy[tags=apply_annotation_1,indent=0] ---- <1> `@SomeAnnotation` applies to the `someMethod` method <2> `@SomeAnnotation` applies to the `SomeClass` class <3> `@SomeAnnotation` applies to the `var` variable In order to limit the scope where an annotation can be applied, it is necessary to declare it on the annotation definition, using the jdk:java.lang.annotation.Target[Target] annotation. For example, here is how you would declare that an annotation can be applied to a class or a method: [source,groovy] ---- include::../test/ClassTest.groovy[tags=ann_target,indent=0] ---- <1> the `@Target` annotation is meant to annotate an annotation with a scope. <2> `@SomeAnnotation` will therefore only be allowed on `TYPE` or `METHOD` The list of possible targets is available in the jdk:java.lang.annotation.ElementType[ElementType enumeration]. WARNING: Groovy does not support the jdk:java.lang.annotation.ElementType#TYPE_PARAMETER[TYPE_PARAMETER] and jdk:java.lang.annotation.ElementType#TYPE_PARAMETER[TYPE_USE] element types which were introduced in Java 8. ==== Annotation member values When an annotation is used, it is required to set at least all members that do not have a default value. For example: [source,groovy] ---- include::../test/ClassTest.groovy[tags=annotation_value_set,indent=0] ---- However it is possible to omit `value=` in the declaration of the value of an annotation if the member `value` is the only one being set: [source,groovy] ---- include::../test/ClassTest.groovy[tags=annotation_value_set_option,indent=0] ---- <1> we can omit the `statusCode` because it has a default value, but `value` needs to be set <2> since `value` is the only mandatory member without a default, we can omit `value=` <3> if both `value` and `statusCode` need to be set, it is required to use `value=` for the default `value` member ==== Retention policy The visibility of an annotation depends on its retention policy. The retention policy of an annotation is set using the jdk:java.lang.annotation.Retention[Retention] annotation: [source,groovy] ---- include::../test/ClassTest.groovy[tags=ann_retention,indent=0] ---- <1> the `@Retention` annotation annotates the `@SomeAnnotation` annotation <2> so `@SomeAnnotation` will have a `SOURCE` retention The list of possible retention targets and description is available in the jdk:java.lang.annotation.RetentionPolicy[RetentionPolicy] enumeration. The choice usually depends on whether you want an annotation to be visible at compile time or runtime. ==== Closure annotation parameters An interesting feature of annotations in Groovy is that you can use a closure as an annotation value. Therefore annotations may be used with a wide variety of expressions and still have IDE support. For example, imagine a framework where you want to execute some methods based on environmental constraints like the JDK version or the OS. One could write the following code: [source,groovy] ---- include::../test/ClassTest.groovy[tags=closure_ann_example,indent=0] ---- For the `@OnlyIf` annotation to accept a `Closure` as an argument, you only have to declare the `value` as a `Class`: [source,groovy] ---- include::../test/ClassTest.groovy[tags=closure_ann_def,indent=0] ---- To complete the example, let's write a sample runner that would use that information: [source,groovy] ---- include::../test/ClassTest.groovy[tags=closure_ann_runner,indent=0] ---- <1> create a new instance of the class passed as an argument (the task class) <2> emulate an environment which is JDK 6 and not Windows <3> iterate on all declared methods of the task class <4> if the method is public and takes no-argument <5> try to find the `@OnlyIf` annotation <6> if it is found get the `value` and create a new `Closure` out of it <7> set the `delegate` of the closure to our environment variable <8> call the closure, which is the annotation closure. It will return a `boolean` <9> if it is `true`, call the method <10> if the method is not annotated with `@OnlyIf`, execute the method anyway <11> after that, return the task object Then the runner can be used this way: [source,groovy] ---- include::../test/ClassTest.groovy[tags=closure_ann_runner_exec,indent=0] ---- ==== Meta-annotations ===== Declaring meta-annotations Meta-annotations, also known as annotation aliases are annotations that are replaced at compile time by other annotations (one meta-annotation is an alias for one or more annotations). Meta-annotations can be used to reduce the size of code involving multiple annotations. Let’s start with a simple example. Imagine you have the `@Service` and `@Transactional` annotations and that you want to annotate a class with both: [source,groovy] ---- include::../test/ClassTest.groovy[tags=transactionalservice_class,indent=0] ---- Given the multiplication of annotations that you could add to the same class, a meta-annotation could help by reducing the two annotations with a single one having the very same semantics. For example, we might want to write this instead: [source,groovy] ---- include::../test/ClassTest.groovy[tags=transactionalservice_class2,indent=0] ---- <1> `@TransactionalService` is a meta-annotation A meta-annotation is declared as a regular annotation but annotated with `@AnnotationCollector` and the list of annotations it is collecting. In our case, the `@TransactionalService` annotation can be written: [source,groovy] ---- include::../test/ClassTest.groovy[tags=metaann_ts,indent=0] ---- <1> annotate the meta-annotation with `@Service` <2> annotate the meta-annotation with `@Transactional` <3> annotate the meta-annotation with `@AnnotationCollector` [[meta-ann-behavior]] ===== Behavior of meta-annotations Groovy supports both _precompiled_ and _source form_ meta-annotations. This means that your meta-annotation _may_ be precompiled, or you can have it in the same source tree as the one you are currently compiling. INFO: Meta-annotations are a Groovy-only feature. There is no chance for you to annotate a Java class with a meta-annotation and hope it will do the same as in Groovy. Likewise, you cannot write a meta-annotation in Java: both the meta-annotation definition *and* usage have to be Groovy code. But you can happily collect Java annotations and Groovy annotations within your meta-annotation. When the Groovy compiler encounters a class annotated with a meta-annotation, it *replaces* it with the collected annotations. So, in our previous example, it will replace `@TransactionalService` with `@Transactional` and `@Service`: [source,groovy] ---- include::../test/ClassTest.groovy[tags=annotations_expanded,indent=0] ---- The conversion from a meta-annotation to the collected annotations is performed during the _semantic analysis_ compilation phase.  In addition to replacing the alias with the collected annotations, a meta-annotation is capable of processing them, including arguments. [[meta-ann-members]] ===== Meta-annotation parameters Meta-annotations can collect annotations which have parameters. To illustrate this, we will imagine two annotations, each of them accepting one argument: [source,groovy] ---- include::../test/ClassTest.groovy[tags=collected_ann_explosive,indent=0] ---- And suppose that you want create a meta-annotation named `@Explosive`: [source,groovy] ---- include::../test/ClassTest.groovy[tags=collected_ann_explosive,indent=0] include::../test/ClassTest.groovy[tags=collector_ann_explosive,indent=0] ---- By default, when the annotations are replaced, they will get the annotation parameter values *as they were defined in the alias*. More interesting, the meta-annotation supports overriding specific values: [source,groovy] ---- include::../test/ClassTest.groovy[tags=example_bomb,indent=0] ---- <1> the `after` value provided as a parameter to `@Explosive` overrides the one defined in the `@Timeout` annotation If two annotations define the same parameter name, the default processor will copy the annotation value to all annotations that accept this parameter: [source,groovy] ---- include::../test/ClassTest.groovy[tags=collector_ann_same_values,indent=0] ---- <1> the `@Foo` annotation defines the `value` member of type `String` <2> the `@Bar` annotation also defines the `value` member of type `String` <3> the `@FooBar` meta-annotation aggregates `@Foo` and `@Bar` <4> class `Bob` is annotated with `@Foo` and `@Bar` <5> the value of the `@Foo` annotation on `Bob` is `a` <6> while the value of the `@Bar` annotation on `Bob` is `b` <7> class `Joe` is annotated with `@FooBar` <8> then the value of the `@Foo` annotation on `Joe` is `a` <9> and the value of the `@Bar` annotation on `Joe` is also `a` In the second case, the meta-annotation value was copied in both `@Foo` and `@Bar` annotations. WARNING: It is a compile time error if the collected annotations define the same members with incompatible types. For example if on the previous example `@Foo` defined a value of type `String` but `@Bar` defined a value of type `int`. It is however possible to customize the behavior of meta-annotations and describe how collected annotations are expanded. We'll look at how to do that shortly but first there is an advanced processing option to cover. [[handling_duplicate_annotations]] ===== Handling duplicate annotations The `@AnnotationCollector` annotation supports a `mode` parameter which can be used to alter how the default processor handles annotation replacement in the presence of duplicate annotations. INFO: Custom processors (discussed next) may or may not support this parameter. As an example, suppose you create a meta-annotation containing the `@ToString` annotation and then place your meta-annotation on a class that already has an explicit `@ToString` annotation. Should this be an error? Should both annotations be applied? Does one take priority over the other? There is no correct answer. In some scenarios it might be quite appropriate for any of these answers to be correct. So, rather than trying to preempt one correct way to handle the duplicate annotation issue, Groovy let's you write your own custom meta-annotation processors (covered next) and let's you write whatever checking logic you like within AST transforms - which are a frequent target for aggregating. Having said that, by simply setting the `mode`, a number of commonly expected scenarios are handled automatically for you within any extra coding. The behavior of the `mode` parameter is determined by the `AnnotationCollectorMode` enum value chosen and is summarized in the following table. |================================ | Mode | Description | DUPLICATE | Annotations from the annotation collection will always be inserted. After all transforms have been run, it will be an error if multiple annotations (excluding those with SOURCE retention) exist. | PREFER_COLLECTOR | Annotations from the collector will be added and any existing annotations with the same name will be removed. | PREFER_COLLECTOR_MERGED | Annotations from the collector will be added and any existing annotations with the same name will be removed but any new parameters found within existing annotations will be merged into the added annotation. | PREFER_EXPLICIT | Annotations from the collector will be ignored if any existing annotations with the same name are found. | PREFER_EXPLICIT_MERGED | Annotations from the collector will be ignored if any existing annotations with the same name are found but any new parameters on the collector annotation will be added to existing annotations. |================================ [[meta-ann-processor]] ===== Custom annotation processors A custom annotation processor will let you choose how to expand a meta-annotation into collected annotations. The behaviour of the meta-annotation is, in this case, totally up to you. To do this, you must: * create a meta-annotation processor, extending gapi:org.codehaus.groovy.transform.AnnotationCollectorTransform[AnnotationCollectorTransform] * declare the processor to be used in the meta-annotation declaration To illustrate this, we are going to explore how the meta-annotation `@CompileDynamic` is implemented. `@CompileDynamic` is a meta-annotation that expands itself to `@CompileStatic(TypeCheckingMode.SKIP)`. The problem is that the default meta annotation processor doesn’t support enums and the annotation value `TypeCheckingMode.SKIP` is one. The naive implementation here would not work: [source,groovy] ---- include::../test/ClassTest.groovy[tags=compiledynamic_naive,indent=0] ---- Instead, we will define it like this: [source,groovy] ---- include::../test/ClassTest.groovy[tags=compiledynamic_def_fixed,indent=0] ---- The first thing you may notice is that our interface is no longer annotated with `@CompileStatic`. The reason for this is that we rely on the `processor` parameter instead, that references a class which will *generate* the annotation. Here is how the custom processor is implemented: [source,groovy] .CompileDynamicProcessor.groovy ---- include::../test/ClassTest.groovy[tags=compiledynamic_processor,indent=0] ---- <1> our custom processor is written in Groovy, and for better compilation performance, we use static compilation <2> the custom processor has to extend gapi:org.codehaus.groovy.transform.AnnotationCollectorTransform[AnnotationCollectorTransform] <3> create a class node representing the `@CompileStatic` annotation type <4> create a class node representing the `TypeCheckingMode` enum type <5> `collector` is the `@AnnotationCollector` node found in the meta-annotation. Usually unused. <6> `aliasAnnotationUsage` is the meta-annotation being expanded, here it is `@CompileDynamic` <7> `aliasAnnotated` is the node being annotated with the meta-annotation <8> `sourceUnit` is the `SourceUnit` being compiled <9> we create a new annotation node for `@CompileStatic` <10> we create an expression equivalent to `TypeCheckingMode.SKIP` <11> we add that expression to the annotation node, which is now `@CompileStatic(TypeCheckingMode.SKIP)` <12> return the generated annotation In the example, the `visit` method is the only method which has to be overridden. It is meant to return a list of annotation nodes that will be added to the node annotated with the meta-annotation. In this example, we return a single one corresponding to `@CompileStatic(TypeCheckingMode.SKIP)`. [[generics]] === Generics (TBD) include::_traits.adoc[leveloffset=+1] include::_records.adoc[leveloffset=+1] include::_sealed.adoc[leveloffset=+1] ",12248,False,2096.6074004517604,median "== The Byteman Rule Language Rules are defined in scripts which consists of a sequence of rule definitions interleaved with comment lines. Comments may occur within the body of a rule definition as well as preceding or following a definition but must be on separate lines from the rule text. Comments are lines which begin with a # character: ---- ###################################### # Example Rule Set # # a single rule definition RULE example rule # comment line in rule body . . . ENDRULE ---- === Rule Events Rule event specifications identify a specific location in a target method associated with a target class. Target methods can be either static or instance methods or constructors. If no detailed location is specified the default location is entry to the target method. So, the basic schema for a single rule is as follows: ---- # rule skeleton RULE CLASS METHOD BIND IF DO ENDRULE ---- The name of the rule following the `RULE` keyword can be any free form text with the restriction that it must include at least one non-white space character. Rule names do not have to be unique but it obviously helps when debugging rule scripts if they clearly identify the rule. The rule name is printed whenever an error is encountered during parsing, type checking, compilation or execution. The class and method names following the `CLASS` and `METHOD` keywords must be on the same line. The class name can identify a class either with or without the package qualification. The method name can identify a method with or without an argument list or return type. A constructor method is identified using the special name `` and a class initialization method is identified using the special name ``. For example, ---- # class and method example RULE any commit on any coordinator engine CLASS CoordinatorEngine METHOD commit . . . ENDRULE ---- matches the rule with any class whose name is `CoordinatorEngine`, irrespective of the package it belongs to. When any class with this name is loaded then the agent will insert a trigger point at the beginning of any method named commit. If there are several occurrences of this method, with different signatures then each method will have a trigger point inserted. More precise matches can be guaranteed by adding a signature comprising a parameter type list and, optionally, a return type. For example, ---- # class and method example 2 RULE commit with no arguments on wst11 coordinator engine CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD State commit() AT LINE 324 . . . ENDRULE ---- This rule will only match the `CoordinatorEngine` class in package `com.arjuna.wst11.messaging.engines` and only match a method commit with no arguments and with a return type whose name is State. Note that in this example the package for class State has been left unspecified. The type checker will infer the package of the parameter or return type from the matched method where it is omitted. The previous example also employs the location specifier `AT LINE`. The text following the line keyword must be able to be parsed to derive an integer line number. This directs the agent to insert the trigger call at the start of a particular line in the source code. Note: * The Byteman agent _will_ not normally transform any classes in package `java.lang` and will never transform classes in package `org.jboss.byteman`, the byteman package itself (it is possible to remove the first of these restrictions by setting a System property, but you need to be really sure you know what you are doing – see below for details). * Inner classes can be specified by employing the (internal format) `$` separator to distinguish an inner class from its enclosing outer class e.g. `org.my.List$Cons`, `Map$Entry$Wrapper`. ==== Class Rules vs Interface Rules Byteman rules can be attached to interfaces as well as classes. If the `CLASS` keyword is replaced with the keyword `INTERFACE` then the rule applies to any class which implements the specified interface. For example, the following rule ---- # interface rule example RULE commit with no arguments on any engine INTERFACE com.arjuna.wst11.messaging.engines.Engine METHOD commit() . . . ENDRULE ---- is attached to method commit of interface `Engine`. If `Engine` is implemented by classes `CoordinatorEngine` and `ParticipantEngine` then the rule implies two trigger points, one at the start of method `CoordinatorEngine.commit()` and another at the start of method `ParticipantEngine.commit()`. The agent ensures that each implementing class is transformed to include a trigger call for the rule. ==== Overriding Rules Normally, Byteman only injects rule code into methods which are defined by the class identified in the `CLASS` clause. This is sometimes not very helpful. For example, the following rule is not much use: ---- RULE trace Object.finalize CLASS java.lang.Object METHOD finalize IF TRUE DO System.out.println(""Finalizing "" + $0) ENDRULE ---- The print statement gets inserted into method `Object.finalize()`. However, the JVM only calls finalize when an object's class overrides `Object.finalize()`. So, this rule will not do what is intended because overriding methods will not be modified. (n.b. this is not quite the full story – method implementations which directly override Object.finalize _and_ call super.finalize() _will_ trigger the rule). There are many other situations where it might be desirable to inject code into overriding method implementations. For example, class `Socket` is specialised by various classes which provide their own implementation of methods bind, accept etc. So, a rule attached to `Socket.bind()` will not be triggered when the bind method of one of these subclasses is called (unless the subclass method calls `super.bind()`). Of course, it is always possible to define a specific rule for each overriding class. However, this is tedious and may possibly miss some cases when the code base is changed. So, Byteman provides a simple bit of syntax for specifying that rules should also be injected into overriding implementations. ---- RULE trace Object.finalize CLASS ^java.lang.Object METHOD finalize IF TRUE DO System.out.println(""Finalizing "" + $0) ENDRULE ---- The `^` prefix attached to the class name tells the agent that the rule should apply to implementations of finalize defined either by class `Object` or by any class which extends `Object`. This prefix can also be used with interface rules, requiring the agent to inject the rule code into methods of classes which implement the interface and also into overriding methods on subclasses of the implementing classes. Note that if an overriding method invokes a super method then this style of injection may cause the injected rule code to be triggered more than once. In particular, injecting into constructors (which, inevitably, invoke some form of super constructor) will often result in multiple triggerings of the rule. This is easily avoided by adding a condition to the rule which checks the name of the caller method. So, for example, the rule above would be better rewritten as ---- RULE trace Object.finalize at initial call CLASS ^java.lang.Object METHOD finalize IF NOT callerEquals(""finalize"") DO System.out.println(""Finalizing "" + $0) ENDRULE ---- This rule uses the built-in method `callerEquals` which can be called with a variety of alternative signatures (described in full below). This version calls `String.equals()` comparing the name of the method which called the trigger method to its String argument and returns the result. The condition negates this using the `NOT` operator (another way of writing the Java `!` Operator). So, when an implementation of `finalize` is called via the finalizer thread's `runFinalizer()` method this condition evaluates to true and the rule fires. When it gets called via `super.finalize()` the condition evaluates to false and the rule does not fire. ==== Overriding Interface Rules The `^` prefix can also be used in combination with `INTERFACE` rules. Normally an interface rule is only injected into classes which directly implement the interface methods. This can mean that a plain `INTERFACE` rule does not always get injected into the classes you are interested in. For example, class `ArrayList` extends class `AbstractList` which, in turn, implements interface `List`. A rule attached to `INTERFACE` List _will_ be considered for injection into `AbstractList` but will _not_ be considered for injection into `ArrayList`. This makes sense because `AbstractList` will contain an implementation of every method in `List` (some of these methods may be abstract). So, any methods in class `ArrayList` which re-implement the interface are considered to be overriding methods. However, the `^` prefix can be used to achieve the desired effect. If the rule is attached to `INTERFACE` ^List then it _will_ be considered for injection into both `AbstractList` and `ArrayList`. Note that there is a subtle difference between these cases where a class extends a superclass and those where an interface extends a superinterface. The same class hierarchy can be used as an example to explain how interface extension is treated. Let's look at the interface `Collection` which is extended by interface `List`. When a rule is attached to `INTERFACE Collection` then it is considered for injection into any class which implements `Collection` and also any class which implements an extension of `Collection`. Since `List` extends `Collection` this means that an implementation class like `AbstractList` will be a candidate for the rule. This is because `AbstractList` is the first class reached down the chain from `Collection` via `List` so it is the first point in the class hierarchy where an implementation can be found for methods of `Collection` (even if it is only an abstract method). Class `ArrayList` willl not be a candidate for injection because any of it's methods which re-implement a method declared by Collection will still only override a method implemented in `AbstractList`. If you want the rule to be injected into these overriding methods defined in class `ArrayList` then you can do so by attaching the rule to `INTERFACE ^Collection`. ==== Location Specifiers The examples above either specified the precise location of the trigger point within the target method to a specific line number using `AT LINE` or defaulted it to the start of the method. Clearly, line numbers can be used to specify almost any point during execution and are easy and convenient to use in code which is not subject to change. However, this approach is not very useful for test automation where the code under test may well get modified. Obviously when code is edited the associated tests need to be revised. But modifications to the code base can easily shift the line numbers of unmodified code invalidating test scripts unrelated to the edits. Luckily, there are several other ways of specifying where a trigger point should be inserted into a target method. For example, ---- # location specifier example RULE countdown at commit CLASS CoordinatorEngine METHOD commit AFTER WRITE $current . . . ENDRULE ---- The name current prefixed with a `$` sign identifies a local variable,or possibly a method parameter. In this case, current happens to be a local variable declared and initialised at the start of method `CoordinatorEngine.commit` whose type is the enum `State`. ---- public State commit() { final State current ; synchronized(this) { current = this.state ; if (current == State.STATE_PREPARED_SUCCESS) { . . . ---- So, the trigger point will be inserted immediately after the first write operation in the bytecode (istore) which updates the stack location used to store current. This is effectively the same as saying that the trigger point will occur at the point in the source code where local variable current is initialised i.e. the first line inside the synchronized block. By contrast, the following rule would locate the trigger point after the first read from field recovered: ---- # location specifier example 2 RULE add countdown at recreate CLASS CoordinatorEngine METHOD AT READ CoordinatorEngine.recovered . . . ENDRULE ---- Note that in the last example the field type is qualified to ensure that the write is to the field belonging to an instance of class `CoordinatorEngine`. Without the type the rule would match any read from a field with name `recovered`. The full set of location specifiers is as follows: `AT ENTRY` + `AT EXIT` + `AT LINE _number_` + `AT READ _[type .] field [count_ | ALL _]_` + `AT READ _$var-or-idx [count_ | ALL _]_` + `AFTER READ _[ type .] field [count_ | ALL _]_` + `AFTER READ _$var-or-idx [count_ | ALL _]_` + `AT WRITE _[ type .] field [count_ | ALL _]_` + `AT WRITE _$var-or-idx [count_ | ALL _]_` + `AFTER WRITE _[ type .] field [count_ | ALL _]_` + `AFTER WRITE _$var-or-idx [count_ | ALL _]_` + `AT INVOKE _[ type .] method [ ( argtypes ) ] [count_ | ALL _]_` + `AFTER INVOKE _[ type .] method [ ( argtypes ) ][count_ | ALL _]_` + `AT SYNCHRONIZE _[count_ | ALL _]_` + `AFTER SYNCHRONIZE _[count_ | ALL _]_` + `AT THROW _[count_ | ALL _]_` + `AT EXCEPTION EXIT` If a location specifier is provided it must immediately follow the `METHOD` specifier. If no location specifier is provided it defaults to `AT ENTRY`. ===== AT ENTRY An `AT ENTRY` specifier normally locates the trigger point before the first executable instruction in the trigger method. An exception to this occurs in the case of a constructor method in which case the trigger point is located before the first instruction following the call to the super constructor or redirection call to an alternative constructor. This is necessary to ensure that rules do not attempt to bind and operate on the instance before it is constructed. ===== AT EXIT An `AT EXIT` specifier locates a trigger point at each location in the trigger method where a normal return of control occurs (i.e. wherever there is an implicit or explicit return but not where a throw exits the method). ===== AT LINE An `AT LINE` specifier locates the trigger point before the first executable bytecode instruction in the trigger method whose source line number is greater than or equal to the line number supplied as argument to the specifier. If there is no executable code at (or following) the specified line number the agent will not insert a trigger point (note that it does not print an error in such cases because this may merely indicate that the rule does not apply to this particular class or method). ===== AT READ An `AT READ` specifier followed by a field name locates the trigger point before the first mention of an object field whose name matches the supplied field name i.e. it corresponds to the first occurred of a corresponding getField instruction in the bytecode. If a type is specified then the getField instruction will only be matched if the named field is declared by a class whose name matches the supplied type. If a count N is supplied then the Nth matching getField will be used as the trigger point. Note that the count identifies to the Nth textual occurence of the field access, not the Nth field access in a particular execution path at runtime. If the keyword ALL is specified in place of a count then the rule will be triggered at all matching getField calls. An `AT READ` specifier followed by a $-prefixed local variable name, method parameter name or method parameter index locates the trigger point before the first instruction which reads the corresponding local or method parameter variable i.e. it corresponds to an iload, dload, aload etc instruction in the bytecode. If a count N is supplied then the Nth matching read will be used as the trigger point. Note that the count identifies to the Nth textual occurrence of a read of the variable, not the Nth access in a particular execution path at runtime. If the keyword ALL is specified in place of a count then the rule will be triggered before every read of the variable. Note that it is only possible to use local or parameter variable names such as $i, $this or $arg1 if the trigger method bytecode includes a local variable table, e.g. if it has been compiled with the -g flag. By contrast, it is always possible to refer to parameter variable read operations using the index notation `$0`, `$1` etc (however, note that location `AT READ` `$0` will only match where the trigger method is an instance method). ===== AFTER READ An `AFTER READ` specification is identical to an `AT READ` specification except that it locates the trigger point after the getField or variable read operation. ===== AT WRITE, AFTER WRITE `AT WRITE` and `AFTER WRITE` specifiers are the same as the corresponding READ specifiers except that they correspond to assignments to the named field or named variable in the source code i.e. they identify putField or istore, dstore, etc instructions. Note that location `AT WRITE $0` or, equivalently, `AT WRITE $this` will never match any candidate trigger method because the target object for an instance method invocation is never assigned. Note also that for a given local variable, localvar, location `AT WRITE` $localvar or, equivalently, `AT WRITE` $localvar 1 identifies the location immediately after the local variable is initialised i.e. it is treated as if it were specified as `AFTER WRITE` $localvar. This is necessary because the variable is not in scope until after it is initialised. This also ensures that the local variable which has been written can be safely accessed in the rule body. ===== AT INVOKE, AFTER INVOKE `AT INVOKE` and `AFTER INVOKE` specifiers are like `READ` and `WRITE` specifiers except that they identify invocations of methods or constructors within the trigger method as the trigger point. The method may be identified using a bare method name or the name may be qualified by a, possibly package-qualified, type or by a descriptor. A descriptor consists of a comma-separated list of type names within brackets. The type names identify the types of the method parameters and may be prefixed with package qualifiers and employ array bracket pairs as suffixes. ===== AT SYNCHRONIZE, AFTER SYNCHRONIZE `AT SYNCHRONIZE` and `AFTER SYNCHRONIZE` specifiers identify synchronization blocks in the target method, i.e. they correspond to `MONITORENTER` instructions in the bytecode. Note that AFTER SYNCHRONIZE identifies the point immediately after entry to the synchronized block rather than the point immediately after exit from the block. ===== AT THROW An `AT THROW` specifier identifies a throw operation within the trigger method as the trigger point. The throw operation may be qualified by a, possibly package-qualified, typename identifying the lexical type of the thrown exception. If a count N is supplied then the location specifies the Nth textual occurrence of a throw. If the keyword ALL is specified in place of a count then the rule will be triggered at all matching occurrences of a throw. ===== AT EXCEPTION EXIT An `AT EXCEPTION EXIT` specifier identifies the point where a method returns control back to its caller via unhandled exceptional control flow. This can happen either because the method itself has thrown an exception or because it has called out to some other method which has thrown an exception. It can also happen when the method executes certain operations in the Java language, for example dereferencing a null object value or indexing beyond the end of an array. A rule injected with this location is triggered at the point where the exception would normally propagate back to the caller. Once rule execution completes then normally the exception flow resumes. However, the rule may subvert this resumed flow by executing a RETURN. It may also explicitly rethrow the original exception or throw some newly created exception by executing a THROW (n.b. if the latter is a checked exception then it must be declared as a possible exception by the trigger method). n.b. when several rules specify the same location the order of injection of trigger calls usually follows the order of the rules in their respective scripts. The exception to this is AFTER locations where the the order of injection is the reverse to the order of occurrence. n.b.b. when a location specifier (other than ENTRY or EXIT) is used with an overriding rule the rule code is only injected into the original method or overriding methods if the location matches the method in question. So, for example, if location AT READ myField 2 is employed then the rule will only be injected into implementations of the method which include two loads of field myField. Methods which do not match the location are ignored. n.b.b.b. for historical reasons `CALL` may be used as a synonym for `INVOKE`, `RETURN` may be used as a synonym for `EXIT` and the `AT` in an `AT LINE` specifier is optional. === Rule Bindings The event specification includes a binding specification which computes values for variables which can subsequently be referenced in the rule body. These values will be computed each time the rule is triggered before testing the rule condition. For example, ---- # binding example RULE countdown at commit CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD commit AT READ state BIND engine:CoordinatorEngine = $0; recovered:boolean = engine.isRecovered(); identifier:String = engine.getId() . . . ENDRULE ---- creates a variable called `engine`. This variable is bound to the recipient of the commit method call which triggered the rule, identified by the parameter reference `$0` (if commit was a static method then reference to `$0` would result in a type check exception). Arguments to the trigger method can be identified using parameter references with successive indices, `$1`, `$2` etc. The declaration of engine specifies its type as being CoordinatorEngine though this is not strictly necessary since it can be inferred form the type of `$0`. Similarly, variables `recovered` and `identifier` are bound by evaluating the expressions on the right of the `=` operator. Note that the binding for `engine` has been established before these variables are bound so it can be referenced in the evaluated expression. Once again, type specifications are provided but they could be inferred. The special syntax `BIND NOTHING` is available for cases where the rule does not need to employ any bindings. Alternatively, the `BIND` clause may be omitted. ==== Downcasts At Rule Variable Initialization A binding initialization can do more than simply introduce a place holder for the value computed in the initializer expression and in this respect it differs significantly from an assignment that occurs elsewhere in the rule body. It is possible to perform a 'downcast' in a binding initialization i.e. assigning a value of some generic class type to a rule variable whose type is a compatible subclass type. For example, in the following rule ---- # downcast example RULE countdown at commit CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD commit AT READ state BIND engine:CoordinatorEngine = $0; endpoint : javax.xml.ws.EndpointReference = engine.participant; w3cEndpoint javax.xml.ws.wsaddressing.W3CEndpointReference = endpoint; . . . ENDRULE ---- the reference stored in the `CoordinatorEngine` field `participant` is used to initialize rule variable `endpoint` whose type is the generic JaxWS class `EndpointReference`. The second binding for rule variable `w3cEndpoint` uses the value stored in `endpoint`. The type of this second variable `w3cEdpoint` is subclass `W3CEndpointReference` of the type `EndpointReference` of the initializing expression. In an assignment anywhere else in a rule this would lead to a type error. The Byteman type checker ignores the type mismatch in this initializing assignment, but only because it knows that `W3CEndpointReference` is a subclass of the type for the intiializer expression, `endpoint`. It assumes that the 'downcast' at this point is deliberate, i.e. that the rule author knows that the value returned by the initializer expression will in fact belongs to the subtype. Byteman still performs a type check when it executes the initialization to ensure that the value is indeed of the required type, throwing an exception if the test fails. n.b. in this case the assignment will never fail because `CoordinatorEngine` field `participant` is actually declared as a `W3CEndpointReference`. Downcasting is particularly useful when rules need to handle generic types like `List` etc. The Byteman type checker cannot identify information about generic types from bytecode because it is erased at compile time. So, for example, a list `get` operation will always be typed as returning an Object. If you know that a specific list available at the injection point stores values of some given type then a value retrieved from the list can be downcast to the desired type in the BIND clause. === Rule Expressions Expressions which occur on the right hand side of the = operator in event bindings can be any of the Java expressions supported by Byteman. This includes all the usual simple expressions found in plus a few extra special cases i.e. * references to previously bound variables * references to the trigger method recipient or parameters * references to the local variables in scope at the trigger point * references to special variables `$!`, `$^`, `$#`, `$*`, `$@`, `$CLASS` and `$METHOD` * static field references * primitive literals * array literals * field accesses * static or instance method invocations * built-in operation invocations n.b. built-in operations are explained in more detail below. Expressions can also be constructed as complex expressions composed from other expressions using the usual Java operators: `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `&&`, `||`, `!`, `=`, `==`, `!=`, `<`, `<=`, `>`, `>=`, `new`, etc. The ternary conditional expression operator, `?` `:`, can also be employed. The type checker does its best to identify the types of simple and complex expressions wherever possible. So, for example, if it knows the type of bound variable engine then it will be able to employ reflection to infer the type of a field access engine.recovered, a method invocation `engine.isRecovered()`, etc. Note: * `throw` and `return` operations are only allowed as the last action in a sequence of rule actions (see below). * Expressions should obey the normal rules regarding associativity and precedence. * The trigger method recipient and parameters may be referred to by index using the symbols `$0` (invalid for a static method), `$1` etc. If the method has been compiled with the relevant debug options then symbolic references may also be used. So, for example, `$this` may be used as an alias for `$0` and `$myArg` may be used as an alias for `$1` if the method first parameter is declared with name `myArg`, * If the trigger method has been compiled with the relevant debug options then local variables may be referenced symbolically using the same syntax to method parameters. So, for example, if variable `idx` is in scope at the trigger point then `$idx` can be used to obtain its value. * Special variables provide access to other trigger method data. There are currently 7 such special variables: - `$!` is valid in at `AT EXIT` rule and is bound to the return value on the stack at the point where the rule is triggered. Its type is the same as the trigger method return type. The rule will fail to inject if the trigger method return type is void. - `$!` is also valid in an `AFTER INVOKE` rule and is bound to the return value on the stack at the point where the rule is triggered. Its type is the same as the invoked method return type. The rule will fail to inject if the invoked method return type is void. - `$^` is valid in an `AT THROW` rule and is bound to the throwable on the stack at the point where the rule is triggered. Its type is Throwable. - `$^` is also valid in an `AT EXCEPTION EXIT` rule and is bound to the throwable being returned from the method via exceptional control flow. Its type is Throwable. - `$#` has type int and identifies the number of parameters supplied to the trigger method. - `$*` is bound to an `Object[]` array containing the trigger method recipient, `$this`, in slot 0 and the trigger method parameter values, `$1`, `$2` etc in slots 1, 2 etc (for a static trigger method the value in slot 0 is `null`). - `$@` is only valid in an `AT INVOKE` rule and is bound to an `Object[]` array containing the `AT INVOKE` target method recipient in slot 0 and the call arguments for the target method installed in slots 1 upwards in call order (if the target method is static the value in slot 0 is `null`). Note that this variable is not valid in `AFTER INVOKE` rules. The array contains the call arguments located on the stack just before the trigger method calls the AT INVOKE target method. These values are no longer available after the call has completed. - `$CLASS` is valid in all rules and is bound to a `String` whose value is the full package qualified name of the trigger class for the rule. The trigger class is the class whose method the rule has been injected into. Note that this is normally the same as the target class mentioned in the `CLASS` clause of the rule. However, when injecting into interfaces or using overriding injection the trigger class may be an implementation or subclass, respectively, of the target class. So there may be more than one trigger class for any given target class. - `$METHOD` is valid in all rules and is bound to a `String` whose value is the full name of the trigger method into which the rule has been injected, qualified with signature and return type. Note that this is normally the same as the target method mentioned in the `METHOD` clause of the rule. However, the target method may omit the signature and return type. So there may be more than one trigger method for any given target method. * Array literal expressions are a comma-separated sequence of expressions enclosed in braces such as `{}` , `{ ""foo"", ""bar"" }`. Array literals may only be used to define the initial value for either: an array variable declared in the `BIND` clause e.g. + `x:int[] = {1, 2, 3};` + or: an array created via a new expression e.g. + `names = new Object[][] {{$0, $0.name()},{$1, $1.name()}};` + _n.b._ Byteman does not restrict the type of expressions embedded in the initializer to other literals. As you can see in the second example above embedded values can be computed using arbitrary Java expressions. Byteman also allows subordinate bracketed terms to have different numbers of items so long as the expressions are type compatible; it simply creates the relevant sub-array using the number of values provided. + _n.b.b._ when an initializer with mixed value types is used to initialize an untyped variable in a `BIND` clause the values must have a type uniform with that of the first element, which can be used consistently to infer the corresponding array type e.g given the following binding `x = { $1, ""foo"", $2 };` + type `Object[]` will be inferred for `x` if `$1` is of type `Object,` type `String[]` will be inferred if `$1` and `$2` are both of of type `String`. With any other types a type error will occur. * Assignments may update the bindings for rule variables introduced in the `BIND` clause, parameter or local variables, instance fields, static fields or the return value special variables `$!`. Assignments are not currently allowed to update any of the the other special variables. * Assignments to parameter variables or local variables are visible on resumption of the trigger method. For example, assume that a rule includes an assignment such as `$name = ""Ernie""`, where name is either a parameter variable or a local variable in scope at the trigger point. If name has value `""Bert""` when the rule is triggered and the assignment actually gets executed then on resumption of the trigger method `name` will have value `""Ernie""`. Note that assignments cannot be made to `$this` (or, equivalently, `$0`); the recipient argument for an instance method is always `final`. * Assignment to `$!` updates the return value on top of the stack at the trigger point, causing the trigger method to return this updated value. The same effect can be achieved by executing a `RETURN` expression. * Byteman provides the English language keywords listed below which can be used in place of the related standard Java operators (in brackets): + `OR (||)`, `AND (&&)`, `NOT (!)`, `LE (<` `=)`, `LT (<)`, `EQ (==)`, `NE (!=)`, `GE (>=)`, `GT (>)`, `TIMES (*)`, `DIVIDE (/)`, `PLUS (+)`, `MINUS (-)`, `MOD (%)`, Keywords are recognised in either upper or lower (but not mixed) case. + Keywords may clash with the same names where they they occur as legal Java identifiers in the target classes and methods specified in Byteman rules === Rule Conditions Rule conditions are nothing more than rule expressions with boolean type. For example, ---- # condition example RULE countdown at commit CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD commit AT READ state BIND engine:CoordinatorEngine = $this; recovered:boolean = engine.isRecovered(); identifier:String = engine.getId() IF recovered . . . ENDRULE ---- merely tests the value of bound variable recovered. The same effect could be achieved by using the following condition: ---- # condition example 2 RULE countdown at commit CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD commit AT READ state BIND engine:CoordinatorEngine = $this, . . . IF engine.isRecovered() . . . ENDRULE ---- Alternatively, if, say, the instance employed a public field, recovered, to store the boolean value returned by method `isRecovered` then the same effect would be achieved by the following condition. ---- # condition example 3 RULE countdown at commit CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD commit AT READ state BIND engine:CoordinatorEngine = $this, . . . IF engine.recovered . . . ENDRULE ---- Note that the boolean literal `true` is available for use in expressions so a rule which should always fire can use this as the condition expression. === Rule Actions Rule actions are either a rule expression or a return or throw action or a sequence of rule expressions separated by semi-colons, possibly ending with a return or throw action. Rule expressions occurring in an action list may have arbitrary type, including void type. A return action is the `return` keyword possibly followed by a rule expression which is used to compute a return value. A return action causes a return from the triggering method so it may omit a return value if and only if the method is void. If a return value is employed then the type checker will ensure that it's type is assignable to the return type of the trigger method. So, for example, the following use of return is legitimate assuming method `commit` has return type `boolean`: ---- # return example RULE countdown at commit CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD commit AT READ state . . . DO debug(""returning early with failure""); return false ENDRULE ---- A throw action is the `throw` keyword followed by an throwable constructor expression. A throwable constructor expression is the keyword `new` followed by the class name of the throwable which is to be thrown followed by an argument list. The argument list may be empty i.e. it may consist of an open and close bracket pair. Alternatively, the brackets may include a single rule expression or a sequence of rule expressions separated by commas. If no arguments are supplied the throwable type must implement an empty constructor. If arguments are supplied then the throwable type must implement a constructor whose signature is type-compatible. n.b. for hysterical reasons the new keyword may be omitted from the throwable constructor expression which follows the throw keyword. A throw action causes a throwable of the type named in the exception constructor to be created and thrown from the _triggering_ method. In order for this to be valid the expression type must either be assignable to `java.lang.RuntimeException` or `java.lang.Error` or be explicitly declared as a checked exception in the triggering method's throws list. The type checker will throw a type exception if either of these conditions is not met. So, for example, the following use of throw is legitimate assuming method `commit` includes `WrongStateException` in its throws list. ---- # throw example RULE countdown at commit CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD commit AT READ state . . . DO debug(""throwing wrong state""); throw new WrongStateException() ENDRULE ---- An empty action list may be specified using the keyword `NOTHING`. === Built-In Calls Built-in calls are calls to a family of useful methods which implement a family operations that are often useful in rule conditions or actions. They are written without a recipient as though they were invocations of a method on `this`. The rule engine identifies calls in this format and translates them to runtime invocations of instance methods of a helper class, by default the class Helper provided by Byteman itself. So, referring back to the last few examples, it is apparent that the class Helper implements a debugging method with signature ---- boolean debug(String message) ---- This method prints the supplied string to `System.out` but only when property `org.jboss.byteman.debug` has been set. It can be used in a rule action to display a message when you wish to debug rule execution, for example: ---- DO debug(""killing JVM""), killJVM() ---- So, in this example when the `debug` built-in is executed the rule engine calls the corresponding method of the current helper instance passing it the string `""killing JVM""`. Method `killJVM` is another built-in implemented by the corresponding instance method of `Helper`. It can be used to perform an immediate halt of the JVM, simulating a JVM crash. Note that method `debug` has a `boolean` return type. It always returns true. This is to allow tracing of rule IF clauses by `AND` in a `debug` call with the rest of the condition. This would normally occur in combination with a test of some bound variable or method parameter, for example: ---- IF debug(""checking for recovered participant"") AND participant.isRecovered() AND debug(""recovered participant "" + participant.getId()) ---- _n.b._ `AND` is an alternative token for the Java `&&` operator. The rule language implementation automatically exposes all public instance methods of class `Helper` as built-in operations. So when the rule type checker encounters an invocation of `debug` with no recipient supplied it verifies that `debug` is a method of class Helper and automatically type checks the call against this method. At execution time the call is executed by invoking the implementation of `debug` on a helper instance created when rule execution is triggered at the injection point. This feature allows additional or alternative built-ins to be added to the rule engine simply by adding new helper implementations. No changes are required to the parser, type checker and compiler in order for this to work. === User-Defined Rule Helpers A rule can specify it's own helper class if it wants to extend, override or replace the set of built-in calls available for use in its event, condition or action. For example, in the following rule, class `FailureTester` is used as the helper class. Its boolean instance method `doWrongState(CoordinatorEngine)` is called from the condition to decide whether or not to throw a `WrongStateException`. ---- # helper example RULE help yourself CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD commit HELPER com.arjuna.wst11.messaging.engines.FailureTester AT EXIT IF doWrongState($0) DO throw new WrongStateException() ENDRULE ---- A helper class does not need to implement any special interface or inherit from any pre-defined class. It merely needs to provide instance methods to resolve the built-in calls which occur in the rule. By sub-classing the default helper it is possible to extend or override the default set of methods. For example, the following rule employs a helper which adds emphasis to the debug messages printed by the rule. ---- # helper example 2 RULE help yourself but rely on others CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD commit HELPER HelperSub AT ENTRY IF NOT flagged($this) DO debug(""throwing wrong state""); flag($this); throw new WrongStateException() ENDRULE ---- ---- class HelperSub extends Helper { public boolean debug(String message) { super(""!!! IMPORTANT EVENT !!! "" + message); } } ---- The rule is still able to employ the built-in methods flag and flagged defined by the default helper class. The examples above use a `HELPER` line in the rule body to reset the helper for a specific rule. It is also possible to reset the helper for all subsequent rules in a file by adding a `HELPER` line outside of the scope of a rule. So, in the following example the first two rules use class `HelperSub` while the third one uses class `YellowSub`. ---- HELPER HelperSub # helper example 3 RULE helping hand . . . RULE I can't help myself . . . RULE help, I need somebody CLASS . . . METHOD . . . HELPER YellowSub ---- === The Rule Helper Lifecycle Methods It is occasionally useful to be able to perform some sort of setup activity when rules are loaded or a teardown activity when rules are unloaded. For example, if tracing rules are loaded to collect statistics on program execution it would be convenient to add a background thread which wakes up at regular intervals in order to print and then zero the value of the various counters incremented by the rules. Similarly, it would be helpful to be able to detect that all the tracing rules had been unloaded so that the thread can be shutdown, avoiding wasted CPU time. The rule engine supports a lifecycle model for loading and unloading which makes this sort of setup and teardown simple to achieve. There are four lifecyle events in the model: activate, install, uninstall and deactivate. Although these lifecycle events are associated with loading and unloading of rules, the focus of the event is the helper class associated with the rule being loaded/unloaded. It is the helper class which provides a callback method to handle the lifecycle event. The four lifecycle events are generated according to the following model. Assume that we have a helper class _H_ and a set of _installed_ rules _R(H)_ employing _H_ as their helper. Obviously _R(H)_ is empty at bootstrap. When a rule _r(H)_ with helper H has been loaded (either during agent bootstrap or via the dynamic listener), injected and typechecked it is installed into the set _R(H)_. When an installed rule is unloaded via the dynamic listener it is uninstalled from the set _R(H)_. - an activate event occurs when an install cause _R(H)_ to transition from empty to non-empty - an install event occurs when _r(H)_ is installed in _R(H)_ - an uninstall event occurs when _r(H)_ is uninstalled from _R(H)_ - a deactivate event occurs an uninstall causes _R(H)_ to transition from non-empty to empty Note that an install always generates an activate event before the associated install event. An uninstall always generates an uninstall event before any associated deactivate event. The helper class _H_ is notified of these events if it implements any of the corresponding static methods: ---- public static void activated() public static void installed(Rule rule) public static void installed(String ruleName) public static void uninstalled(Rule rule) public static void uninstalled(String ruleName) public static void deactivated() ---- `activated()` is called when an activate event occurs. It can perform a one-off set up operation on behalf of all rules employing the helper. `deactivated()` is called when a deactivate event occurs. It can perform a one-off tear down operation on behalf of all rules employing the helper. `installed(Rule)` is called when an install event occurs. It can perform a set up operation specific to the supplied rule. `deinstalled(Rule)` is called when an install event occurs. It can perform a tear down operation specific to the supplied rule. `installed(String)` and `uninstalled(String)` can also be implemented as alternatives to `installed(Rule)` and `uninstalled(Rule)` if the helper can make do with the rule name rather than using the `Byteman Rule` instance. Note that if both flavours are implemented only the method which takes a `Rule` will be called. It is important to understand that loading and unloading of a rule does not always initiate lifecycle processing. If a rule does not parse or typecheck correctly it will not be installed so it will not generate activate or install events. If later this rule is unloaded it will not generate uninstall or deactivate events since it was never installed. It is also possible for a valid rule to be loaded and unloaded without initiating lifecycle processing. For example, the rule may never get injected because no matching trigger class has been loaded into the JVM. === Rule Compilation By default rules are executed by Byteman's own interpreter which interprets the rule's parse tree. However, it is also possible to translate a rule's bindings, condition and actions to bytecode which can then be executed directly by the JVM and, potentially, optimized by the JIT compiler. This is very useful when rule code is injected into a method which is called very frequently. The default execution mode can be switched from interpreted to compiled by setting system property org.jboss.byteman.compile.to.bytecode when the agent is loaded. However, resetting the default for all rules may not be helpful as it is nor always worth incurring the overhead of compiling rules which only get executed once. So, it is also possible to request compilation for a group of rules within a rule script or even for individual rules. The following rule uses a COMPILE clause to ensure that it is always translated to bytecode even when the default mode is interpreted. ---- # this rule will always be compiled RULE compile example CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD prepare COMPILE AT ENTRY . . . ENDRULE ---- If you have reset the default to compiled and wish to disable compilation then a NOCOMPILE clause can be used. The same two clauses can also appear outside a rule at the top level in a script (just as with HELPER clauses). This resets the default for subsequent rules in the same script. ---- # set default execute mode to compile COMPILE # this rule will be compiled RULE compile example 2 CLASS com.arjuna.wst11.messaging.engines.Engine METHOD prepare AT ENTRY . . . ENDRULE # this rule will never be compiled RULE compile example 3 CLASS com.arjuna.wst11.messaging.engines.CoordinatorEngine METHOD prepare NOCOMPILE AT ENTRY . . . ENDRULE # set default execute mode to interpreted NOCOMPILE # this rule will be interpreted RULE compile example 4 CLASS com.arjuna.wst11.messaging.engines.ParticipantEngine METHOD commit AT ENTRY . . . ENDRULE ---- === Module Imports [NOTE] This section documents an early-preview Byteman feature which is incomplete and may be subject to change. When a Byteman rule is injected into a method the injected code needs to be resolved against the values and types available in the injection context. For example, if the rule is injected into method `charAt` of class `String` then a mention of parameter variable `$1` is typed by checking the type signature of the trigger method and noting that it is an `int`. The injected code loads the integer value from slot 1 of the local area of a trigger method invocation and passes it to the rule execution engine. Similarly, a call to `Thread.currentThread()` is type checked by noting that the name preceding the method invocation is a reference to a class named `java.lang.Thread` and looking up first the class and then the method in order to identify that the return type is also of type `Thread`. The rule execution engine executes the resolved method in order to compute the value of this expression. Resolution of type names to classes requires a classloader lookup to see whether a class with the given name is `in scope'. Byteman interprets what it means for a name to be `in scope' by looking up class names using the classloader of the _trigger_ class i.e. the class which owns the method into which the rule is being injected. In normal Java SE deployments this normally presents no issues because application and JDK runtime classes are all visible via the classpath. So, in the following example, the code injected into application class `ThreadPool` can directly refer to application class `Logger` and invoke one of its static methods ---- RULE call out to logging method CLASS org.my.ThreadPool METHOD schedule(Runnable) BIND runnableKlazz = $1.getClass().getName() IF TRUE DO org.my.Logger.log(runnableKlazz, ""scheduled: "" + System.currentTimeMillis()) ---- Since both classes are deployed on the classpath they will both be loaded by the system classloader. When Byteman tries to inject the rule into class `org.my.ThreadPool` it uses that loader to lookup class `org.my.Logger` and finds the desired class. Note that package and class privacy imposes no barriers to Byteman here. The rule could call Logger.log even if it were private. In Java EE deployments this sort of cross-jar or cross-deployment reference may not work. If the two classes above are deployed in separate war files then the classloader for `org.my.ThreadPool` may not be able to resolve references to class `org.my.Logger`. Indeed, if you employ a module system like JBoss Modules or OSGi then you may not even be able to resolve references to classes on the system or bootstrap classpath when you are injecting to code which is deployed via a JBoss or OSGi module loader. Byteman provides a way to overcome this problem using an `IMPORT` declaration. Note that this declaration is _not_ to be confused with Java's `import` statement. `IMPORT` is only appropriate when injecting into a class which belongs to a module. Its purpose is to ensure that classes from other modules are `in scope' for rule code. Type references which are not visible from the target class's loader may still be resolved against types provided by the module whose name follows the `IMPORT` keyword. So, for example, let's assume class `org.my.ThreadPool` is deployed in a JBoss EE depoyment which does not have access to the transactions API. This is a reasonable assumption given that the thread pool has no reason to import the TX module nor to use any of the transaction annotations which would lead to the TX module being auto-imported. The following rule explicitly imports the JBoss Module bringing class `TransactionManager` into scope. This allows the trace call to include details of any active transaction in the record of schedule operations. ---- RULE log thread schedule operations with details of current TX CLASS org.my.ThreadPool METHOD schedule(Runnable) IMPORT javax.transaction.api BIND runnableKlazz = $1.getClass().getName() IF TRUE DO traceln(runnableKlazz + ""scheduled at "" + System.currentTimeMillis() + in TX "" + javax.Transaction.TransactionManager.getTransaction()) ---- Note that the format of the module name following the IMPORT keyword is specific to the module system being used. In this case the name identifies the module used by JBoss EAP to deploy the Java EE Transactions API classes. It is possible to import more than one module by adding repeated `IMPORT` declarations. Also, when writing a script imports may be written at top level (outside of rule scope) accumulating a list of imports that apply to subsequent rules. An empty IMPORT statement at top level will clear the current accumulated imports list. An empty IMPORT statement in the body of a RULE will clear any script level imports just for that rule. ---- # import the TX and JPA APIs IMPORT javax.transaction.api IMPORT javax.persistence.api RULE resolve TX and JPA classes CLASS . . . METHOD . . . AT ENTRY IMPORT javax.transaction.api . . . ENDRULE # cancel script level APIs and use hibernate APIs RULE resolve Hibernate classes CLASS . . . METHOD . . . AT ENTRY IMPORT IMPORT org.hibernate . . . ENDRULE # cancel all script level APIs IMPORT RULE resolve only trigger class scope . . . ENDRULE ---- In order for module imports to work Byteman has to be able to type check the rule using a class loader which looks up type by name first via the target class's loader and then via the classloaders for any imported modules. Since this is a module system-specific task it requires the use of a module system-specific extension jar. Byteman supports a plugin architecture to install an extension which will handle `IMPORT` declarations. You need to configure an appropiate module system plugin when you install the Byteman agent if you want to be able to use imports. Details of how to configure this plugin are provided in chapter _Using Byteman_ below. Currently, Byteman ships with only the one JBoss Modules plugin, for use with JBoss EAP and related products that use the JBoss Modules module system. Eventually, Byteman will provide plugins for other module systems such as the most popular OSGi implementations and, perhaps, the JDK's own Jigsaw module system ",12263,False,2085.2505107785346,median "#include #include ""untitled2.h"" #include ""NIDAQmx.h"" #include ""qmessagebox.h"" #include #include ""QStandardItemModel"" #include #include ""QFileDialog"" #include ""qcustomplot.h"" #include ""plot.h"" #include ""gnuplot.h"" #include // std::setw #include ""sstream"" #include #include #include ""TH1F.h"" #include ""TApplication.h"" #include ""TCanvas.h"" #include ""Math/Minimizer.h"" #include ""TMinuitMinimizer.h"" #include ""Math/Factory.h"" #include ""Math/Functor.h"" #include ""TRandom2.h"" #include ""TError.h"" #include ""Minuit2/Minuit2Minimizer.h"" #include ""Eigen/Core"" #include ""Eigen/LU"" #include ""Math/GSLSimAnMinimizer.h"" #include #include using namespace Eigen; #define DAQmxErrChk(functionCall) if( DAQmxFailed(error=(functionCall)) ) goto Error; else TApplication theApp(""A"",0,0); vector < vector > untitled2::temp_data; untitled2::untitled2(QWidget *parent) : QMainWindow(parent) { angle_pol_test=0; wdg=0; //Configure pointers reference not initialized yet daq_internal_pointer=0; calib_internal_pointer=0; gpib_int_pointer=0; ui.setupUi(this); //Reserve memory for C-like use of vectors calibmatrix_qs.resize(4); for(int i=0;i<4;i++){ (calibmatrix_qs[i]).resize(6); } stokesvect_qs.resize(4); //Initialize the tableview and his model model = new QStandardItemModel(7,6,this); //7 Rows and 6 Columns model->setHorizontalHeaderItem(0, new QStandardItem(QString(""|H>""))); model->setHorizontalHeaderItem(1, new QStandardItem(QString(""|V>""))); model->setHorizontalHeaderItem(2, new QStandardItem(QString(""|P>""))); model->setHorizontalHeaderItem(3, new QStandardItem(QString(""|M>""))); model->setHorizontalHeaderItem(4, new QStandardItem(QString(""|L>""))); model->setHorizontalHeaderItem(5, new QStandardItem(QString(""|R>""))); ui.tableView->setModel(model); //Initialize the tableview and his model model_matrix = new QStandardItemModel(4,6,this); //7 Rows and 6 Columns ui.tableView_2->setModel(model_matrix); //Initialize the tableview and his model model_stokes = new QStandardItemModel(4,1,this); //7 Rows and 6 Columns ui.tableView_3->setModel(model_stokes); //Initializiation of data pointers to null, needed for memory managment for(int i=0;i<4;i++){ for(int j=0;j<6;j++){ calibmatrix_qs[i][j]=0; } } for(int i=0;i<4;++i){ stokesvect_qs[i]=0; } T_H1=0; T_H2=0; T_H3=0; T_H4=0; T_H5=0; T_H6=0; T_H7=0; T_V1=0; T_V2=0; T_V3=0; T_V4=0; T_V5=0; T_V6=0; T_V7=0; T_P1=0; T_P2=0; T_P3=0; T_P4=0; T_P5=0; T_P6=0; T_P7=0; T_M1=0; T_M2=0; T_M3=0; T_M4=0; T_M5=0; T_M6=0; T_M7=0; T_L1=0; T_L2=0; T_L3=0; T_L4=0; T_L5=0; T_L6=0; T_L7=0; T_R1=0; T_R2=0; T_R3=0; T_R4=0; T_R5=0; T_R6=0; T_R7=0; } untitled2::~untitled2() { } void untitled2::setlabel1(double val){ ui.label_cvalue_1->setText(QString::number(val)); } void untitled2::setlabel2(double val){ ui.label_cvalue_2->setText(QString::number(val)); } void untitled2::setlabel3(double val){ ui.label_cvalue_3->setText(QString::number(val)); } void untitled2::setlabel4(double val){ ui.label_cvalue_4->setText(QString::number(val)); } void untitled2::setlabel5(double val){ ui.label_cvalue_5->setText(QString::number(val)); } void untitled2::setlabel6(double val){ ui.label_cvalue_6->setText(QString::number(val)); } void untitled2::setlabel7(double val){ ui.label_cvalue_7->setText(QString::number(val)); } void untitled2::on_pushButton_clicked() { if(daq_internal_pointer!=0){ if(acquisition::stop==true){ if(acquisition::NI==true){ daq_internal_pointer->read_daq(); } else{ daq_internal_pointer->read_daq_MC(); } } // cout<<""PASSATALETTURA""; ui.label_cvalue_1->setText(QString::number(daq_internal_pointer->mean(1))); ui.label_cvalue_2->setText(QString::number(daq_internal_pointer->mean(2))); ui.label_cvalue_3->setText(QString::number(daq_internal_pointer->mean(3))); ui.label_cvalue_4->setText(QString::number(daq_internal_pointer->mean(4))); ui.label_cvalue_5->setText(QString::number(daq_internal_pointer->mean(5))); ui.label_cvalue_6->setText(QString::number(daq_internal_pointer->mean(6))); ui.label_cvalue_7->setText(QString::number(daq_internal_pointer->mean(7))); /*QMessageBox msgBox; msgBox.setText(QString::number(daq_internal_pointer->data[1])); msgBox.exec(); */ } else{ QMessageBox msgBox; msgBox.setText(""Error: No reference to daq istance""); msgBox.exec(); } ui.centralWidget->update(); } void untitled2::on_H_Button_clicked() { if(daq_internal_pointer!=0 && calib_internal_pointer!=0){ if(acquisition::stop==true){ if(acquisition::NI==true){ daq_internal_pointer->read_daq(); } else{ daq_internal_pointer->read_daq_MC(); } } calib_internal_pointer->H_vector[0]=(daq_internal_pointer->mean(1)); calib_internal_pointer->H_vector[1]=(daq_internal_pointer->mean(2)); calib_internal_pointer->H_vector[2]=(daq_internal_pointer->mean(3)); calib_internal_pointer->H_vector[3]=(daq_internal_pointer->mean(4)); calib_internal_pointer->H_vector[4]=(daq_internal_pointer->mean(5)); calib_internal_pointer->H_vector[5]=(daq_internal_pointer->mean(6)); calib_internal_pointer->H_vector[6]=(daq_internal_pointer->mean(7)); if(T_H1!=0){ delete T_H1; T_H1=0; } if(T_H2!=0){ delete T_H2; T_H2=0; } if(T_H3!=0){ delete T_H3; T_H3=0; } if(T_H4!=0){ delete T_H4; T_H4=0; } if(T_H5!=0){ delete T_H5; T_H5=0; } if(T_H6!=0){ delete T_H6; T_H6=0; } if(T_H7!=0){ delete T_H7; T_H7=0; } T_H1= new QStandardItem (QString::number(calib_internal_pointer->H_vector[0])); T_H2= new QStandardItem (QString::number(calib_internal_pointer->H_vector[1])); T_H3= new QStandardItem (QString::number(calib_internal_pointer->H_vector[2])); T_H4= new QStandardItem (QString::number(calib_internal_pointer->H_vector[3])); T_H5= new QStandardItem (QString::number(calib_internal_pointer->H_vector[4])); T_H6= new QStandardItem (QString::number(calib_internal_pointer->H_vector[5])); T_H7= new QStandardItem (QString::number(calib_internal_pointer->H_vector[6])); model->setItem(0,0,T_H1); model->setItem(1,0,T_H2); model->setItem(2,0,T_H3); model->setItem(3,0,T_H4); model->setItem(4,0,T_H5); model->setItem(5,0,T_H6); model->setItem(6,0,T_H7); ui.tableView->update(); } else{ QMessageBox msgBox; msgBox.setText(""Error: No reference to daq istance""); msgBox.exec(); } } void untitled2::on_V_Button_clicked() { if(daq_internal_pointer!=0){ if(acquisition::stop==true){ if(acquisition::NI==true){ daq_internal_pointer->read_daq(); } else{ daq_internal_pointer->read_daq_MC(); } } calib_internal_pointer->V_vector[0]=(daq_internal_pointer->mean(1)); calib_internal_pointer->V_vector[1]=(daq_internal_pointer->mean(2)); calib_internal_pointer->V_vector[2]=(daq_internal_pointer->mean(3)); calib_internal_pointer->V_vector[3]=(daq_internal_pointer->mean(4)); calib_internal_pointer->V_vector[4]=(daq_internal_pointer->mean(5)); calib_internal_pointer->V_vector[5]=(daq_internal_pointer->mean(6)); calib_internal_pointer->V_vector[6]=(daq_internal_pointer->mean(7)); if(T_V1!=0){ delete T_V1; T_V1=0; } if(T_V2!=0){ delete T_V2; T_V2=0; } if(T_V3!=0){ delete T_V3; T_V3=0; } if(T_V4!=0){ delete T_V4; T_V4=0; } if(T_V5!=0){ delete T_V5; T_V5=0; } if(T_V6!=0){ delete T_V6; T_V6=0; } if(T_V7!=0){ delete T_V7; T_V7=0; } T_V1= new QStandardItem (QString::number(calib_internal_pointer->V_vector[0])); T_V2= new QStandardItem (QString::number(calib_internal_pointer->V_vector[1])); T_V3= new QStandardItem (QString::number(calib_internal_pointer->V_vector[2])); T_V4= new QStandardItem (QString::number(calib_internal_pointer->V_vector[3])); T_V5= new QStandardItem (QString::number(calib_internal_pointer->V_vector[4])); T_V6= new QStandardItem (QString::number(calib_internal_pointer->V_vector[5])); T_V7= new QStandardItem (QString::number(calib_internal_pointer->V_vector[6])); model->setItem(0,1,T_V1); model->setItem(1,1,T_V2); model->setItem(2,1,T_V3); model->setItem(3,1,T_V4); model->setItem(4,1,T_V5); model->setItem(5,1,T_V6); model->setItem(6,1,T_V7); ui.tableView->update(); } else{ QMessageBox msgBox; msgBox.setText(""Error: No reference to daq istance""); msgBox.exec(); } } void untitled2::on_P_Button_clicked() { if(daq_internal_pointer!=0){ if(acquisition::stop==true){ if(acquisition::NI==true){ daq_internal_pointer->read_daq(); } else{ daq_internal_pointer->read_daq_MC(); } } calib_internal_pointer->P_vector[0]=(daq_internal_pointer->mean(1)); calib_internal_pointer->P_vector[1]=(daq_internal_pointer->mean(2)); calib_internal_pointer->P_vector[2]=(daq_internal_pointer->mean(3)); calib_internal_pointer->P_vector[3]=(daq_internal_pointer->mean(4)); calib_internal_pointer->P_vector[4]=(daq_internal_pointer->mean(5)); calib_internal_pointer->P_vector[5]=(daq_internal_pointer->mean(6)); calib_internal_pointer->P_vector[6]=(daq_internal_pointer->mean(7)); if(T_P1!=0){ delete T_P1; T_P1=0; } if(T_P2!=0){ delete T_P2; T_P2=0; } if(T_P3!=0){ delete T_P3; T_P3=0; } if(T_P4!=0){ delete T_P4; T_P4=0; } if(T_P5!=0){ delete T_P5; T_P5=0; } if(T_P6!=0){ delete T_P6; T_P6=0; } if(T_P7!=0){ delete T_P7; T_P7=0; } T_P1= new QStandardItem (QString::number(calib_internal_pointer->P_vector[0])); T_P2= new QStandardItem (QString::number(calib_internal_pointer->P_vector[1])); T_P3= new QStandardItem (QString::number(calib_internal_pointer->P_vector[2])); T_P4= new QStandardItem (QString::number(calib_internal_pointer->P_vector[3])); T_P5= new QStandardItem (QString::number(calib_internal_pointer->P_vector[4])); T_P6= new QStandardItem (QString::number(calib_internal_pointer->P_vector[5])); T_P7= new QStandardItem (QString::number(calib_internal_pointer->P_vector[6])); model->setItem(0,2,T_P1); model->setItem(1,2,T_P2); model->setItem(2,2,T_P3); model->setItem(3,2,T_P4); model->setItem(4,2,T_P5); model->setItem(5,2,T_P6); model->setItem(6,2,T_P7); ui.tableView->update(); } else{ QMessageBox msgBox; msgBox.setText(""Error: No reference to daq istance""); msgBox.exec(); } } void untitled2::on_M_Button_clicked() { if(daq_internal_pointer!=0){ if(acquisition::stop==true){ if(acquisition::NI==true){ daq_internal_pointer->read_daq(); } else{ daq_internal_pointer->read_daq_MC(); } } calib_internal_pointer->M_vector[0]=(daq_internal_pointer->mean(1)); calib_internal_pointer->M_vector[1]=(daq_internal_pointer->mean(2)); calib_internal_pointer->M_vector[2]=(daq_internal_pointer->mean(3)); calib_internal_pointer->M_vector[3]=(daq_internal_pointer->mean(4)); calib_internal_pointer->M_vector[4]=(daq_internal_pointer->mean(5)); calib_internal_pointer->M_vector[5]=(daq_internal_pointer->mean(6)); calib_internal_pointer->M_vector[6]=(daq_internal_pointer->mean(7)); if(T_M1!=0){ delete T_M1; T_M1=0; } if(T_M2!=0){ delete T_M2; T_M2=0; } if(T_M3!=0){ delete T_M3; T_M3=0; } if(T_M4!=0){ delete T_M4; T_M4=0; } if(T_M5!=0){ delete T_M5; T_M5=0; } if(T_M6!=0){ delete T_M6; T_M6=0; } if(T_M7!=0){ delete T_M7; T_M7=0; } T_M1= new QStandardItem (QString::number(calib_internal_pointer->M_vector[0])); T_M2= new QStandardItem (QString::number(calib_internal_pointer->M_vector[1])); T_M3= new QStandardItem (QString::number(calib_internal_pointer->M_vector[2])); T_M4= new QStandardItem (QString::number(calib_internal_pointer->M_vector[3])); T_M5= new QStandardItem (QString::number(calib_internal_pointer->M_vector[4])); T_M6= new QStandardItem (QString::number(calib_internal_pointer->M_vector[5])); T_M7= new QStandardItem (QString::number(calib_internal_pointer->M_vector[6])); model->setItem(0,3,T_M1); model->setItem(1,3,T_M2); model->setItem(2,3,T_M3); model->setItem(3,3,T_M4); model->setItem(4,3,T_M5); model->setItem(5,3,T_M6); model->setItem(6,3,T_M7); ui.tableView->update(); } else{ QMessageBox msgBox; msgBox.setText(""Error: No reference to daq istance""); msgBox.exec(); } } void untitled2::on_L_Button_clicked() { if(daq_internal_pointer!=0){ if(acquisition::stop==true){ if(acquisition::NI==true){ daq_internal_pointer->read_daq(); } else{ daq_internal_pointer->read_daq_MC(); } } calib_internal_pointer->L_vector[0]=(daq_internal_pointer->mean(1)); calib_internal_pointer->L_vector[1]=(daq_internal_pointer->mean(2)); calib_internal_pointer->L_vector[2]=(daq_internal_pointer->mean(3)); calib_internal_pointer->L_vector[3]=(daq_internal_pointer->mean(4)); calib_internal_pointer->L_vector[4]=(daq_internal_pointer->mean(5)); calib_internal_pointer->L_vector[5]=(daq_internal_pointer->mean(6)); calib_internal_pointer->L_vector[6]=(daq_internal_pointer->mean(7)); if(T_L1!=0){ delete T_L1; T_L1=0; } if(T_L2!=0){ delete T_L2; T_L2=0; } if(T_L3!=0){ delete T_L3; T_L3=0; } if(T_L4!=0){ delete T_L4; T_L4=0; } if(T_L5!=0){ delete T_L5; T_L5=0; } if(T_L6!=0){ delete T_L6; T_L6=0; } if(T_L7!=0){ delete T_L7; T_L7=0; } T_L1= new QStandardItem (QString::number(calib_internal_pointer->L_vector[0])); T_L2= new QStandardItem (QString::number(calib_internal_pointer->L_vector[1])); T_L3= new QStandardItem (QString::number(calib_internal_pointer->L_vector[2])); T_L4= new QStandardItem (QString::number(calib_internal_pointer->L_vector[3])); T_L5= new QStandardItem (QString::number(calib_internal_pointer->L_vector[4])); T_L6= new QStandardItem (QString::number(calib_internal_pointer->L_vector[5])); T_L7= new QStandardItem (QString::number(calib_internal_pointer->L_vector[6])); model->setItem(0,4,T_L1); model->setItem(1,4,T_L2); model->setItem(2,4,T_L3); model->setItem(3,4,T_L4); model->setItem(4,4,T_L5); model->setItem(5,4,T_L6); model->setItem(6,4,T_L7); ui.tableView->update(); } else{ QMessageBox msgBox; msgBox.setText(""Error: No reference to daq istance""); msgBox.exec(); } } void untitled2::on_R_Button_clicked() { if(daq_internal_pointer!=0){ if(acquisition::stop==true){ if(acquisition::NI==true){ daq_internal_pointer->read_daq(); } else{ daq_internal_pointer->read_daq_MC(); } } calib_internal_pointer->R_vector[0]=(daq_internal_pointer->mean(1)); calib_internal_pointer->R_vector[1]=(daq_internal_pointer->mean(2)); calib_internal_pointer->R_vector[2]=(daq_internal_pointer->mean(3)); calib_internal_pointer->R_vector[3]=(daq_internal_pointer->mean(4)); calib_internal_pointer->R_vector[4]=(daq_internal_pointer->mean(5)); calib_internal_pointer->R_vector[5]=(daq_internal_pointer->mean(6)); calib_internal_pointer->R_vector[6]=(daq_internal_pointer->mean(7)); if(T_R1!=0){ delete T_R1; T_R1=0; } if(T_R2!=0){ delete T_R2; T_R2=0; } if(T_R3!=0){ delete T_R3; T_R3=0; } if(T_R4!=0){ delete T_R4; T_R4=0; } if(T_R5!=0){ delete T_R5; T_R5=0; } if(T_R6!=0){ delete T_R6; T_R6=0; } if(T_R7!=0){ delete T_R7; T_R7=0; } T_R1= new QStandardItem (QString::number(calib_internal_pointer->R_vector[0])); T_R2= new QStandardItem (QString::number(calib_internal_pointer->R_vector[1])); T_R3= new QStandardItem (QString::number(calib_internal_pointer->R_vector[2])); T_R4= new QStandardItem (QString::number(calib_internal_pointer->R_vector[3])); T_R5= new QStandardItem (QString::number(calib_internal_pointer->R_vector[4])); T_R6= new QStandardItem (QString::number(calib_internal_pointer->R_vector[5])); T_R7= new QStandardItem (QString::number(calib_internal_pointer->R_vector[6])); model->setItem(0,5,T_R1); model->setItem(1,5,T_R2); model->setItem(2,5,T_R3); model->setItem(3,5,T_R4); model->setItem(4,5,T_R5); model->setItem(5,5,T_R6); model->setItem(6,5,T_R7); ui.tableView->update(); } else{ QMessageBox msgBox; msgBox.setText(""Error: No reference to daq istance""); msgBox.exec(); } } void untitled2::on_CalibrateButton_clicked() { if(calib_internal_pointer!=0){ if(acquisition::NI==true){ calib_internal_pointer->compute_calibration_Numeric(); } else{ calib_internal_pointer->compute_calibration_4_det(); } for(int i=0;i<4;i++){ for(int j=0;j<6;j++){ if( calibmatrix_qs[i][j]!=0){ delete calibmatrix_qs[i][j]; calibmatrix_qs[i][j]=0; } } } for(int i=0;i<4;i++){ for(int j=0;j<6;j++){ calibmatrix_qs[i][j]=new QStandardItem (QString::number(calib_internal_pointer->matrix[i][j])); model_matrix->setItem(i,j,calibmatrix_qs[i][j]); } } ui.tableView_2->update(); } } void untitled2::on_stokesButton_clicked() { if(calib_internal_pointer!=0 && daq_internal_pointer!=0 ){ if(acquisition::stop==true){ if(acquisition::NI==true){ daq_internal_pointer->read_daq(); } else{ daq_internal_pointer->read_daq_MC(); } } double itot=daq_internal_pointer->mean(7); if(acquisition::NI==false){ itot=daq_internal_pointer->mean(1)+daq_internal_pointer->mean(2)+daq_internal_pointer->mean(3)+daq_internal_pointer->mean(4); } itot=1; double i1=(daq_internal_pointer->mean(1))/itot; double i2=(daq_internal_pointer->mean(2))/itot; double i3=(daq_internal_pointer->mean(3))/itot; double i4=(daq_internal_pointer->mean(4))/itot; double i5=(daq_internal_pointer->mean(5))/itot; double i6=(daq_internal_pointer->mean(6))/itot; calib_internal_pointer->stokes_dat[0]=i1*calib_internal_pointer->matrix[0][0] + i2*calib_internal_pointer->matrix[0][1] + i3*calib_internal_pointer->matrix[0][2] + i4*calib_internal_pointer->matrix[0][3] + i5*calib_internal_pointer->matrix[0][4] + i6*calib_internal_pointer->matrix[0][5]; calib_internal_pointer->stokes_dat[1]=i1*calib_internal_pointer->matrix[1][0] + i2*calib_internal_pointer->matrix[1][1] + i3*calib_internal_pointer->matrix[1][2] + i4*calib_internal_pointer->matrix[1][3] + i5*calib_internal_pointer->matrix[1][4] + i6*calib_internal_pointer->matrix[1][5]; calib_internal_pointer->stokes_dat[2]=i1*calib_internal_pointer->matrix[2][0] + i2*calib_internal_pointer->matrix[2][1] + i3*calib_internal_pointer->matrix[2][2] + i4*calib_internal_pointer->matrix[2][3] + i5*calib_internal_pointer->matrix[2][4] + i6*calib_internal_pointer->matrix[2][5]; calib_internal_pointer->stokes_dat[3]=i1*calib_internal_pointer->matrix[3][0] + i2*calib_internal_pointer->matrix[3][1] + i3*calib_internal_pointer->matrix[3][2] + i4*calib_internal_pointer->matrix[3][3] + i5*calib_internal_pointer->matrix[3][4] + i6*calib_internal_pointer->matrix[3][5]; double s0,s1,s2,s3=0.0; s0=calib_internal_pointer->stokes_dat[0]; s1=calib_internal_pointer->stokes_dat[1]/s0; s2=calib_internal_pointer->stokes_dat[2]/s0; s3=calib_internal_pointer->stokes_dat[3]/s0; // cout<stokes_dat[1]=s1; calib_internal_pointer->stokes_dat[2]=s2; calib_internal_pointer->stokes_dat[3]=s3; for(int i=0;i<4;i++){ if( stokesvect_qs[i]!=0){ delete stokesvect_qs[i]; stokesvect_qs[i]=0; } } for(int i=0;i<4;i++){ stokesvect_qs[i]=new QStandardItem (QString::number(calib_internal_pointer->stokes_dat[i])); model_stokes->setItem(i,0,stokesvect_qs[i]); } ui.tableView_3->update(); } else{ QMessageBox msgBox; msgBox.setText(""Error: No reference to daq istance""); msgBox.exec(); } } void untitled2::on_exportButton_clicked() { QString filename=QFileDialog::getSaveFileName(this, tr(""Save File""),""./calibration.txt"",tr(""Text files (*.txt)"")); ofstream fileout; fileout.open(filename.toUtf8().constData()); if(calib_internal_pointer!=0){ for(int i=0;i<4;++i){ for(int j=0;j<6;++j){ fileout<matrix[i][j]<<""\\t""; } fileout<>temp0; filein>>temp1; filein>>temp2; filein>>temp3; filein>>temp4; filein>>temp5; calib_internal_pointer->matrix[i][0]=temp0; calib_internal_pointer->matrix[i][1]=temp1; calib_internal_pointer->matrix[i][2]=temp2; calib_internal_pointer->matrix[i][3]=temp3; calib_internal_pointer->matrix[i][4]=temp4; calib_internal_pointer->matrix[i][5]=temp5; } } filein.close(); for(int i=0;i<4;i++){ for(int j=0;j<6;j++){ if( calibmatrix_qs[i][j]!=0){ delete calibmatrix_qs[i][j]; calibmatrix_qs[i][j]=0; } } } for(int i=0;i<4;i++){ for(int j=0;j<6;j++){ calibmatrix_qs[i][j]=new QStandardItem (QString::number(calib_internal_pointer->matrix[i][j])); model_matrix->setItem(i,j,calibmatrix_qs[i][j]); } } ui.tableView_2->update(); return; } void untitled2::on_plotButton_clicked() { wdg = new Plot(daq_internal_pointer); wdg->setAttribute(Qt::WA_DeleteOnClose); wdg->show(); wdg->run(); } void untitled2::on_contAcqButton_clicked() { if(acquisition::NI==true){ daq_internal_pointer->thread_cont_acq(); } else{ daq_internal_pointer->thread_cont_acq_MC(); } } void untitled2::on_stopacqButton_clicked() { acquisition::stop=true; daq_internal_pointer->thread_cont_acq_stop(); } void untitled2::closeEvent(QCloseEvent *event) { acquisition::stop=true; } void untitled2::on_plotStokesButton_clicked() { Gnuplot plot; string a,b,c; a=""a=""; a=a+to_string(calib_internal_pointer->stokes_dat[1]); b=""b=""; b=b+to_string(calib_internal_pointer->stokes_dat[2]); c=""c=""; c=c+to_string(calib_internal_pointer->stokes_dat[3]); // cout<thread_cont_acq(); QFuture future = QtConcurrent::run(this,&untitled2::threaded_save_stokes,filename_out); } } void untitled2::threaded_save_stokes(const QString &filename_out){ ofstream file_out; file_out.open(filename_out.toUtf8().constData()); while(acquisition::stop==false) { std::this_thread::sleep_for(std::chrono::seconds(10)); float itot=1.; double i1=(daq_internal_pointer->mean(1))/itot; double i2=(daq_internal_pointer->mean(2))/itot; double i3=(daq_internal_pointer->mean(3))/itot; double i4=(daq_internal_pointer->mean(4))/itot; double i5=(daq_internal_pointer->mean(5))/itot; double i6=(daq_internal_pointer->mean(6))/itot; calib_internal_pointer->stokes_dat[0]=i1*calib_internal_pointer->matrix[0][0] + i2*calib_internal_pointer->matrix[0][1] + i3*calib_internal_pointer->matrix[0][2] + i4*calib_internal_pointer->matrix[0][3] + i5*calib_internal_pointer->matrix[0][4] + i6*calib_internal_pointer->matrix[0][5]; calib_internal_pointer->stokes_dat[1]=i1*calib_internal_pointer->matrix[1][0] + i2*calib_internal_pointer->matrix[1][1] + i3*calib_internal_pointer->matrix[1][2] + i4*calib_internal_pointer->matrix[1][3] + i5*calib_internal_pointer->matrix[1][4] + i6*calib_internal_pointer->matrix[1][5]; calib_internal_pointer->stokes_dat[2]=i1*calib_internal_pointer->matrix[2][0] + i2*calib_internal_pointer->matrix[2][1] + i3*calib_internal_pointer->matrix[2][2] + i4*calib_internal_pointer->matrix[2][3] + i5*calib_internal_pointer->matrix[2][4] + i6*calib_internal_pointer->matrix[2][5]; calib_internal_pointer->stokes_dat[3]=i1*calib_internal_pointer->matrix[3][0] + i2*calib_internal_pointer->matrix[3][1] + i3*calib_internal_pointer->matrix[3][2] + i4*calib_internal_pointer->matrix[3][3] + i5*calib_internal_pointer->matrix[3][4] + i6*calib_internal_pointer->matrix[3][5]; double s0,s1,s2,s3=0.0; s0=calib_internal_pointer->stokes_dat[0]; s1=calib_internal_pointer->stokes_dat[1]/s0; s2=calib_internal_pointer->stokes_dat[2]/s0; s3=calib_internal_pointer->stokes_dat[3]/s0; // cout<stokes_dat[1]=s1; calib_internal_pointer->stokes_dat[2]=s2; calib_internal_pointer->stokes_dat[3]=s3; file_out<stokes_dat[0]<<""\\t""<stokes_dat[1]<<""\\t""<stokes_dat[2]<<""\\t""<stokes_dat[3]<init(); Sleep(60); gpib_int_pointer->GPIBWrite((char *)""*IDN?\\n""); Sleep(60); cout<GPIBRead()<read_daq(); for(int i=0;i<4;i++){ for (int j=0;j<6;++j){ calib_internal_pointer->matrix[i][j]=matrix_NI_temp[i][j]; } } untitled2::on_stokesButton_clicked(); stkNI[0]=calib_internal_pointer->stokes_dat[0]; stkNI[1]=calib_internal_pointer->stokes_dat[1]; stkNI[2]=calib_internal_pointer->stokes_dat[2]; stkNI[3]=calib_internal_pointer->stokes_dat[3]; acquisition::NI=false; acquisition::datasize=acquisition::Count; acquisition::total_num_chan=4; acquisition::data.resize(acquisition::datasize+1); acquisition::ADData.resize(acquisition::datasize+1); daq_internal_pointer->read_daq(); for(int i=0;i<4;i++){ for (int j=0;j<6;++j){ calib_internal_pointer->matrix[i][j]=matrix_MC_temp[i][j]; } } untitled2::on_stokesButton_clicked(); stkMC[0]=calib_internal_pointer->stokes_dat[0]; stkMC[1]=calib_internal_pointer->stokes_dat[1]; stkMC[2]=calib_internal_pointer->stokes_dat[2]; stkMC[3]=calib_internal_pointer->stokes_dat[3]; fidelty=stkNI[1]*stkMC[1]+stkNI[2]*stkMC[2]+stkNI[3]*stkMC[3]; fileout<>temp0; filein>>temp1; filein>>temp2; filein>>temp3; filein>>temp4; filein>>temp5; matrix_NI_temp[i][0]=temp0; matrix_NI_temp[i][1]=temp1; matrix_NI_temp[i][2]=temp2; matrix_NI_temp[i][3]=temp3; matrix_NI_temp[i][4]=temp4; matrix_NI_temp[i][5]=temp5; } filein.close(); QString filename2=QFileDialog::getOpenFileName(this, tr(""Open File""),""./calibration_MC.txt"",tr(""Text files (*.txt)"")); ifstream filein2; filein2.open(filename2.toUtf8().constData()); temp0=0; temp1=0; temp2=0; temp3=0; temp4=0; temp5=0; for(int i=0;i<4;++i){ filein2>>temp0; filein2>>temp1; filein2>>temp2; filein2>>temp3; matrix_MC_temp[i][0]=temp0; matrix_MC_temp[i][1]=temp1; matrix_MC_temp[i][2]=temp2; matrix_MC_temp[i][3]=temp3; matrix_MC_temp[i][4]=0; matrix_MC_temp[i][5]=0; } filein2.close(); } void untitled2::keyPressEvent(QKeyEvent* event) { // If Ctrl-C typed // Or use event->matches(QKeySequence::Copy) if (event->key() == Qt::Key_C && (event->modifiers() & Qt::ControlModifier)) { QAbstractItemModel * model = ui.tableView_3->model(); QItemSelectionModel * selection = ui.tableView_3->selectionModel(); QModelIndexList cells = selection->selectedIndexes(); qSort(cells); // Necessary, otherwise they are in column order QString text; int currentRow = 0; // To determine when to insert newlines foreach (const QModelIndex& cell, cells) { if (text.length() == 0) { // First item } else if (cell.row() != currentRow) { // New row text += '\\n'; } else { // Next cell text += '\\t'; } currentRow = cell.row(); text += cell.data().toString(); } QApplication::clipboard()->setText(text); } } void untitled2::on_polContCalButton_clicked() { double angle=0.; string command; ofstream fileout; fileout.open(""polarizationcontrollercalibration.txt""); if(gpib_int_pointer!=0){ gpib_int_pointer->init(); Sleep(60); gpib_int_pointer->GPIBWrite((char *)""X=-99.00\\n""); Sleep(60); gpib_int_pointer->GPIBWrite((char *)""Y=00.00\\n""); Sleep(60); gpib_int_pointer->GPIBWrite((char *)""Z=00.00\\n""); Sleep(60); for (int i=0;i<=1320;i++){ angle =-99+ 0.15*i; // number to be converted to a string command=""X=""; // string which will contain the result ostringstream convert; // stream used for the conversion convert << std::setfill('0') << std::setw(4)<< setiosflags(ios::fixed) << setprecision(2) <GPIBWrite(&(command[0])); Sleep(60); untitled2::on_stokesButton_clicked(); fileout<stokes_dat[0]<<""\\t""<stokes_dat[1]<<""\\t""<stokes_dat[2]<<""\\t""<stokes_dat[3]<GPIBWrite((char *)""X=00.00\\n""); Sleep(60); gpib_int_pointer->GPIBWrite((char *)""Y=-99.00\\n""); Sleep(60); for (int i=0;i<=1320;i++){ angle =-99+ 0.15*i; // number to be converted to a string command=""Y=""; // string which will contain the result ostringstream convert; // stream used for the conversion convert << std::setfill('0') << std::setw(4)<< setiosflags(ios::fixed) << setprecision(2) <GPIBWrite(&(command[0])); Sleep(60); untitled2::on_stokesButton_clicked(); fileout<stokes_dat[0]<<""\\t""<stokes_dat[1]<<""\\t""<stokes_dat[2]<<""\\t""<stokes_dat[3]<GPIBWrite((char *)""Y=00.00\\n""); Sleep(60); gpib_int_pointer->GPIBWrite((char *)""Z=-99.00\\n""); Sleep(60); for (int i=0;i<=1320;i++){ angle =-99+ 0.15*i; // number to be converted to a string command=""Z=""; // string which will contain the result ostringstream convert; // stream used for the conversion convert << std::setfill('0') << std::setw(4)<< setiosflags(ios::fixed) << setprecision(2) <GPIBWrite(&(command[0])); Sleep(60); untitled2::on_stokesButton_clicked(); fileout<stokes_dat[0]<<""\\t""<stokes_dat[1]<<""\\t""<stokes_dat[2]<<""\\t""<stokes_dat[3]<stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); if(initial_difference>0.3){ step=3; } else if(initial_difference>0.15){ step=0.45; } else if(initial_difference>0.1){ step=0.3; } new_angle=ang+step; temp_command=create_command(waw,new_angle); gpib_int_pointer->GPIBWrite(&(temp_command[0])); untitled2::on_stokesButton_clicked(); forward_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); if(forward_difference<= initial_difference){ temp_difference=initial_difference; while(forward_difference<=temp_difference){ temp_difference=forward_difference; new_angle=new_angle+step; if(new_angle>99){new_angle=-90;} temp_command=create_command(waw,new_angle); gpib_int_pointer->GPIBWrite(&(temp_command[0])); untitled2::on_stokesButton_clicked(); forward_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); } new_angle=new_angle-step; if(new_angle<-99){new_angle=+90;} temp_command=create_command(waw,new_angle); gpib_int_pointer->GPIBWrite(&(temp_command[0])); } else{ new_angle=ang-step; temp_command=create_command(waw,new_angle); gpib_int_pointer->GPIBWrite(&(temp_command[0])); untitled2::on_stokesButton_clicked(); backward_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); if(backward_difference<= initial_difference){ temp_difference=initial_difference; while(backward_difference<=temp_difference){ temp_difference=backward_difference; new_angle=new_angle-step; if(new_angle<-99){new_angle=99;} temp_command=create_command(waw,new_angle); gpib_int_pointer->GPIBWrite(&(temp_command[0])); untitled2::on_stokesButton_clicked(); backward_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); } new_angle=new_angle+step; if(new_angle>99){new_angle=-99;} temp_command=create_command(waw,new_angle); gpib_int_pointer->GPIBWrite(&(temp_command[0])); } } ang=new_angle; return temp_difference; } void untitled2::on_stabilizationButton_clicked(){ stabilizatio_loop=true; bool ok; double s1 = QInputDialog::getDouble(this, tr(""QInputDialog::getDouble()""), tr(""S1:""), 1, -1, 1, 2, &ok); double s2 = QInputDialog::getDouble(this, tr(""QInputDialog::getDouble()""), tr(""S2:""), 1, -1, 1, 2, &ok); double s3 = QInputDialog::getDouble(this, tr(""QInputDialog::getDouble()""), tr(""S3:""), 1, -1, 1, 2, &ok); QFuture future = QtConcurrent::run(this,&untitled2::stabilization_thread,s1,s2,s3); } void untitled2::stabilization_thread(double s1, double s2,double s3) { qRegisterMetaType>(""QList""); qRegisterMetaType>(""QVector""); qRegisterMetaType(""QAbstractItemModel::LayoutChangeHint""); double angle1=0.; double angle2=0.; double angle3=0.; double difference; double tollerance=0.00000001; //bool loop_total=true; cout<init(); Sleep(60); gpib_int_pointer->GPIBWrite((char *)""X?\\n""); Sleep(60); angle1=atof(gpib_int_pointer->GPIBRead()); Sleep(60); gpib_int_pointer->GPIBWrite((char *)""Y?\\n""); Sleep(60); angle2=atof(gpib_int_pointer->GPIBRead()); Sleep(60); gpib_int_pointer->GPIBWrite((char *)""Z?\\n""); Sleep(60); angle3=atof(gpib_int_pointer->GPIBRead()); Sleep(60); cout< dis(-99, 99); // Range of the generation= range of PC (I know here range=[-99,99) but i don't care so much Unlikely {-99,-99,-99} will be an eigenstate so... int total_data=80; if(calib_internal_pointer!=0 && daq_internal_pointer!=0 ){ if(acquisition::NI==true){ gpib_int_pointer->init(); Sleep(60); vector temp; temp.resize(7); string temp_command; ofstream fillee(""referenceout.txt""); for(int i=0;iGPIBWrite(&(temp_command[0])); Sleep(60); temp_command=create_command(2,dis(gen)); gpib_int_pointer->GPIBWrite(&(temp_command[0])); Sleep(60); temp_command=create_command(3,dis(gen)); gpib_int_pointer->GPIBWrite(&(temp_command[0])); Sleep(200); daq_internal_pointer->read_daq(); temp[6]=daq_internal_pointer->mean(7); temp[0]=daq_internal_pointer->mean(1); temp[1]=daq_internal_pointer->mean(2); temp[2]=daq_internal_pointer->mean(3); temp[3]=daq_internal_pointer->mean(4); temp[4]=daq_internal_pointer->mean(5); temp[5]=daq_internal_pointer->mean(6); /* for(int j=0;j<6;j++){ if(i%6==j){ temp[j]=1; } else{ temp[j]=0; } cout<matrix[0][i]=c(i); //cout<& M) { bool xyz; double rv; for (int i=0; i < M.getactualsize(); i++) { cout << ""i="" << i << "": ""; for (int j=0; j future = QtConcurrent::run(this,&untitled2::fixreference_thread); } void untitled2::fixreference_thread() { if(calib_internal_pointer!=0 && daq_internal_pointer!=0 ){ if(acquisition::NI==true){ double theta=0; double phi=0; double difference; double tollerance=0.01; untitled2::on_stokesButton_clicked(); while(stabilizatio_loop){ difference=fix_reference(1,theta,phi,reference); if(differencestokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); untitled2::updatestokes(out); if(initial_difference>0.1){ // step=0.00001; } if(angle==1) { theta=theta+step; } else if(angle==2){ phi=phi+step; } calib_internal_pointer->rotate_calib_matrix(theta,phi); untitled2::updatestokes(out); forward_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); if(forward_difference<= initial_difference){ temp_difference=forward_difference; } else{ if(angle==1) { theta=theta-2*step; } else if(angle==2){ phi=phi-2*step; } calib_internal_pointer->rotate_calib_matrix(theta,phi); untitled2::updatestokes(out); backward_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); if(backward_difference<= initial_difference){ temp_difference=backward_difference; }else{ if(angle==1) { theta=theta+step; } else if(angle==2){ phi=phi+step; } temp_difference=initial_difference; } } return temp_difference; } /* double untitled2::fix_reference(int angle,double &theta,double &phi,double * reference){ double initial_difference; double forward_difference; double backward_difference; double temp_difference; double step=0.0000001; bool out=true; initial_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); untitled2::updatestokes(out); if(initial_difference>0.1){ // step=0.00001; } if(angle==1) { theta=theta+step; } else if(angle==2){ phi=phi+step; } calib_internal_pointer->rotate_calib_matrix(theta,phi); untitled2::updatestokes(out); forward_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); if(forward_difference<= initial_difference){ temp_difference=initial_difference; while(forward_difference<=temp_difference){ temp_difference=forward_difference; if(angle==1) { theta=theta+step; } else if(angle==2){ phi=phi+step; } calib_internal_pointer->rotate_calib_matrix(theta,phi); untitled2::updatestokes(out); forward_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); } if(angle==1) { theta=theta-step; } if(angle==2){ phi=phi-step; } calib_internal_pointer->rotate_calib_matrix(theta,phi); untitled2::updatestokes(out); } else{ if(angle==1) { theta=theta-step; } else if(angle==2){ phi=phi-step; } calib_internal_pointer->rotate_calib_matrix(theta,phi); untitled2::updatestokes(out); backward_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); if(backward_difference<= initial_difference){ temp_difference=initial_difference; while(backward_difference<=temp_difference){ temp_difference=backward_difference; if(angle==1) { theta=theta-step; } else if(angle==2){ phi=phi-step; } calib_internal_pointer->rotate_calib_matrix(theta,phi); untitled2::updatestokes(out); backward_difference=( (reference[0]-calib_internal_pointer->stokes_dat[1])*(reference[0]-calib_internal_pointer->stokes_dat[1])+(reference[1]-calib_internal_pointer->stokes_dat[2])*(reference[1]-calib_internal_pointer->stokes_dat[2])+(reference[2]-calib_internal_pointer->stokes_dat[3])*(reference[2]-calib_internal_pointer->stokes_dat[3]) ); } if(angle==1) { theta=theta+step; } if(angle==2){ phi=phi+step; } calib_internal_pointer->rotate_calib_matrix(theta,phi); untitled2::updatestokes(out); } } return temp_difference; } */ void untitled2::updatestokes(bool out) { if(calib_internal_pointer!=0 && daq_internal_pointer!=0 ){ double itot=daq_internal_pointer->mean(7); itot=1; double i1=(daq_internal_pointer->mean(1))/itot; double i2=(daq_internal_pointer->mean(2))/itot; double i3=(daq_internal_pointer->mean(3))/itot; double i4=(daq_internal_pointer->mean(4))/itot; double i5=(daq_internal_pointer->mean(5))/itot; double i6=(daq_internal_pointer->mean(6))/itot; calib_internal_pointer->stokes_dat[0]=i1*calib_internal_pointer->matrix[0][0] + i2*calib_internal_pointer->matrix[0][1] + i3*calib_internal_pointer->matrix[0][2] + i4*calib_internal_pointer->matrix[0][3] + i5*calib_internal_pointer->matrix[0][4] + i6*calib_internal_pointer->matrix[0][5]; calib_internal_pointer->stokes_dat[1]=i1*calib_internal_pointer->matrix[1][0] + i2*calib_internal_pointer->matrix[1][1] + i3*calib_internal_pointer->matrix[1][2] + i4*calib_internal_pointer->matrix[1][3] + i5*calib_internal_pointer->matrix[1][4] + i6*calib_internal_pointer->matrix[1][5]; calib_internal_pointer->stokes_dat[2]=i1*calib_internal_pointer->matrix[2][0] + i2*calib_internal_pointer->matrix[2][1] + i3*calib_internal_pointer->matrix[2][2] + i4*calib_internal_pointer->matrix[2][3] + i5*calib_internal_pointer->matrix[2][4] + i6*calib_internal_pointer->matrix[2][5]; calib_internal_pointer->stokes_dat[3]=i1*calib_internal_pointer->matrix[3][0] + i2*calib_internal_pointer->matrix[3][1] + i3*calib_internal_pointer->matrix[3][2] + i4*calib_internal_pointer->matrix[3][3] + i5*calib_internal_pointer->matrix[3][4] + i6*calib_internal_pointer->matrix[3][5]; double s0,s1,s2,s3=0.0; s0=calib_internal_pointer->stokes_dat[0]; s1=calib_internal_pointer->stokes_dat[1]/s0; s2=calib_internal_pointer->stokes_dat[2]/s0; s3=calib_internal_pointer->stokes_dat[3]/s0; if(out){ cout<stokes_dat[1]=s1; calib_internal_pointer->stokes_dat[2]=s2; calib_internal_pointer->stokes_dat[3]=s3; if(out){ for(int i=0;i<4;i++){ if( stokesvect_qs[i]!=0){ delete stokesvect_qs[i]; stokesvect_qs[i]=0; } } for(int i=0;i<4;i++){ stokesvect_qs[i]=new QStandardItem (QString::number(calib_internal_pointer->stokes_dat[i])); model_stokes->setItem(i,0,stokesvect_qs[i]); } ui.tableView_3->update(); } } else{ QMessageBox msgBox; msgBox.setText(""Error: No reference to daq istance""); msgBox.exec(); } } void untitled2::on_testButton_clicked() { // calib_internal_pointer->rotate_calib_matrix(1.5,1.5); ofstream fileout(""polarimeter_perform.txt"", std::fstream::in | std::fstream::out | std::fstream::app); on_stokesButton_clicked(); angle_pol_test=angle_pol_test+2; fileout<stokes_dat[0]<<""\\t""<stokes_dat[1]<<""\\t""<stokes_dat[2]<<""\\t""<stokes_dat[3]<rotate_calib_matrix(theta,phi); } ",16295,True,2754.517224004596,median "#include #include #include namespace { void show_line_error (QLineEdit & line) { line.setStyleSheet (""QLineEdit { color: red }""); } void show_line_ok (QLineEdit & line) { line.setStyleSheet (""QLineEdit { color: black }""); } void show_line_success (QLineEdit & line) { line.setStyleSheet (""QLineEdit { color: blue }""); } void show_label_error (QLabel & label) { label.setStyleSheet (""QLabel { color: red }""); } void show_label_ok (QLabel & label) { label.setStyleSheet (""QLabel { color: black }""); } void show_button_error (QPushButton & button) { button.setStyleSheet (""QPushButton { color: red }""); } void show_button_ok (QPushButton & button) { button.setStyleSheet (""QPushButton { color: black }""); } void show_button_success (QPushButton & button) { button.setStyleSheet (""QPushButton { color: blue }""); } } bool rai_qt::eventloop_processor::event (QEvent * event_a) { assert(dynamic_cast (event_a) != nullptr); static_cast (event_a)->action (); return true; } rai_qt::eventloop_event::eventloop_event (std::function const & action_a) : QEvent (QEvent::Type::User), action (action_a) { } rai_qt::self_pane::self_pane (rai_qt::wallet & wallet_a, rai::account const & account_a) : window (new QWidget), layout (new QVBoxLayout), self_layout (new QHBoxLayout), self_window (new QWidget), your_account_label (new QLabel (""Your RaiBlocks account:"")), account_window (new QWidget), account_layout (new QHBoxLayout), account_text (new QLabel), copy_button (new QPushButton (""Copy"")), balance_window (new QWidget), balance_layout (new QHBoxLayout), balance_label (new QLabel), wallet (wallet_a) { version = new QLabel (boost::str (boost::format (""Version %1%.%2%"") % RAIBLOCKS_VERSION_MAJOR % RAIBLOCKS_VERSION_MINOR).c_str ()); self_layout->addWidget (your_account_label); self_layout->addStretch (); self_layout->addWidget (version); self_layout->setContentsMargins (0, 0, 0, 0); self_window->setLayout (self_layout); auto font (QFontDatabase::systemFont (QFontDatabase::FixedFont)); font.setPointSize (account_text->font().pointSize()); account_text->setFont (font); account_text->setTextInteractionFlags(Qt::TextSelectableByMouse); account_layout->addWidget (account_text); account_layout->addWidget (copy_button); account_layout->setContentsMargins (0, 0, 0, 0); account_window->setLayout (account_layout); layout->addWidget (self_window); layout->addWidget (account_window); balance_layout->addWidget (balance_label); balance_layout->addStretch (); balance_layout->setContentsMargins (0, 0, 0, 0); balance_window->setLayout (balance_layout); layout->addWidget (balance_window); layout->setContentsMargins (5, 5, 5, 5); window->setLayout (layout); QObject::connect (copy_button, &QPushButton::clicked, [this] () { this->wallet.application.clipboard ()->setText (QString (this->wallet.account.to_account ().c_str ())); }); } void rai_qt::self_pane::refresh_balance () { auto balance (wallet.node.balance_pending (wallet.account)); auto final_text (std::string (""Balance (XRB): "") + (balance.first / wallet.rendering_ratio).convert_to ()); if (!balance.second.is_zero ()) { final_text += ""\\nPending: "" + (balance.second / wallet.rendering_ratio).convert_to (); } wallet.self.balance_label->setText (QString (final_text.c_str ())); } rai_qt::accounts::accounts (rai_qt::wallet & wallet_a) : window (new QWidget), layout (new QVBoxLayout), wallet_balance_label (new QLabel), model (new QStandardItemModel), view (new QTableView), use_account (new QPushButton (""Use account"")), create_account (new QPushButton (""Create account"")), import_wallet (new QPushButton (""Import wallet"")), backup_seed (new QPushButton (""Backup/Clipboard wallet seed"")), separator (new QFrame), account_key_line (new QLineEdit), account_key_button (new QPushButton (""Import adhoc key"")), back (new QPushButton (""Back"")), wallet (wallet_a) { separator->setFrameShape (QFrame::HLine); separator->setFrameShadow (QFrame::Sunken); model->setHorizontalHeaderItem (0, new QStandardItem (""Balance"")); model->setHorizontalHeaderItem (1, new QStandardItem (""Account"")); view->setEditTriggers (QAbstractItemView::NoEditTriggers); view->setModel (model); view->verticalHeader ()->hide (); view->setContextMenuPolicy (Qt::ContextMenuPolicy::CustomContextMenu); layout->addWidget (wallet_balance_label); layout->addWidget (view); layout->addWidget (use_account); layout->addWidget (create_account); layout->addWidget (import_wallet); layout->addWidget (backup_seed); layout->addWidget (separator); layout->addWidget (account_key_line); layout->addWidget (account_key_button); layout->addWidget (back); window->setLayout (layout); QObject::connect (use_account, &QPushButton::released, [this] () { auto selection (view->selectionModel ()->selection ().indexes ()); if (selection.size () == 1) { auto error (this->wallet.account.decode_account (model->item (selection [0].row (), 1)->text ().toStdString ())); assert (!error); this->wallet.refresh (); } }); QObject::connect (account_key_button, &QPushButton::released, [this] () { QString key_text_wide (account_key_line->text ()); std::string key_text (key_text_wide.toLocal8Bit ()); rai::raw_key key; if (!key.data.decode_hex (key_text)) { show_line_ok (*account_key_line); account_key_line->clear (); this->wallet.wallet_m->insert_adhoc (key); this->wallet.accounts.refresh (); this->wallet.accounts.refresh_wallet_balance (); this->wallet.history.refresh (); } else { show_line_error (*account_key_line); } }); QObject::connect (back, &QPushButton::clicked, [this] () { this->wallet.pop_main_stack (); }); QObject::connect (create_account, &QPushButton::released, [this] () { rai::transaction transaction (this->wallet.wallet_m->store.environment, nullptr, true); if (this->wallet.wallet_m->store.valid_password (transaction)) { this->wallet.wallet_m->deterministic_insert (transaction); show_button_success (*create_account); create_account->setText (""New account was created""); refresh (); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_button_ok (*create_account); create_account->setText (""Create account""); }); } else { show_button_error (*create_account); create_account->setText (""Wallet is locked, unlock it to create account""); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_button_ok (*create_account); create_account->setText (""Create account""); }); } }); QObject::connect (import_wallet, &QPushButton::released, [this] () { this->wallet.push_main_stack (this->wallet.import.window); }); QObject::connect (backup_seed, &QPushButton::released, [this] () { rai::raw_key seed; rai::transaction transaction (this->wallet.wallet_m->store.environment, nullptr, false); if (this->wallet.wallet_m->store.valid_password (transaction)) { this->wallet.wallet_m->store.seed (seed, transaction); this->wallet.application.clipboard ()->setText (QString (seed.data.to_string ().c_str ())); show_button_success (*backup_seed); backup_seed->setText (""Seed was copied to clipboard""); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_button_ok (*backup_seed); backup_seed->setText (""Backup/Clipboard wallet seed""); }); } else { this->wallet.application.clipboard ()->setText (""""); show_button_error (*backup_seed); backup_seed->setText (""Wallet is locked, unlock it to enable the backup""); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_button_ok (*backup_seed); backup_seed->setText (""Backup/Clipboard wallet seed""); }); } }); refresh_wallet_balance (); } void rai_qt::accounts::refresh_wallet_balance () { rai::transaction transaction (this->wallet.wallet_m->store.environment, nullptr, false); rai::uint128_t balance (0); rai::uint128_t pending (0); for (auto i (this->wallet.wallet_m->store.begin (transaction)), j (this->wallet.wallet_m->store.end ()); i != j; ++i) { rai::public_key key (i->first); balance = balance + (this->wallet.node.ledger.account_balance (transaction, key)); pending = pending + (this->wallet.node.ledger.account_pending (transaction, key)); } auto final_text (std::string (""Wallet balance (XRB): "") + (balance / this->wallet.rendering_ratio).convert_to ()); if (!pending.is_zero ()) { final_text += ""\\nWallet pending: "" + (pending / this->wallet.rendering_ratio).convert_to (); } wallet_balance_label->setText (QString (final_text.c_str ())); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (60), [this] () { this->wallet.application.postEvent (&this->wallet.processor, new eventloop_event ([this] () { refresh_wallet_balance (); })); }); } void rai_qt::accounts::refresh () { model->removeRows (0, model->rowCount ()); rai::transaction transaction (wallet.wallet_m->store.environment, nullptr, false); QBrush brush; for (auto i (wallet.wallet_m->store.begin (transaction)), j (wallet.wallet_m->store.end ()); i != j; ++i) { rai::public_key key (i->first); auto balance_amount (wallet.node.ledger.account_balance (transaction, key)); bool display (true); switch (wallet.wallet_m->store.key_type (i->second)) { case rai::key_type::adhoc: { brush.setColor (""red""); display = !balance_amount.is_zero (); break; } default: { brush.setColor (""black""); break; } } if (display) { QList items; std::string balance; rai::amount (balance_amount / wallet.rendering_ratio).encode_dec (balance); items.push_back (new QStandardItem (balance.c_str ())); auto account (new QStandardItem (QString (key.to_account ().c_str ()))); account->setForeground (brush); items.push_back (account); model->appendRow (items); } } } rai_qt::import::import (rai_qt::wallet & wallet_a) : window (new QWidget), layout (new QVBoxLayout), seed_label (new QLabel (""Seed:"")), seed (new QLineEdit), clear_label (new QLabel (""Modifying seed clears existing keys\\nType 'clear keys' below to confirm:"")), clear_line (new QLineEdit), import_seed (new QPushButton (""Import seed"")), separator (new QFrame), filename_label (new QLabel (""Filename:"")), filename (new QLineEdit), password_label (new QLabel (""Password:"")), password (new QLineEdit), perform (new QPushButton (""Import"")), back (new QPushButton (""Back"")), wallet (wallet_a) { layout->addWidget (seed_label); layout->addWidget (seed); layout->addWidget (clear_label); layout->addWidget (clear_line); clear_line->setPlaceholderText (""clear keys""); layout->addWidget (import_seed); layout->addWidget (separator); layout->addWidget (filename_label); layout->addWidget (filename); layout->addWidget (password_label); layout->addWidget (password); layout->addWidget (perform); layout->addStretch (); layout->addWidget (back); window->setLayout (layout); QObject::connect (perform, &QPushButton::released, [this] () { std::ifstream stream; stream.open (filename->text ().toStdString ().c_str ()); if (!stream.fail ()) { show_line_ok (*filename); std::stringstream contents; contents << stream.rdbuf (); if (!this->wallet.wallet_m->import (contents.str (), password->text ().toStdString ().c_str ())) { show_line_ok (*password); this->wallet.accounts.refresh (); password->clear (); filename->clear (); } else { show_line_error (*password); } } else { show_line_error (*filename); } }); QObject::connect (back, &QPushButton::released, [this] () { this->wallet.pop_main_stack (); }); QObject::connect (import_seed, &QPushButton::released, [this] () { if (clear_line->text ().toStdString () == ""clear keys"") { show_line_ok (*clear_line); rai::raw_key seed_l; if (!seed_l.data.decode_hex (seed->text ().toStdString ())) { bool successful (false); { rai::transaction transaction (this->wallet.wallet_m->store.environment, nullptr, true); if (this->wallet.wallet_m->store.valid_password (transaction)) { this->wallet.wallet_m->store.seed_set (transaction, seed_l); successful = true; } else { show_line_error (*seed); show_button_error (*import_seed); import_seed->setText (""Wallet is locked, unlock it to enable the import""); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (10), [this] () { show_line_ok (*seed); show_button_ok (*import_seed); import_seed->setText (""Import seed""); }); } } if (successful) { rai::transaction transaction (this->wallet.wallet_m->store.environment, nullptr, true); this->wallet.account = this->wallet.wallet_m->deterministic_insert (transaction); auto count (0); for (uint32_t i (1), n (32); i < n; ++i) { rai::raw_key prv; this->wallet.wallet_m->store.deterministic_key (prv, transaction, i); rai::keypair pair (prv.data.to_string ()); auto latest (this->wallet.node.ledger.latest (transaction, pair.pub)); if (!latest.is_zero ()) { count = i; n = i + 32; } } for (uint32_t i (0); i < count; ++i) { this->wallet.account = this->wallet.wallet_m->deterministic_insert (transaction); } } if (successful) { seed->clear (); clear_line->clear (); show_line_ok (*seed); show_button_success (*import_seed); import_seed->setText (""Successful import of seed""); this->wallet.refresh (); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_button_ok (*import_seed); import_seed->setText (""Import seed""); }); } } else { show_line_error (*seed); } } else { show_line_error (*clear_line); } }); } rai_qt::history::history (rai::ledger & ledger_a, rai::account const & account_a, rai::uint128_t const & rendering_ratio_a) : window (new QWidget), layout (new QVBoxLayout), model (new QStandardItemModel), view (new QTableView), tx_window (new QWidget), tx_layout (new QHBoxLayout), tx_label (new QLabel (""Account history count:"")), tx_count (new QSpinBox), ledger (ledger_a), account (account_a), rendering_ratio (rendering_ratio_a) {/* tx_count->setRange (1, 256); tx_layout->addWidget (tx_label); tx_layout->addWidget (tx_count); tx_layout->setContentsMargins (0, 0, 0, 0); tx_window->setLayout (tx_layout);*/ model->setHorizontalHeaderItem (0, new QStandardItem (""Type"")); model->setHorizontalHeaderItem (1, new QStandardItem (""Account"")); model->setHorizontalHeaderItem (2, new QStandardItem (""Amount"")); model->setHorizontalHeaderItem (3, new QStandardItem (""Hash"")); view->setModel (model); view->setEditTriggers (QAbstractItemView::NoEditTriggers); view->verticalHeader ()->hide (); // layout->addWidget (tx_window); layout->addWidget (view); layout->setContentsMargins (0, 0, 0, 0); window->setLayout (layout); tx_count->setValue (32); } namespace { class short_text_visitor : public rai::block_visitor { public: short_text_visitor (MDB_txn * transaction_a, rai::ledger & ledger_a) : transaction (transaction_a), ledger (ledger_a) { } void send_block (rai::send_block const & block_a) { type = ""Send""; account = block_a.hashables.destination; amount = ledger.amount (transaction, block_a.hash ()); } void receive_block (rai::receive_block const & block_a) { type = ""Receive""; account = ledger.account (transaction, block_a.source ()); amount = ledger.amount (transaction, block_a.source ()); } void open_block (rai::open_block const & block_a) { type = ""Receive""; if (block_a.hashables.source != rai::genesis_account) { account = ledger.account (transaction, block_a.hashables.source); amount = ledger.amount (transaction, block_a.hash ()); } else { account = rai::genesis_account; amount = rai::genesis_amount; } } void change_block (rai::change_block const & block_a) { type = ""Change""; amount = 0; account = block_a.hashables.representative; } MDB_txn * transaction; rai::ledger & ledger; std::string type; rai::uint128_t amount; rai::account account; }; } void rai_qt::history::refresh () { rai::transaction transaction (ledger.store.environment, nullptr, false); model->removeRows (0, model->rowCount ()); auto hash (ledger.latest (transaction, account)); short_text_visitor visitor (transaction, ledger); for (auto i (0), n (tx_count->value ()); i < n && !hash.is_zero (); ++i) { QList items; auto block (ledger.store.block_get (transaction, hash)); assert (block != nullptr); block->visit (visitor); items.push_back (new QStandardItem (QString (visitor.type.c_str ()))); items.push_back (new QStandardItem (QString (visitor.account.to_account ().c_str ()))); items.push_back (new QStandardItem (QString (rai::amount (visitor.amount / rendering_ratio).to_string_dec ().c_str ()))); items.push_back (new QStandardItem (QString (hash.to_string ().c_str ()))); hash = block->previous (); model->appendRow (items); } } rai_qt::block_viewer::block_viewer (rai_qt::wallet & wallet_a) : window (new QWidget), layout (new QVBoxLayout), hash_label (new QLabel (""Hash:"")), hash (new QLineEdit), block_label (new QLabel (""Block:"")), block (new QPlainTextEdit), successor_label (new QLabel (""Successor:"")), successor (new QLineEdit), retrieve (new QPushButton (""Retrieve"")), rebroadcast (new QPushButton (""Rebroadcast"")), back (new QPushButton (""Back"")), wallet (wallet_a) { layout->addWidget (hash_label); layout->addWidget (hash); layout->addWidget (block_label); layout->addWidget (block); layout->addWidget (successor_label); layout->addWidget (successor); layout->addWidget (retrieve); layout->addWidget (rebroadcast); layout->addStretch (); layout->addWidget (back); window->setLayout (layout); QObject::connect (back, &QPushButton::released, [this] () { this->wallet.pop_main_stack (); }); QObject::connect (retrieve, &QPushButton::released, [this] () { rai::block_hash hash_l; if (!hash_l.decode_hex (hash->text ().toStdString ())) { rai::transaction transaction (this->wallet.node.store.environment, nullptr, false); auto block_l (this->wallet.node.store.block_get (transaction, hash_l)); if (block_l != nullptr) { std::string contents; block_l->serialize_json (contents); block->setPlainText (contents.c_str ()); auto successor_l (this->wallet.node.store.block_successor (transaction, hash_l)); successor->setText (successor_l.to_string ().c_str ()); } else { block->setPlainText (""Block not found""); } } else { block->setPlainText (""Bad block hash""); } }); QObject::connect (rebroadcast, &QPushButton::released, [this] () { rai::block_hash block; auto error (block.decode_hex (hash->text ().toStdString ())); if (!error) { rai::transaction transaction (this->wallet.node.store.environment, nullptr, false); if (this->wallet.node.store.block_exists (transaction, block)) { rebroadcast->setEnabled (false); this->wallet.node.background ([this, block] () { rebroadcast_action (block); }); } } }); rebroadcast->setToolTip (""Rebroadcast block into the network""); } void rai_qt::block_viewer::rebroadcast_action (rai::uint256_union const & hash_a) { auto done (true); rai::transaction transaction (wallet.node.ledger.store.environment, nullptr, false); auto block (wallet.node.store.block_get (transaction, hash_a)); if (block != nullptr) { wallet.node.network.republish_block (transaction, std::move (block)); auto successor (wallet.node.store.block_successor (transaction, hash_a)); if (!successor.is_zero ()) { done = false; wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (1), [this, successor] () { rebroadcast_action (successor); }); } } if (done) { rebroadcast->setEnabled (true); } } rai_qt::account_viewer::account_viewer (rai_qt::wallet & wallet_a) : window (new QWidget), layout (new QVBoxLayout), account_label (new QLabel (""Account:"")), account_line (new QLineEdit), refresh (new QPushButton (""Refresh"")), balance_window (new QWidget), balance_layout (new QHBoxLayout), balance_label (new QLabel), history (wallet_a.wallet_m->node.ledger, account, wallet_a.rendering_ratio), back (new QPushButton (""Back"")), account (wallet_a.account), wallet (wallet_a) { layout->addWidget (account_label); layout->addWidget (account_line); layout->addWidget (refresh); balance_layout->addWidget (balance_label); balance_layout->addStretch (); balance_layout->setContentsMargins (0, 0, 0, 0); balance_window->setLayout (balance_layout); layout->addWidget (balance_window); layout->addWidget (history.window); layout->addWidget (back); window->setLayout (layout); QObject::connect (back, &QPushButton::released, [this] () { this->wallet.pop_main_stack (); }); QObject::connect (refresh, &QPushButton::released, [this] () { account.clear (); if (!account.decode_account (account_line->text ().toStdString ())) { show_line_ok (*account_line); this->history.refresh (); auto balance (this->wallet.node.balance_pending (account)); auto final_text (std::string (""Balance (XRB): "") + (balance.first / this->wallet.rendering_ratio).convert_to ()); if (!balance.second.is_zero ()) { final_text += ""\\nPending: "" + (balance.second / this->wallet.rendering_ratio).convert_to (); } balance_label->setText (QString (final_text.c_str ())); } else { show_line_error (*account_line); balance_label->clear (); } }); } rai_qt::status::status (rai_qt::wallet & wallet_a) : wallet (wallet_a) { wallet.status->setToolTip (""Wallet status, block count (blocks downloaded)""); active.insert (rai_qt::status_types::nominal); set_text (); } void rai_qt::status::erase (rai_qt::status_types status_a) { assert (status_a != rai_qt::status_types::nominal); auto erased (active.erase (status_a)); (void)erased; set_text (); } void rai_qt::status::insert (rai_qt::status_types status_a) { assert (status_a != rai_qt::status_types::nominal); active.insert (status_a); set_text (); } void rai_qt::status::set_text () { wallet.status->setText (text ().c_str ()); wallet.status->setStyleSheet ((std::string (""QLabel {"") + color () + ""}"").c_str ()); } std::string rai_qt::status::text () { assert (!active.empty ()); std::string result; size_t unchecked (0); std::string count_string; { rai::transaction transaction (wallet.wallet_m->node.store.environment, nullptr, false); auto size (wallet.wallet_m->node.store.block_count (transaction)); unchecked = wallet.wallet_m->node.store.unchecked_count (transaction); count_string = std::to_string (size.sum ()); } switch (*active.begin ()) { case rai_qt::status_types::disconnected: result = ""Status: Disconnected""; break; case rai_qt::status_types::working: result = ""Status: Generating proof of work""; break; case rai_qt::status_types::synchronizing: result = ""Status: Synchronizing""; break; case rai_qt::status_types::locked: result = ""Status: Wallet locked""; break; case rai_qt::status_types::vulnerable: result = ""Status: Wallet password empty""; break; case rai_qt::status_types::active: result = ""Status: Wallet active""; break; case rai_qt::status_types::nominal: result = ""Status: Running""; break; default: assert (false); break; } result += "", Block: ""; if (unchecked != 0 && wallet.wallet_m->node.bootstrap_initiator.in_progress ()) { count_string += "" ("" + std::to_string (unchecked) + "")""; } result += count_string.c_str (); return result; } std::string rai_qt::status::color () { assert (!active.empty ()); std::string result; switch (*active.begin ()) { case rai_qt::status_types::disconnected: result = ""color: red""; break; case rai_qt::status_types::working: result = ""color: blue""; break; case rai_qt::status_types::synchronizing: result = ""color: blue""; break; case rai_qt::status_types::locked: result = ""color: orange""; break; case rai_qt::status_types::vulnerable: result = ""color: blue""; break; case rai_qt::status_types::active: result = ""color: black""; break; case rai_qt::status_types::nominal: result = ""color: black""; break; default: assert (false); break; } return result; } rai_qt::wallet::wallet (QApplication & application_a, rai_qt::eventloop_processor & processor_a, rai::node & node_a, std::shared_ptr wallet_a, rai::account & account_a) : rendering_ratio (rai::Mxrb_ratio), node (node_a), wallet_m (wallet_a), account (account_a), processor (processor_a), history (node.ledger, account, rendering_ratio), accounts (*this), self (*this, account_a), settings (*this), advanced (*this), block_creation (*this), block_entry (*this), block_viewer (*this), account_viewer (*this), import (*this), application (application_a), status (new QLabel), main_stack (new QStackedWidget), client_window (new QWidget), client_layout (new QVBoxLayout), entry_window (new QWidget), entry_window_layout (new QVBoxLayout), separator (new QFrame), account_history_label (new QLabel (""Account history:"")), send_blocks (new QPushButton (""Send"")), settings_button (new QPushButton (""Settings"")), accounts_button (new QPushButton (""Accounts"")), show_advanced (new QPushButton (""Advanced"")), send_blocks_window (new QWidget), send_blocks_layout (new QVBoxLayout), send_account_label (new QLabel (""Destination account:"")), send_account (new QLineEdit), send_count_label (new QLabel (""Amount:"")), send_count (new QLineEdit), send_blocks_send (new QPushButton (""Send"")), send_blocks_back (new QPushButton (""Back"")), active_status (*this) { update_connected (); empty_password (); settings.update_locked (true, true); send_blocks_layout->addWidget (send_account_label); send_account->setPlaceholderText (rai::zero_key.pub.to_account ().c_str ()); send_blocks_layout->addWidget (send_account); send_blocks_layout->addWidget (send_count_label); send_count->setPlaceholderText (""0""); send_blocks_layout->addWidget (send_count); send_blocks_layout->addWidget (send_blocks_send); send_blocks_layout->addStretch (); send_blocks_layout->addWidget (send_blocks_back); send_blocks_layout->setContentsMargins (0, 0, 0, 0); send_blocks_window->setLayout (send_blocks_layout); entry_window_layout->addWidget (account_history_label); entry_window_layout->addWidget (history.window); entry_window_layout->addWidget (send_blocks); entry_window_layout->addWidget (settings_button); entry_window_layout->addWidget (accounts_button); entry_window_layout->addWidget (show_advanced); entry_window_layout->setContentsMargins (0, 0, 0, 0); entry_window_layout->setSpacing (5); entry_window->setLayout (entry_window_layout); main_stack->addWidget (entry_window); status->setAlignment (Qt::AlignHCenter); separator->setFrameShape (QFrame::HLine); separator->setFrameShadow (QFrame::Sunken); client_layout->addWidget (status); client_layout->addWidget (self.window); client_layout->addWidget (separator); client_layout->addWidget (main_stack); client_layout->setSpacing (0); client_layout->setContentsMargins (0, 0, 0, 0); client_window->setLayout (client_layout); client_window->resize (320, 480); refresh (); } void rai_qt::wallet::start () { std::weak_ptr this_w (shared_from_this ()); QObject::connect (settings_button, &QPushButton::released, [this_w] () { if (auto this_l = this_w.lock ()) { this_l->settings.activate (); } }); QObject::connect (accounts_button, &QPushButton::released, [this_w] () { if (auto this_l = this_w.lock ()) { this_l->push_main_stack (this_l->accounts.window); } }); QObject::connect (show_advanced, &QPushButton::released, [this_w] () { if (auto this_l = this_w.lock ()) { this_l->push_main_stack (this_l->advanced.window); } }); QObject::connect (send_blocks_send, &QPushButton::released, [this_w] () { if (auto this_l = this_w.lock ()) { show_line_ok (*this_l->send_count); show_line_ok (*this_l->send_account); rai::amount amount; if (!amount.decode_dec (this_l->send_count->text ().toStdString ())) { rai::uint128_t actual (amount.number () * this_l->rendering_ratio); if (actual / this_l->rendering_ratio == amount.number ()) { QString account_text (this_l->send_account->text ()); std::string account_text_narrow (account_text.toLocal8Bit ()); rai::account account_l; auto parse_error (account_l.decode_account (account_text_narrow)); if (!parse_error) { this_l->send_blocks_send->setEnabled (false); this_l->node.background ([this_w, account_l, actual] () { if (auto this_l = this_w.lock ()) { this_l->wallet_m->send_async (this_l->account, account_l, actual, [this_w] (std::shared_ptr block_a) { if (auto this_l = this_w.lock ()) { auto succeeded (block_a != nullptr); this_l->application.postEvent (&this_l->processor, new eventloop_event ([this_w, succeeded] () { if (auto this_l = this_w.lock ()) { this_l->send_blocks_send->setEnabled (true); if (succeeded) { this_l->send_count->clear (); this_l->send_account->clear (); this_l->accounts.refresh (); } else { show_line_error (*this_l->send_count); } } })); } }); } }); } else { show_line_error (*this_l->send_account); } } else { show_line_error (*this_l->send_account); } } else { show_line_error (*this_l->send_count); } } }); QObject::connect (send_blocks_back, &QPushButton::released, [this_w] () { if (auto this_l = this_w.lock ()) { this_l->pop_main_stack (); } }); QObject::connect (send_blocks, &QPushButton::released, [this_w] () { if (auto this_l = this_w.lock ()) { this_l->push_main_stack (this_l->send_blocks_window); } }); node.observers.blocks.add ([this_w] (rai::block const &, rai::account const & account_a, rai::amount const &) { if (auto this_l = this_w.lock ()) { this_l->application.postEvent (&this_l->processor, new eventloop_event ([this_w, account_a] () { if (auto this_l = this_w.lock ()) { if (this_l->wallet_m->exists (account_a)) { this_l->accounts.refresh (); } if (account_a == this_l->account) { this_l->history.refresh (); this_l->self.refresh_balance (); } } })); } }); node.observers.wallet.add ([this_w] (rai::account const & account_a, bool active_a) { if (auto this_l = this_w.lock ()) { this_l->application.postEvent (&this_l->processor, new eventloop_event ([this_w, account_a, active_a] () { if (auto this_l = this_w.lock ()) { if (this_l->account == account_a) { if (active_a) { this_l->active_status.insert (rai_qt::status_types::active); } else { this_l->active_status.erase (rai_qt::status_types::active); } } } })); } }); node.observers.endpoint.add ([this_w] (rai::endpoint const &) { if (auto this_l = this_w.lock ()) { this_l->application.postEvent (&this_l->processor, new eventloop_event ([this_w] () { if (auto this_l = this_w.lock ()) { this_l->update_connected (); } })); } }); node.observers.disconnect.add ([this_w] () { if (auto this_l = this_w.lock ()) { this_l->application.postEvent (&this_l->processor, new eventloop_event ([this_w] () { if (auto this_l = this_w.lock ()) { this_l->update_connected (); } })); } }); node.bootstrap_initiator.add_observer ([this_w] (bool active_a) { if (auto this_l = this_w.lock ()) { this_l->application.postEvent (&this_l->processor, new eventloop_event ([this_w, active_a] () { if (auto this_l = this_w.lock ()) { if (active_a) { this_l->active_status.insert (rai_qt::status_types::synchronizing); } else { this_l->active_status.erase (rai_qt::status_types::synchronizing); } } })); } }); node.work.work_observers.add ([this_w] (bool working) { if (auto this_l = this_w.lock ()) { this_l->application.postEvent (&this_l->processor, new eventloop_event ([this_w, working] () { if (auto this_l = this_w.lock ()) { if (working) { this_l->active_status.insert (rai_qt::status_types::working); } else { this_l->active_status.erase (rai_qt::status_types::working); } } })); } }); wallet_m->lock_observer = [this_w] (bool invalid, bool vulnerable) { if (auto this_l = this_w.lock ()) { this_l->application.postEvent (&this_l->processor, new eventloop_event ([this_w, invalid, vulnerable] () { if (auto this_l = this_w.lock ()) { this_l->settings.update_locked (invalid, vulnerable); } })); } }; settings_button->setToolTip (""Unlock wallet, set password, change representative""); } void rai_qt::wallet::refresh () { { rai::transaction transaction (wallet_m->store.environment, nullptr, false); assert (wallet_m->store.exists (transaction, account)); } self.account_text->setText (QString (account.to_account_split ().c_str ())); self.refresh_balance (); accounts.refresh (); history.refresh (); account_viewer.history.refresh (); settings.refresh_representative (); } void rai_qt::wallet::update_connected () { if (node.peers.empty ()) { active_status.insert (rai_qt::status_types::disconnected); } else { active_status.erase (rai_qt::status_types::disconnected); } } void rai_qt::wallet::empty_password () { rai::raw_key empty; empty.data.clear (); wallet_m->store.password.value_set (empty); } void rai_qt::wallet::change_rendering_ratio (rai::uint128_t const & rendering_ratio_a) { application.postEvent (&processor, new eventloop_event ([this, rendering_ratio_a] () { this->rendering_ratio = rendering_ratio_a; this->refresh (); })); } void rai_qt::wallet::push_main_stack (QWidget * widget_a) { main_stack->addWidget (widget_a); main_stack->setCurrentIndex (main_stack->count () - 1); } void rai_qt::wallet::pop_main_stack () { main_stack->removeWidget (main_stack->currentWidget ()); } rai_qt::settings::settings (rai_qt::wallet & wallet_a) : window (new QWidget), layout (new QVBoxLayout), password (new QLineEdit), lock_window (new QWidget), lock_layout (new QHBoxLayout), unlock (new QPushButton (""Unlock"")), lock (new QPushButton (""Lock"")), sep1 (new QFrame), new_password (new QLineEdit), retype_password (new QLineEdit), change (new QPushButton (""Set/Change password"")), sep2 (new QFrame), representative (new QLabel (""Account representative:"")), current_representative (new QLabel), new_representative (new QLineEdit), change_rep (new QPushButton (""Change representative"")), back (new QPushButton (""Back"")), wallet (wallet_a) { password->setPlaceholderText(""Password""); password->setEchoMode (QLineEdit::EchoMode::Password); layout->addWidget (password); layout->addWidget (lock_window); lock_layout->addWidget (unlock); lock_layout->addWidget (lock); lock_window->setLayout (lock_layout); sep1->setFrameShape (QFrame::HLine); sep1->setFrameShadow (QFrame::Sunken); layout->addWidget (sep1); new_password->setEchoMode (QLineEdit::EchoMode::Password); new_password->setPlaceholderText (""New password""); layout->addWidget (new_password); retype_password->setEchoMode (QLineEdit::EchoMode::Password); retype_password->setPlaceholderText (""Retype password""); layout->addWidget (retype_password); layout->addWidget (change); sep2->setFrameShape (QFrame::HLine); sep2->setFrameShadow (QFrame::Sunken); layout->addWidget (sep2); layout->addWidget (representative); current_representative->setTextInteractionFlags(Qt::TextSelectableByMouse); layout->addWidget (current_representative); new_representative->setPlaceholderText (rai::zero_key.pub.to_account ().c_str ()); layout->addWidget (new_representative); layout->addWidget (change_rep); layout->addStretch (); layout->addWidget (back); window->setLayout (layout); QObject::connect (change, &QPushButton::released, [this] () { rai::transaction transaction (this->wallet.wallet_m->store.environment, nullptr, true); if (this->wallet.wallet_m->store.valid_password (transaction)) { if (new_password->text ().isEmpty()) { new_password->clear (); new_password->setPlaceholderText (""Empty Password - try again: New password""); retype_password->clear (); retype_password->setPlaceholderText (""Empty Password - try again: Retype password""); } else { if (new_password->text () == retype_password->text ()) { this->wallet.wallet_m->store.rekey (transaction, std::string (new_password->text ().toLocal8Bit ())); new_password->clear (); retype_password->clear (); retype_password->setPlaceholderText (""Retype password""); show_button_success (*change); change->setText (""Password was changed""); update_locked (false, false); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_button_ok (*change); change->setText (""Set/Change password""); }); } else { retype_password->clear (); retype_password->setPlaceholderText (""Password mismatch""); } } } else { show_button_error (*change); change->setText (""Wallet is locked, unlock it""); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_button_ok (*change); change->setText (""Set/Change password""); }); } }); QObject::connect (change_rep, &QPushButton::released, [this] () { rai::account representative_l; if (!representative_l.decode_account (new_representative->text ().toStdString ())) { rai::transaction transaction (this->wallet.wallet_m->store.environment, nullptr, false); if (this->wallet.wallet_m->store.valid_password (transaction)) { change_rep->setEnabled (false); { rai::transaction transaction_l (this->wallet.wallet_m->store.environment, nullptr, true); this->wallet.wallet_m->store.representative_set (transaction_l, representative_l); } auto block (this->wallet.wallet_m->change_sync (this->wallet.account, representative_l)); change_rep->setEnabled (true); show_button_success (*change_rep); change_rep->setText (""Represenative was changed""); current_representative->setText (QString (representative_l.to_account_split ().c_str ())); new_representative->clear (); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_button_ok (*change_rep); change_rep->setText (""Change representative""); }); } else { show_button_error (*change_rep); change_rep->setText (""Wallet is locked, unlock it""); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_button_ok (*change_rep); change_rep->setText (""Change representative""); }); } } else { show_line_error (*new_representative); show_button_error (*change_rep); change_rep->setText (""Invalid account""); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_line_ok (*new_representative); show_button_ok (*change_rep); change_rep->setText (""Change representative""); }); } }); QObject::connect (back, &QPushButton::released, [this] () { assert (this->wallet.main_stack->currentWidget () == window); this->wallet.pop_main_stack (); }); QObject::connect (unlock, &QPushButton::released, [this] () { if (!this->wallet.wallet_m->enter_password (std::string (password->text ().toLocal8Bit ()))) { password->clear (); } else { show_line_error (*password); show_button_error (*unlock); unlock->setText (""Invalid password""); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_line_ok (*password); show_button_ok (*unlock); unlock->setText (""Unlock""); }); } }); QObject::connect (lock, &QPushButton::released, [this] () { if (password->text ().isEmpty()) { rai::raw_key empty; empty.data.clear (); this->wallet.wallet_m->store.password.value_set (empty); update_locked (true, true); } else { show_line_error (*password); show_button_error (*lock); lock->setText (""Error""); show_line_success (*new_password); show_button_success (*change); this->wallet.node.alarm.add (std::chrono::system_clock::now () + std::chrono::seconds (5), [this] () { show_line_ok (*password); password->clear (); show_button_ok (*lock); lock->setText (""Lock""); show_line_ok (*new_password); show_button_ok (*change); }); } }); representative->setToolTip (""In the infrequent case where the network needs to make a global decision,\\nyour wallet software performs a balance-weighted vote to determine\\nthe outcome. Since not everyone can remain online and perform this duty,\\nyour wallet names a representative that can vote with, but cannot spend,\\nyour balance.""); refresh_representative (); } void rai_qt::settings::refresh_representative () { rai::transaction transaction (this->wallet.wallet_m->node.store.environment, nullptr, false); rai::account_info info; auto error (this->wallet.wallet_m->node.store.account_get (transaction, this->wallet.account, info)); if (!error) { auto block (this->wallet.wallet_m->node.store.block_get (transaction, info.rep_block)); assert (block != nullptr); current_representative->setText (QString (block->representative ().to_account_split ().c_str ())); } else { current_representative->setText (this->wallet.wallet_m->store.representative (transaction).to_account_split ().c_str ()); } } void rai_qt::settings::activate () { this->wallet.push_main_stack (window); } void rai_qt::settings::update_locked (bool invalid, bool vulnerable) { if (invalid) { this->wallet.active_status.insert (rai_qt::status_types::locked); } else { this->wallet.active_status.erase (rai_qt::status_types::locked); } if (vulnerable) { this->wallet.active_status.insert (rai_qt::status_types::vulnerable); } else { this->wallet.active_status.erase (rai_qt::status_types::vulnerable); } } rai_qt::advanced_actions::advanced_actions (rai_qt::wallet & wallet_a) : window (new QWidget), layout (new QVBoxLayout), show_ledger (new QPushButton (""Ledger"")), show_peers (new QPushButton (""Peers"")), search_for_receivables (new QPushButton (""Search for receivables"")), bootstrap (new QPushButton (""Initiate bootstrap"")), wallet_refresh (new QPushButton (""Refresh Wallet"")), create_block (new QPushButton (""Create Block"")), enter_block (new QPushButton (""Enter Block"")), block_viewer (new QPushButton (""Block Viewer"")), account_viewer (new QPushButton (""Account Viewer"")), scale_window (new QWidget), scale_layout (new QHBoxLayout), scale_label (new QLabel (""Scale:"")), ratio_group (new QButtonGroup), mrai (new QRadioButton (""Mxrb"")), krai (new QRadioButton (""kxrb"")), rai (new QRadioButton (""xrb"")), back (new QPushButton (""Back"")), ledger_window (new QWidget), ledger_layout (new QVBoxLayout), ledger_model (new QStandardItemModel), ledger_view (new QTableView), ledger_refresh (new QPushButton (""Refresh"")), ledger_back (new QPushButton (""Back"")), peers_window (new QWidget), peers_layout (new QVBoxLayout), peers_model (new QStandardItemModel), peers_view (new QTableView), bootstrap_label (new QLabel (""IPV6:port \\""::ffff:192.168.0.1:7075\\"""")), bootstrap_line (new QLineEdit), peers_bootstrap (new QPushButton (""Initiate Bootstrap"")), peers_refresh (new QPushButton (""Refresh"")), peers_back (new QPushButton (""Back"")), wallet (wallet_a) { ratio_group->addButton (mrai); ratio_group->addButton (krai); ratio_group->addButton (rai); ratio_group->setId (mrai, 0); ratio_group->setId (krai, 1); ratio_group->setId (rai, 2); scale_layout->addWidget(scale_label); scale_layout->addWidget(mrai); scale_layout->addWidget(krai); scale_layout->addWidget(rai); scale_window->setLayout(scale_layout); ledger_model->setHorizontalHeaderItem (0, new QStandardItem (""Account"")); ledger_model->setHorizontalHeaderItem (1, new QStandardItem (""Balance"")); ledger_model->setHorizontalHeaderItem (2, new QStandardItem (""Block"")); ledger_view->setModel (ledger_model); ledger_view->setEditTriggers (QAbstractItemView::NoEditTriggers); ledger_view->verticalHeader ()->hide (); ledger_layout->addWidget (ledger_view); ledger_layout->addWidget (ledger_refresh); ledger_layout->addWidget (ledger_back); ledger_layout->setContentsMargins (0, 0, 0, 0); ledger_window->setLayout (ledger_layout); peers_model->setHorizontalHeaderItem (0, new QStandardItem (""IPv6 address:port"")); peers_model->setHorizontalHeaderItem (1, new QStandardItem (""Net version"")); peers_view->setEditTriggers (QAbstractItemView::NoEditTriggers); peers_view->verticalHeader ()->hide (); peers_view->setModel (peers_model); peers_view->setColumnWidth(0,220); peers_view->setSortingEnabled(true); peers_layout->addWidget (peers_view); peers_layout->addWidget (bootstrap_label); peers_layout->addWidget (bootstrap_line); peers_layout->addWidget (peers_bootstrap); peers_layout->addWidget (peers_refresh); peers_layout->addWidget (peers_back); peers_layout->setContentsMargins (0, 0, 0, 0); peers_window->setLayout (peers_layout); layout->addWidget (show_ledger); layout->addWidget (show_peers); layout->addWidget (search_for_receivables); layout->addWidget (bootstrap); layout->addWidget (wallet_refresh); layout->addWidget (create_block); layout->addWidget (enter_block); layout->addWidget (block_viewer); layout->addWidget (account_viewer); layout->addWidget (scale_window); layout->addStretch (); layout->addWidget (back); window->setLayout (layout); QObject::connect (mrai, &QRadioButton::toggled, [this] () { if (mrai->isChecked ()) { this->wallet.change_rendering_ratio (rai::Mxrb_ratio); } }); QObject::connect (krai, &QRadioButton::toggled, [this] () { if (krai->isChecked ()) { this->wallet.change_rendering_ratio (rai::kxrb_ratio); } }); QObject::connect (rai, &QRadioButton::toggled, [this] () { if (rai->isChecked ()) { this->wallet.change_rendering_ratio (rai::xrb_ratio); } }); mrai->click (); QObject::connect (wallet_refresh, &QPushButton::released, [this] () { this->wallet.accounts.refresh (); this->wallet.accounts.refresh_wallet_balance (); }); QObject::connect (show_peers, &QPushButton::released, [this] () { refresh_peers (); this->wallet.push_main_stack (peers_window); }); QObject::connect (show_ledger, &QPushButton::released, [this] () { this->wallet.push_main_stack (ledger_window); }); QObject::connect (back, &QPushButton::released, [this] () { this->wallet.pop_main_stack (); }); QObject::connect (peers_back, &QPushButton::released, [this] () { this->wallet.pop_main_stack (); }); QObject::connect (peers_bootstrap, &QPushButton::released, [this] () { rai::endpoint endpoint; auto error (rai::parse_endpoint (bootstrap_line->text ().toStdString (), endpoint)); if (!error) { show_line_ok (*bootstrap_line); bootstrap_line->clear (); this->wallet.node.bootstrap_initiator.bootstrap (endpoint); } else { show_line_error (*bootstrap_line); } }); QObject::connect (peers_refresh, &QPushButton::released, [this] () { refresh_peers (); }); QObject::connect (ledger_refresh, &QPushButton::released, [this] () { refresh_ledger (); }); QObject::connect (ledger_back, &QPushButton::released, [this] () { this->wallet.pop_main_stack (); }); QObject::connect (search_for_receivables, &QPushButton::released, [this] () { this->wallet.wallet_m->search_pending (); }); QObject::connect (bootstrap, &QPushButton::released, [this] () { this->wallet.node.bootstrap_initiator.bootstrap (); }); QObject::connect (create_block, &QPushButton::released, [this] () { this->wallet.push_main_stack (this->wallet.block_creation.window); }); QObject::connect (enter_block, &QPushButton::released, [this] () { this->wallet.push_main_stack (this->wallet.block_entry.window); }); QObject::connect (block_viewer, &QPushButton::released, [this] () { this->wallet.push_main_stack (this->wallet.block_viewer.window); }); QObject::connect (account_viewer, &QPushButton::released, [this] () { this->wallet.push_main_stack (this->wallet.account_viewer.window); }); bootstrap->setToolTip (""Multi-connection bootstrap to random peers""); search_for_receivables->setToolTip (""Search for pending blocks""); create_block->setToolTip (""Create block in JSON format""); enter_block->setToolTip (""Enter block in JSON format""); } void rai_qt::advanced_actions::refresh_peers () { peers_model->removeRows (0, peers_model->rowCount ()); auto list (wallet.node.peers.list_version ()); for (auto i (list.begin ()), n (list.end ()); i != n; ++i) { std::stringstream endpoint; endpoint << i->first.address ().to_string (); endpoint << ':'; endpoint << i->first.port (); QString qendpoint (endpoint.str().c_str ()); QList items; items.push_back (new QStandardItem (qendpoint)); items.push_back (new QStandardItem (QString (std::to_string (i->second).c_str ()))); peers_model->appendRow (items); } } void rai_qt::advanced_actions::refresh_ledger () { ledger_model->removeRows (0, ledger_model->rowCount ()); rai::transaction transaction (wallet.node.store.environment, nullptr, false); for (auto i (wallet.node.ledger.store.latest_begin (transaction)), j (wallet.node.ledger.store.latest_end ()); i != j; ++i) { QList items; items.push_back (new QStandardItem (QString (rai::block_hash (i->first).to_account ().c_str ()))); rai::account_info info (i->second); std::string balance; rai::amount (info.balance.number () / wallet.rendering_ratio).encode_dec (balance); items.push_back (new QStandardItem (QString (balance.c_str ()))); std::string block_hash; info.head.encode_hex (block_hash); items.push_back (new QStandardItem (QString (block_hash.c_str ()))); ledger_model->appendRow (items); } } rai_qt::block_entry::block_entry (rai_qt::wallet & wallet_a) : window (new QWidget), layout (new QVBoxLayout), block (new QPlainTextEdit), status (new QLabel), process (new QPushButton (""Process"")), back (new QPushButton (""Back"")), wallet (wallet_a) { layout->addWidget (block); layout->addWidget (status); layout->addWidget (process); layout->addWidget (back); window->setLayout (layout); QObject::connect (process, &QPushButton::released, [this] () { auto string (block->toPlainText ().toStdString ()); try { boost::property_tree::ptree tree; std::stringstream istream (string); boost::property_tree::read_json (istream, tree); auto block_l (rai::deserialize_block_json (tree)); if (block_l != nullptr) { show_label_ok (*status); this->status->setText (""""); this->wallet.node.process_receive_republish (std::move (block_l)); } else { show_label_error (*status); this->status->setText (""Unable to parse block""); } } catch (std::runtime_error const &) { show_label_error (*status); this->status->setText (""Unable to parse block""); } }); QObject::connect (back, &QPushButton::released, [this] () { this->wallet.pop_main_stack (); }); } rai_qt::block_creation::block_creation (rai_qt::wallet & wallet_a) : window (new QWidget), layout (new QVBoxLayout), group (new QButtonGroup), button_layout (new QHBoxLayout), send (new QRadioButton (""Send"")), receive (new QRadioButton (""Receive"")), change (new QRadioButton (""Change"")), open (new QRadioButton (""Open"")), account_label (new QLabel (""Account:"")), account (new QLineEdit), source_label (new QLabel (""Source:"")), source (new QLineEdit), amount_label (new QLabel (""Amount:"")), amount (new QLineEdit), destination_label (new QLabel (""Destination:"")), destination (new QLineEdit), representative_label (new QLabel (""Representative:"")), representative (new QLineEdit), block (new QPlainTextEdit), status (new QLabel), create (new QPushButton (""Create"")), back (new QPushButton (""Back"")), wallet (wallet_a) { group->addButton (send); group->addButton (receive); group->addButton (change); group->addButton (open); group->setId (send, 0); group->setId (receive, 1); group->setId (change, 2); group->setId (open, 3); button_layout->addWidget (send); button_layout->addWidget (receive); button_layout->addWidget (open); button_layout->addWidget (change); layout->addLayout (button_layout); layout->addWidget (account_label); layout->addWidget (account); layout->addWidget (source_label); layout->addWidget (source); layout->addWidget (amount_label); layout->addWidget (amount); layout->addWidget (destination_label); layout->addWidget (destination); layout->addWidget (representative_label); layout->addWidget (representative); layout->addWidget (block); layout->addWidget (status); layout->addWidget (create); layout->addWidget (back); window->setLayout (layout); QObject::connect (send, &QRadioButton::toggled, [this] () { if (send->isChecked ()) { deactivate_all (); activate_send (); } }); QObject::connect (receive, &QRadioButton::toggled, [this] () { if (receive->isChecked ()) { deactivate_all (); activate_receive (); } }); QObject::connect (open, &QRadioButton::toggled, [this] () { if (open->isChecked ()) { deactivate_all (); activate_open (); } }); QObject::connect (change, &QRadioButton::toggled, [this] () { if (change->isChecked ()) { deactivate_all (); activate_change (); } }); QObject::connect (create, &QPushButton::released, [this] () { switch (group->checkedId ()) { case 0: create_send (); break; case 1: create_receive (); break; case 2: create_change (); break; case 3: create_open (); break; default: assert (false); break; } }); QObject::connect (back, &QPushButton::released, [this] () { this->wallet.pop_main_stack (); }); send->click (); } void rai_qt::block_creation::deactivate_all () { account_label->hide (); account->hide (); source_label->hide (); source->hide (); amount_label->hide (); amount->hide (); destination_label->hide (); destination->hide (); representative_label->hide (); representative->hide (); } void rai_qt::block_creation::activate_send () { account_label->show (); account->show (); amount_label->show (); amount->show (); destination_label->show (); destination->show (); } void rai_qt::block_creation::activate_receive () { source_label->show (); source->show (); } void rai_qt::block_creation::activate_open () { source_label->show (); source->show (); representative_label->show (); representative->show (); } void rai_qt::block_creation::activate_change () { account_label->show (); account->show (); representative_label->show (); representative->show (); } void rai_qt::block_creation::create_send () { rai::account account_l; auto error (account_l.decode_account (account->text ().toStdString ())); if (!error) { rai::amount amount_l; error = amount_l.decode_dec (amount->text ().toStdString ()); if (!error) { rai::account destination_l; error = destination_l.decode_account (destination->text ().toStdString ()); if (!error) { rai::transaction transaction (wallet.node.store.environment, nullptr, false); rai::raw_key key; if (!wallet.wallet_m->store.fetch (transaction, account_l, key)) { auto balance (wallet.node.ledger.account_balance (transaction, account_l)); if (amount_l.number () <= balance) { rai::account_info info; auto error (wallet.node.store.account_get (transaction, account_l, info)); assert (!error); rai::send_block send (info.head, destination_l, balance - amount_l.number (), key, account_l, wallet.wallet_m->work_fetch (transaction, account_l, info.head)); std::string block_l; send.serialize_json (block_l); block->setPlainText (QString (block_l.c_str ())); show_label_ok (*status); status->setText (""Created block""); } else { show_label_error (*status); status->setText (""Insufficient balance""); } } else { show_label_error (*status); status->setText (""Account is not in wallet""); } } else { show_label_error (*status); status->setText (""Unable to decode destination""); } } else { show_label_error (*status); status->setText (""Unable to decode amount""); } } else { show_label_error (*status); status->setText (""Unable to decode account""); } } void rai_qt::block_creation::create_receive () { rai::block_hash source_l; auto error (source_l.decode_hex (source->text ().toStdString ())); if (!error) { rai::transaction transaction (wallet.node.store.environment, nullptr, false); auto block_l (wallet.node.store.block_get (transaction, source_l)); if (block_l != nullptr) { auto send_block (dynamic_cast (block_l.get ())); if (send_block != nullptr) { rai::pending_key pending_key (send_block->hashables.destination, source_l); rai::pending_info pending; if (!wallet.node.store.pending_get (transaction, pending_key, pending)) { rai::account_info info; auto error (wallet.node.store.account_get (transaction, pending_key.account, info)); if (!error) { rai::raw_key key; auto error (wallet.wallet_m->store.fetch (transaction, pending_key.account, key)); if (!error) { rai::receive_block receive (info.head, source_l, key, pending_key.account, wallet.wallet_m->work_fetch (transaction, pending_key.account, info.head)); std::string block_l; receive.serialize_json (block_l); block->setPlainText (QString (block_l.c_str ())); show_label_ok (*status); status->setText (""Created block""); } else { show_label_error (*status); status->setText (""Account is not in wallet""); } } else { show_label_error (*status); status->setText (""Account not yet open""); } } else { show_label_error (*status); status->setText (""Source block is not pending to receive""); } } else { show_label_error (*status); status->setText(""Source is not a send block""); } } else { show_label_error (*status); status->setText(""Source block not found""); } } else { show_label_error (*status); status->setText (""Unable to decode source""); } } void rai_qt::block_creation::create_change () { rai::account account_l; auto error (account_l.decode_account (account->text ().toStdString ())); if (!error) { rai::account representative_l; error = representative_l.decode_account (representative->text ().toStdString ()); if (!error) { rai::transaction transaction (wallet.node.store.environment, nullptr, false); rai::account_info info; auto error (wallet.node.store.account_get (transaction, account_l, info)); if (!error) { rai::raw_key key; auto error (wallet.wallet_m->store.fetch (transaction, account_l, key)); if (!error) { rai::change_block change (info.head, representative_l, key, account_l, wallet.wallet_m->work_fetch (transaction, account_l, info.head)); std::string block_l; change.serialize_json (block_l); block->setPlainText (QString (block_l.c_str ())); show_label_ok (*status); status->setText (""Created block""); } else { show_label_error (*status); status->setText (""Account is not in wallet""); } } else { show_label_error (*status); status->setText (""Account not yet open""); } } else { show_label_error (*status); status->setText (""Unable to decode representative""); } } else { show_label_error (*status); status->setText (""Unable to decode account""); } } void rai_qt::block_creation::create_open () { rai::block_hash source_l; auto error (source_l.decode_hex (source->text ().toStdString ())); if (!error) { rai::account representative_l; error = representative_l.decode_account (representative->text ().toStdString ()); if (!error) { rai::transaction transaction (wallet.node.store.environment, nullptr, false); auto block_l (wallet.node.store.block_get (transaction, source_l)); if (block_l != nullptr) { auto send_block (dynamic_cast (block_l.get ())); if (send_block != nullptr) { rai::pending_key pending_key (send_block->hashables.destination, source_l); rai::pending_info pending; if (!wallet.node.store.pending_get (transaction, pending_key, pending)) { rai::account_info info; auto error (wallet.node.store.account_get (transaction, pending_key.account, info)); if (error) { rai::raw_key key; auto error (wallet.wallet_m->store.fetch (transaction, pending_key.account, key)); if (!error) { rai::open_block open (source_l, representative_l, pending_key.account, key, pending_key.account, wallet.wallet_m->work_fetch (transaction, pending_key.account, pending_key.account)); std::string block_l; open.serialize_json (block_l); block->setPlainText (QString (block_l.c_str ())); show_label_ok (*status); status->setText (""Created block""); } else { show_label_error (*status); status->setText (""Account is not in wallet""); } } else { show_label_error (*status); status->setText (""Account already open""); } } else { show_label_error (*status); status->setText (""Source block is not pending to receive""); } } else { show_label_error (*status); status->setText(""Source is not a send block""); } } else { show_label_error (*status); status->setText(""Source block not found""); } } else { show_label_error (*status); status->setText (""Unable to decode representative""); } } else { show_label_error (*status); status->setText (""Unable to decode source""); } } ",16175,True,3328.009401123399,median "//===-- msan_interceptors.cpp ---------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file is a part of MemorySanitizer. // // Interceptors for standard library functions. // // FIXME: move as many interceptors as possible into // sanitizer_common/sanitizer_common_interceptors.h //===----------------------------------------------------------------------===// #include ""interception/interception.h"" #include ""msan.h"" #include ""msan_chained_origin_depot.h"" #include ""msan_origin.h"" #include ""msan_report.h"" #include ""msan_thread.h"" #include ""msan_poisoning.h"" #include ""sanitizer_common/sanitizer_platform_limits_posix.h"" #include ""sanitizer_common/sanitizer_platform_limits_netbsd.h"" #include ""sanitizer_common/sanitizer_allocator.h"" #include ""sanitizer_common/sanitizer_allocator_interface.h"" #include ""sanitizer_common/sanitizer_allocator_internal.h"" #include ""sanitizer_common/sanitizer_atomic.h"" #include ""sanitizer_common/sanitizer_common.h"" #include ""sanitizer_common/sanitizer_errno.h"" #include ""sanitizer_common/sanitizer_stackdepot.h"" #include ""sanitizer_common/sanitizer_libc.h"" #include ""sanitizer_common/sanitizer_linux.h"" #include ""sanitizer_common/sanitizer_tls_get_addr.h"" #include ""sanitizer_common/sanitizer_vector.h"" #if SANITIZER_NETBSD #define fstat __fstat50 #define gettimeofday __gettimeofday50 #define getrusage __getrusage50 #define tzset __tzset50 #endif #include // ACHTUNG! No other system header includes in this file. // Ideally, we should get rid of stdarg.h as well. using namespace __msan; using __sanitizer::memory_order; using __sanitizer::atomic_load; using __sanitizer::atomic_store; using __sanitizer::atomic_uintptr_t; DECLARE_REAL(SIZE_T, strlen, const char *s) DECLARE_REAL(SIZE_T, strnlen, const char *s, SIZE_T maxlen) DECLARE_REAL(void *, memcpy, void *dest, const void *src, uptr n) DECLARE_REAL(void *, memset, void *dest, int c, uptr n) // True if this is a nested interceptor. static THREADLOCAL int in_interceptor_scope; void __msan_scoped_disable_interceptor_checks() { ++in_interceptor_scope; } void __msan_scoped_enable_interceptor_checks() { --in_interceptor_scope; } struct InterceptorScope { InterceptorScope() { ++in_interceptor_scope; } ~InterceptorScope() { --in_interceptor_scope; } }; bool IsInInterceptorScope() { return in_interceptor_scope; } static uptr allocated_for_dlsym; static const uptr kDlsymAllocPoolSize = 1024; static uptr alloc_memory_for_dlsym[kDlsymAllocPoolSize]; static bool IsInDlsymAllocPool(const void *ptr) { uptr off = (uptr)ptr - (uptr)alloc_memory_for_dlsym; return off < sizeof(alloc_memory_for_dlsym); } static void *AllocateFromLocalPool(uptr size_in_bytes) { uptr size_in_words = RoundUpTo(size_in_bytes, kWordSize) / kWordSize; void *mem = (void *)&alloc_memory_for_dlsym[allocated_for_dlsym]; allocated_for_dlsym += size_in_words; CHECK_LT(allocated_for_dlsym, kDlsymAllocPoolSize); return mem; } #define ENSURE_MSAN_INITED() do { \\ CHECK(!msan_init_is_running); \\ if (!msan_inited) { \\ __msan_init(); \\ } \\ } while (0) // Check that [x, x+n) range is unpoisoned. #define CHECK_UNPOISONED_0(x, n) \\ do { \\ sptr __offset = __msan_test_shadow(x, n); \\ if (__msan::IsInSymbolizer()) break; \\ if (__offset >= 0 && __msan::flags()->report_umrs) { \\ GET_CALLER_PC_BP_SP; \\ (void)sp; \\ ReportUMRInsideAddressRange(__func__, x, n, __offset); \\ __msan::PrintWarningWithOrigin( \\ pc, bp, __msan_get_origin((const char *)x + __offset)); \\ if (__msan::flags()->halt_on_error) { \\ Printf(""Exiting\\n""); \\ Die(); \\ } \\ } \\ } while (0) // Check that [x, x+n) range is unpoisoned unless we are in a nested // interceptor. #define CHECK_UNPOISONED(x, n) \\ do { \\ if (!IsInInterceptorScope()) CHECK_UNPOISONED_0(x, n); \\ } while (0) #define CHECK_UNPOISONED_STRING_OF_LEN(x, len, n) \\ CHECK_UNPOISONED((x), \\ common_flags()->strict_string_checks ? (len) + 1 : (n) ) #define CHECK_UNPOISONED_STRING(x, n) \\ CHECK_UNPOISONED_STRING_OF_LEN((x), internal_strlen(x), (n)) #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(SIZE_T, fread_unlocked, void *ptr, SIZE_T size, SIZE_T nmemb, void *file) { ENSURE_MSAN_INITED(); SIZE_T res = REAL(fread_unlocked)(ptr, size, nmemb, file); if (res > 0) __msan_unpoison(ptr, res *size); return res; } #define MSAN_MAYBE_INTERCEPT_FREAD_UNLOCKED INTERCEPT_FUNCTION(fread_unlocked) #else #define MSAN_MAYBE_INTERCEPT_FREAD_UNLOCKED #endif #if !SANITIZER_NETBSD INTERCEPTOR(void *, mempcpy, void *dest, const void *src, SIZE_T n) { return (char *)__msan_memcpy(dest, src, n) + n; } #define MSAN_MAYBE_INTERCEPT_MEMPCPY INTERCEPT_FUNCTION(mempcpy) #else #define MSAN_MAYBE_INTERCEPT_MEMPCPY #endif INTERCEPTOR(void *, memccpy, void *dest, const void *src, int c, SIZE_T n) { ENSURE_MSAN_INITED(); void *res = REAL(memccpy)(dest, src, c, n); CHECK(!res || (res >= dest && res <= (char *)dest + n)); SIZE_T sz = res ? (char *)res - (char *)dest : n; CHECK_UNPOISONED(src, sz); __msan_unpoison(dest, sz); return res; } INTERCEPTOR(void *, bcopy, const void *src, void *dest, SIZE_T n) { return __msan_memmove(dest, src, n); } INTERCEPTOR(int, posix_memalign, void **memptr, SIZE_T alignment, SIZE_T size) { GET_MALLOC_STACK_TRACE; CHECK_NE(memptr, 0); int res = msan_posix_memalign(memptr, alignment, size, &stack); if (!res) __msan_unpoison(memptr, sizeof(*memptr)); return res; } #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(void *, memalign, SIZE_T alignment, SIZE_T size) { GET_MALLOC_STACK_TRACE; return msan_memalign(alignment, size, &stack); } #define MSAN_MAYBE_INTERCEPT_MEMALIGN INTERCEPT_FUNCTION(memalign) #else #define MSAN_MAYBE_INTERCEPT_MEMALIGN #endif INTERCEPTOR(void *, aligned_alloc, SIZE_T alignment, SIZE_T size) { GET_MALLOC_STACK_TRACE; return msan_aligned_alloc(alignment, size, &stack); } #if !SANITIZER_NETBSD INTERCEPTOR(void *, __libc_memalign, SIZE_T alignment, SIZE_T size) { GET_MALLOC_STACK_TRACE; void *ptr = msan_memalign(alignment, size, &stack); if (ptr) DTLS_on_libc_memalign(ptr, size); return ptr; } #define MSAN_MAYBE_INTERCEPT___LIBC_MEMALIGN INTERCEPT_FUNCTION(__libc_memalign) #else #define MSAN_MAYBE_INTERCEPT___LIBC_MEMALIGN #endif INTERCEPTOR(void *, valloc, SIZE_T size) { GET_MALLOC_STACK_TRACE; return msan_valloc(size, &stack); } #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(void *, pvalloc, SIZE_T size) { GET_MALLOC_STACK_TRACE; return msan_pvalloc(size, &stack); } #define MSAN_MAYBE_INTERCEPT_PVALLOC INTERCEPT_FUNCTION(pvalloc) #else #define MSAN_MAYBE_INTERCEPT_PVALLOC #endif INTERCEPTOR(void, free, void *ptr) { GET_MALLOC_STACK_TRACE; if (!ptr || UNLIKELY(IsInDlsymAllocPool(ptr))) return; MsanDeallocate(&stack, ptr); } #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(void, cfree, void *ptr) { GET_MALLOC_STACK_TRACE; if (!ptr || UNLIKELY(IsInDlsymAllocPool(ptr))) return; MsanDeallocate(&stack, ptr); } #define MSAN_MAYBE_INTERCEPT_CFREE INTERCEPT_FUNCTION(cfree) #else #define MSAN_MAYBE_INTERCEPT_CFREE #endif #if !SANITIZER_NETBSD INTERCEPTOR(uptr, malloc_usable_size, void *ptr) { return __sanitizer_get_allocated_size(ptr); } #define MSAN_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE \\ INTERCEPT_FUNCTION(malloc_usable_size) #else #define MSAN_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE #endif #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD // This function actually returns a struct by value, but we can't unpoison a // temporary! The following is equivalent on all supported platforms but // aarch64 (which uses a different register for sret value). We have a test // to confirm that. INTERCEPTOR(void, mallinfo, __sanitizer_struct_mallinfo *sret) { #ifdef __aarch64__ uptr r8; asm volatile(""mov %0,x8"" : ""=r"" (r8)); sret = reinterpret_cast<__sanitizer_struct_mallinfo*>(r8); #endif REAL(memset)(sret, 0, sizeof(*sret)); __msan_unpoison(sret, sizeof(*sret)); } #define MSAN_MAYBE_INTERCEPT_MALLINFO INTERCEPT_FUNCTION(mallinfo) #else #define MSAN_MAYBE_INTERCEPT_MALLINFO #endif #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(int, mallopt, int cmd, int value) { return 0; } #define MSAN_MAYBE_INTERCEPT_MALLOPT INTERCEPT_FUNCTION(mallopt) #else #define MSAN_MAYBE_INTERCEPT_MALLOPT #endif #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(void, malloc_stats, void) { // FIXME: implement, but don't call REAL(malloc_stats)! } #define MSAN_MAYBE_INTERCEPT_MALLOC_STATS INTERCEPT_FUNCTION(malloc_stats) #else #define MSAN_MAYBE_INTERCEPT_MALLOC_STATS #endif INTERCEPTOR(char *, strcpy, char *dest, const char *src) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; SIZE_T n = REAL(strlen)(src); CHECK_UNPOISONED_STRING(src + n, 0); char *res = REAL(strcpy)(dest, src); CopyShadowAndOrigin(dest, src, n + 1, &stack); return res; } INTERCEPTOR(char *, strncpy, char *dest, const char *src, SIZE_T n) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; SIZE_T copy_size = REAL(strnlen)(src, n); if (copy_size < n) copy_size++; // trailing \\0 char *res = REAL(strncpy)(dest, src, n); CopyShadowAndOrigin(dest, src, copy_size, &stack); __msan_unpoison(dest + copy_size, n - copy_size); return res; } #if !SANITIZER_NETBSD INTERCEPTOR(char *, stpcpy, char *dest, const char *src) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; SIZE_T n = REAL(strlen)(src); CHECK_UNPOISONED_STRING(src + n, 0); char *res = REAL(stpcpy)(dest, src); CopyShadowAndOrigin(dest, src, n + 1, &stack); return res; } #define MSAN_MAYBE_INTERCEPT_STPCPY INTERCEPT_FUNCTION(stpcpy) #else #define MSAN_MAYBE_INTERCEPT_STPCPY #endif INTERCEPTOR(char *, strdup, char *src) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; // On FreeBSD strdup() leverages strlen(). InterceptorScope interceptor_scope; SIZE_T n = REAL(strlen)(src); CHECK_UNPOISONED_STRING(src + n, 0); char *res = REAL(strdup)(src); CopyShadowAndOrigin(res, src, n + 1, &stack); return res; } #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(char *, __strdup, char *src) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; SIZE_T n = REAL(strlen)(src); CHECK_UNPOISONED_STRING(src + n, 0); char *res = REAL(__strdup)(src); CopyShadowAndOrigin(res, src, n + 1, &stack); return res; } #define MSAN_MAYBE_INTERCEPT___STRDUP INTERCEPT_FUNCTION(__strdup) #else #define MSAN_MAYBE_INTERCEPT___STRDUP #endif #if !SANITIZER_NETBSD INTERCEPTOR(char *, gcvt, double number, SIZE_T ndigit, char *buf) { ENSURE_MSAN_INITED(); char *res = REAL(gcvt)(number, ndigit, buf); SIZE_T n = REAL(strlen)(buf); __msan_unpoison(buf, n + 1); return res; } #define MSAN_MAYBE_INTERCEPT_GCVT INTERCEPT_FUNCTION(gcvt) #else #define MSAN_MAYBE_INTERCEPT_GCVT #endif INTERCEPTOR(char *, strcat, char *dest, const char *src) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; SIZE_T src_size = REAL(strlen)(src); SIZE_T dest_size = REAL(strlen)(dest); CHECK_UNPOISONED_STRING(src + src_size, 0); CHECK_UNPOISONED_STRING(dest + dest_size, 0); char *res = REAL(strcat)(dest, src); CopyShadowAndOrigin(dest + dest_size, src, src_size + 1, &stack); return res; } INTERCEPTOR(char *, strncat, char *dest, const char *src, SIZE_T n) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; SIZE_T dest_size = REAL(strlen)(dest); SIZE_T copy_size = REAL(strnlen)(src, n); CHECK_UNPOISONED_STRING(dest + dest_size, 0); char *res = REAL(strncat)(dest, src, n); CopyShadowAndOrigin(dest + dest_size, src, copy_size, &stack); __msan_unpoison(dest + dest_size + copy_size, 1); // \\0 return res; } // Hack: always pass nptr and endptr as part of __VA_ARGS_ to avoid having to // deal with empty __VA_ARGS__ in the case of INTERCEPTOR_STRTO. #define INTERCEPTOR_STRTO_BODY(ret_type, func, ...) \\ ENSURE_MSAN_INITED(); \\ ret_type res = REAL(func)(__VA_ARGS__); \\ __msan_unpoison(endptr, sizeof(*endptr)); \\ return res; #define INTERCEPTOR_STRTO(ret_type, func, char_type) \\ INTERCEPTOR(ret_type, func, const char_type *nptr, char_type **endptr) { \\ INTERCEPTOR_STRTO_BODY(ret_type, func, nptr, endptr); \\ } #define INTERCEPTOR_STRTO_BASE(ret_type, func, char_type) \\ INTERCEPTOR(ret_type, func, const char_type *nptr, char_type **endptr, \\ int base) { \\ INTERCEPTOR_STRTO_BODY(ret_type, func, nptr, endptr, base); \\ } #define INTERCEPTOR_STRTO_LOC(ret_type, func, char_type) \\ INTERCEPTOR(ret_type, func, const char_type *nptr, char_type **endptr, \\ void *loc) { \\ INTERCEPTOR_STRTO_BODY(ret_type, func, nptr, endptr, loc); \\ } #define INTERCEPTOR_STRTO_BASE_LOC(ret_type, func, char_type) \\ INTERCEPTOR(ret_type, func, const char_type *nptr, char_type **endptr, \\ int base, void *loc) { \\ INTERCEPTOR_STRTO_BODY(ret_type, func, nptr, endptr, base, loc); \\ } #if SANITIZER_NETBSD #define INTERCEPTORS_STRTO(ret_type, func, char_type) \\ INTERCEPTOR_STRTO(ret_type, func, char_type) \\ INTERCEPTOR_STRTO_LOC(ret_type, func##_l, char_type) #define INTERCEPTORS_STRTO_BASE(ret_type, func, char_type) \\ INTERCEPTOR_STRTO_BASE(ret_type, func, char_type) \\ INTERCEPTOR_STRTO_BASE_LOC(ret_type, func##_l, char_type) #else #define INTERCEPTORS_STRTO(ret_type, func, char_type) \\ INTERCEPTOR_STRTO(ret_type, func, char_type) \\ INTERCEPTOR_STRTO_LOC(ret_type, func##_l, char_type) \\ INTERCEPTOR_STRTO_LOC(ret_type, __##func##_l, char_type) \\ INTERCEPTOR_STRTO_LOC(ret_type, __##func##_internal, char_type) #define INTERCEPTORS_STRTO_BASE(ret_type, func, char_type) \\ INTERCEPTOR_STRTO_BASE(ret_type, func, char_type) \\ INTERCEPTOR_STRTO_BASE_LOC(ret_type, func##_l, char_type) \\ INTERCEPTOR_STRTO_BASE_LOC(ret_type, __##func##_l, char_type) \\ INTERCEPTOR_STRTO_BASE_LOC(ret_type, __##func##_internal, char_type) #endif INTERCEPTORS_STRTO(double, strtod, char) INTERCEPTORS_STRTO(float, strtof, char) INTERCEPTORS_STRTO(long double, strtold, char) INTERCEPTORS_STRTO_BASE(long, strtol, char) INTERCEPTORS_STRTO_BASE(long long, strtoll, char) INTERCEPTORS_STRTO_BASE(unsigned long, strtoul, char) INTERCEPTORS_STRTO_BASE(unsigned long long, strtoull, char) INTERCEPTORS_STRTO_BASE(u64, strtouq, char) INTERCEPTORS_STRTO(double, wcstod, wchar_t) INTERCEPTORS_STRTO(float, wcstof, wchar_t) INTERCEPTORS_STRTO(long double, wcstold, wchar_t) INTERCEPTORS_STRTO_BASE(long, wcstol, wchar_t) INTERCEPTORS_STRTO_BASE(long long, wcstoll, wchar_t) INTERCEPTORS_STRTO_BASE(unsigned long, wcstoul, wchar_t) INTERCEPTORS_STRTO_BASE(unsigned long long, wcstoull, wchar_t) #if SANITIZER_NETBSD #define INTERCEPT_STRTO(func) \\ INTERCEPT_FUNCTION(func); \\ INTERCEPT_FUNCTION(func##_l); #else #define INTERCEPT_STRTO(func) \\ INTERCEPT_FUNCTION(func); \\ INTERCEPT_FUNCTION(func##_l); \\ INTERCEPT_FUNCTION(__##func##_l); \\ INTERCEPT_FUNCTION(__##func##_internal); #endif // FIXME: support *wprintf in common format interceptors. INTERCEPTOR(int, vswprintf, void *str, uptr size, void *format, va_list ap) { ENSURE_MSAN_INITED(); int res = REAL(vswprintf)(str, size, format, ap); if (res >= 0) { __msan_unpoison(str, 4 * (res + 1)); } return res; } INTERCEPTOR(int, swprintf, void *str, uptr size, void *format, ...) { ENSURE_MSAN_INITED(); va_list ap; va_start(ap, format); int res = vswprintf(str, size, format, ap); va_end(ap); return res; } #define INTERCEPTOR_STRFTIME_BODY(char_type, ret_type, func, s, ...) \\ ENSURE_MSAN_INITED(); \\ InterceptorScope interceptor_scope; \\ ret_type res = REAL(func)(s, __VA_ARGS__); \\ if (s) __msan_unpoison(s, sizeof(char_type) * (res + 1)); \\ return res; INTERCEPTOR(SIZE_T, strftime, char *s, SIZE_T max, const char *format, __sanitizer_tm *tm) { INTERCEPTOR_STRFTIME_BODY(char, SIZE_T, strftime, s, max, format, tm); } INTERCEPTOR(SIZE_T, strftime_l, char *s, SIZE_T max, const char *format, __sanitizer_tm *tm, void *loc) { INTERCEPTOR_STRFTIME_BODY(char, SIZE_T, strftime_l, s, max, format, tm, loc); } #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(SIZE_T, __strftime_l, char *s, SIZE_T max, const char *format, __sanitizer_tm *tm, void *loc) { INTERCEPTOR_STRFTIME_BODY(char, SIZE_T, __strftime_l, s, max, format, tm, loc); } #define MSAN_MAYBE_INTERCEPT___STRFTIME_L INTERCEPT_FUNCTION(__strftime_l) #else #define MSAN_MAYBE_INTERCEPT___STRFTIME_L #endif INTERCEPTOR(SIZE_T, wcsftime, wchar_t *s, SIZE_T max, const wchar_t *format, __sanitizer_tm *tm) { INTERCEPTOR_STRFTIME_BODY(wchar_t, SIZE_T, wcsftime, s, max, format, tm); } INTERCEPTOR(SIZE_T, wcsftime_l, wchar_t *s, SIZE_T max, const wchar_t *format, __sanitizer_tm *tm, void *loc) { INTERCEPTOR_STRFTIME_BODY(wchar_t, SIZE_T, wcsftime_l, s, max, format, tm, loc); } #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(SIZE_T, __wcsftime_l, wchar_t *s, SIZE_T max, const wchar_t *format, __sanitizer_tm *tm, void *loc) { INTERCEPTOR_STRFTIME_BODY(wchar_t, SIZE_T, __wcsftime_l, s, max, format, tm, loc); } #define MSAN_MAYBE_INTERCEPT___WCSFTIME_L INTERCEPT_FUNCTION(__wcsftime_l) #else #define MSAN_MAYBE_INTERCEPT___WCSFTIME_L #endif INTERCEPTOR(int, mbtowc, wchar_t *dest, const char *src, SIZE_T n) { ENSURE_MSAN_INITED(); int res = REAL(mbtowc)(dest, src, n); if (res != -1 && dest) __msan_unpoison(dest, sizeof(wchar_t)); return res; } INTERCEPTOR(SIZE_T, mbrtowc, wchar_t *dest, const char *src, SIZE_T n, void *ps) { ENSURE_MSAN_INITED(); SIZE_T res = REAL(mbrtowc)(dest, src, n, ps); if (res != (SIZE_T)-1 && dest) __msan_unpoison(dest, sizeof(wchar_t)); return res; } // wchar_t *wmemcpy(wchar_t *dest, const wchar_t *src, SIZE_T n); INTERCEPTOR(wchar_t *, wmemcpy, wchar_t *dest, const wchar_t *src, SIZE_T n) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; wchar_t *res = REAL(wmemcpy)(dest, src, n); CopyShadowAndOrigin(dest, src, n * sizeof(wchar_t), &stack); return res; } #if !SANITIZER_NETBSD INTERCEPTOR(wchar_t *, wmempcpy, wchar_t *dest, const wchar_t *src, SIZE_T n) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; wchar_t *res = REAL(wmempcpy)(dest, src, n); CopyShadowAndOrigin(dest, src, n * sizeof(wchar_t), &stack); return res; } #define MSAN_MAYBE_INTERCEPT_WMEMPCPY INTERCEPT_FUNCTION(wmempcpy) #else #define MSAN_MAYBE_INTERCEPT_WMEMPCPY #endif INTERCEPTOR(wchar_t *, wmemset, wchar_t *s, wchar_t c, SIZE_T n) { CHECK(MEM_IS_APP(s)); ENSURE_MSAN_INITED(); wchar_t *res = REAL(wmemset)(s, c, n); __msan_unpoison(s, n * sizeof(wchar_t)); return res; } INTERCEPTOR(wchar_t *, wmemmove, wchar_t *dest, const wchar_t *src, SIZE_T n) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; wchar_t *res = REAL(wmemmove)(dest, src, n); MoveShadowAndOrigin(dest, src, n * sizeof(wchar_t), &stack); return res; } INTERCEPTOR(int, wcscmp, const wchar_t *s1, const wchar_t *s2) { ENSURE_MSAN_INITED(); int res = REAL(wcscmp)(s1, s2); return res; } INTERCEPTOR(int, gettimeofday, void *tv, void *tz) { ENSURE_MSAN_INITED(); int res = REAL(gettimeofday)(tv, tz); if (tv) __msan_unpoison(tv, 16); if (tz) __msan_unpoison(tz, 8); return res; } #if !SANITIZER_NETBSD INTERCEPTOR(char *, fcvt, double x, int a, int *b, int *c) { ENSURE_MSAN_INITED(); char *res = REAL(fcvt)(x, a, b, c); __msan_unpoison(b, sizeof(*b)); __msan_unpoison(c, sizeof(*c)); if (res) __msan_unpoison(res, REAL(strlen)(res) + 1); return res; } #define MSAN_MAYBE_INTERCEPT_FCVT INTERCEPT_FUNCTION(fcvt) #else #define MSAN_MAYBE_INTERCEPT_FCVT #endif INTERCEPTOR(char *, getenv, char *name) { if (msan_init_is_running) return REAL(getenv)(name); ENSURE_MSAN_INITED(); char *res = REAL(getenv)(name); if (res) __msan_unpoison(res, REAL(strlen)(res) + 1); return res; } extern char **environ; static void UnpoisonEnviron() { char **envp = environ; for (; *envp; ++envp) { __msan_unpoison(envp, sizeof(*envp)); __msan_unpoison(*envp, REAL(strlen)(*envp) + 1); } // Trailing NULL pointer. __msan_unpoison(envp, sizeof(*envp)); } INTERCEPTOR(int, setenv, const char *name, const char *value, int overwrite) { ENSURE_MSAN_INITED(); CHECK_UNPOISONED_STRING(name, 0); int res = REAL(setenv)(name, value, overwrite); if (!res) UnpoisonEnviron(); return res; } INTERCEPTOR(int, putenv, char *string) { ENSURE_MSAN_INITED(); int res = REAL(putenv)(string); if (!res) UnpoisonEnviron(); return res; } #if SANITIZER_FREEBSD || SANITIZER_NETBSD INTERCEPTOR(int, fstat, int fd, void *buf) { ENSURE_MSAN_INITED(); int res = REAL(fstat)(fd, buf); if (!res) __msan_unpoison(buf, __sanitizer::struct_stat_sz); return res; } #define MSAN_MAYBE_INTERCEPT_FSTAT INTERCEPT_FUNCTION(fstat) #else #define MSAN_MAYBE_INTERCEPT_FSTAT #endif #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(int, __fxstat, int magic, int fd, void *buf) { ENSURE_MSAN_INITED(); int res = REAL(__fxstat)(magic, fd, buf); if (!res) __msan_unpoison(buf, __sanitizer::struct_stat_sz); return res; } #define MSAN_MAYBE_INTERCEPT___FXSTAT INTERCEPT_FUNCTION(__fxstat) #else #define MSAN_MAYBE_INTERCEPT___FXSTAT #endif #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(int, __fxstat64, int magic, int fd, void *buf) { ENSURE_MSAN_INITED(); int res = REAL(__fxstat64)(magic, fd, buf); if (!res) __msan_unpoison(buf, __sanitizer::struct_stat64_sz); return res; } #define MSAN_MAYBE_INTERCEPT___FXSTAT64 INTERCEPT_FUNCTION(__fxstat64) #else #define MSAN_MAYBE_INTERCEPT___FXSTAT64 #endif #if SANITIZER_FREEBSD || SANITIZER_NETBSD INTERCEPTOR(int, fstatat, int fd, char *pathname, void *buf, int flags) { ENSURE_MSAN_INITED(); int res = REAL(fstatat)(fd, pathname, buf, flags); if (!res) __msan_unpoison(buf, __sanitizer::struct_stat_sz); return res; } # define MSAN_INTERCEPT_FSTATAT INTERCEPT_FUNCTION(fstatat) #else INTERCEPTOR(int, __fxstatat, int magic, int fd, char *pathname, void *buf, int flags) { ENSURE_MSAN_INITED(); int res = REAL(__fxstatat)(magic, fd, pathname, buf, flags); if (!res) __msan_unpoison(buf, __sanitizer::struct_stat_sz); return res; } # define MSAN_INTERCEPT_FSTATAT INTERCEPT_FUNCTION(__fxstatat) #endif #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(int, __fxstatat64, int magic, int fd, char *pathname, void *buf, int flags) { ENSURE_MSAN_INITED(); int res = REAL(__fxstatat64)(magic, fd, pathname, buf, flags); if (!res) __msan_unpoison(buf, __sanitizer::struct_stat64_sz); return res; } #define MSAN_MAYBE_INTERCEPT___FXSTATAT64 INTERCEPT_FUNCTION(__fxstatat64) #else #define MSAN_MAYBE_INTERCEPT___FXSTATAT64 #endif INTERCEPTOR(int, pipe, int pipefd[2]) { if (msan_init_is_running) return REAL(pipe)(pipefd); ENSURE_MSAN_INITED(); int res = REAL(pipe)(pipefd); if (!res) __msan_unpoison(pipefd, sizeof(int[2])); return res; } INTERCEPTOR(int, pipe2, int pipefd[2], int flags) { ENSURE_MSAN_INITED(); int res = REAL(pipe2)(pipefd, flags); if (!res) __msan_unpoison(pipefd, sizeof(int[2])); return res; } INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int sv[2]) { ENSURE_MSAN_INITED(); int res = REAL(socketpair)(domain, type, protocol, sv); if (!res) __msan_unpoison(sv, sizeof(int[2])); return res; } #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(char *, fgets_unlocked, char *s, int size, void *stream) { ENSURE_MSAN_INITED(); char *res = REAL(fgets_unlocked)(s, size, stream); if (res) __msan_unpoison(s, REAL(strlen)(s) + 1); return res; } #define MSAN_MAYBE_INTERCEPT_FGETS_UNLOCKED INTERCEPT_FUNCTION(fgets_unlocked) #else #define MSAN_MAYBE_INTERCEPT_FGETS_UNLOCKED #endif #define INTERCEPTOR_GETRLIMIT_BODY(func, resource, rlim) \\ if (msan_init_is_running) \\ return REAL(getrlimit)(resource, rlim); \\ ENSURE_MSAN_INITED(); \\ int res = REAL(func)(resource, rlim); \\ if (!res) \\ __msan_unpoison(rlim, __sanitizer::struct_rlimit_sz); \\ return res INTERCEPTOR(int, getrlimit, int resource, void *rlim) { INTERCEPTOR_GETRLIMIT_BODY(getrlimit, resource, rlim); } #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(int, __getrlimit, int resource, void *rlim) { INTERCEPTOR_GETRLIMIT_BODY(__getrlimit, resource, rlim); } INTERCEPTOR(int, getrlimit64, int resource, void *rlim) { if (msan_init_is_running) return REAL(getrlimit64)(resource, rlim); ENSURE_MSAN_INITED(); int res = REAL(getrlimit64)(resource, rlim); if (!res) __msan_unpoison(rlim, __sanitizer::struct_rlimit64_sz); return res; } INTERCEPTOR(int, prlimit, int pid, int resource, void *new_rlimit, void *old_rlimit) { if (msan_init_is_running) return REAL(prlimit)(pid, resource, new_rlimit, old_rlimit); ENSURE_MSAN_INITED(); CHECK_UNPOISONED(new_rlimit, __sanitizer::struct_rlimit_sz); int res = REAL(prlimit)(pid, resource, new_rlimit, old_rlimit); if (!res) __msan_unpoison(old_rlimit, __sanitizer::struct_rlimit_sz); return res; } INTERCEPTOR(int, prlimit64, int pid, int resource, void *new_rlimit, void *old_rlimit) { if (msan_init_is_running) return REAL(prlimit64)(pid, resource, new_rlimit, old_rlimit); ENSURE_MSAN_INITED(); CHECK_UNPOISONED(new_rlimit, __sanitizer::struct_rlimit64_sz); int res = REAL(prlimit64)(pid, resource, new_rlimit, old_rlimit); if (!res) __msan_unpoison(old_rlimit, __sanitizer::struct_rlimit64_sz); return res; } #define MSAN_MAYBE_INTERCEPT___GETRLIMIT INTERCEPT_FUNCTION(__getrlimit) #define MSAN_MAYBE_INTERCEPT_GETRLIMIT64 INTERCEPT_FUNCTION(getrlimit64) #define MSAN_MAYBE_INTERCEPT_PRLIMIT INTERCEPT_FUNCTION(prlimit) #define MSAN_MAYBE_INTERCEPT_PRLIMIT64 INTERCEPT_FUNCTION(prlimit64) #else #define MSAN_MAYBE_INTERCEPT___GETRLIMIT #define MSAN_MAYBE_INTERCEPT_GETRLIMIT64 #define MSAN_MAYBE_INTERCEPT_PRLIMIT #define MSAN_MAYBE_INTERCEPT_PRLIMIT64 #endif #if SANITIZER_FREEBSD // FreeBSD's define uname() as // static __inline int uname(struct utsname *name) { // return __xuname(SYS_NMLN, (void*)name); // } INTERCEPTOR(int, __xuname, int size, void *utsname) { ENSURE_MSAN_INITED(); int res = REAL(__xuname)(size, utsname); if (!res) __msan_unpoison(utsname, __sanitizer::struct_utsname_sz); return res; } #define MSAN_INTERCEPT_UNAME INTERCEPT_FUNCTION(__xuname) #else INTERCEPTOR(int, uname, struct utsname *utsname) { ENSURE_MSAN_INITED(); int res = REAL(uname)(utsname); if (!res) __msan_unpoison(utsname, __sanitizer::struct_utsname_sz); return res; } #define MSAN_INTERCEPT_UNAME INTERCEPT_FUNCTION(uname) #endif INTERCEPTOR(int, gethostname, char *name, SIZE_T len) { ENSURE_MSAN_INITED(); int res = REAL(gethostname)(name, len); if (!res) { SIZE_T real_len = REAL(strnlen)(name, len); if (real_len < len) ++real_len; __msan_unpoison(name, real_len); } return res; } #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(int, epoll_wait, int epfd, void *events, int maxevents, int timeout) { ENSURE_MSAN_INITED(); int res = REAL(epoll_wait)(epfd, events, maxevents, timeout); if (res > 0) { __msan_unpoison(events, __sanitizer::struct_epoll_event_sz * res); } return res; } #define MSAN_MAYBE_INTERCEPT_EPOLL_WAIT INTERCEPT_FUNCTION(epoll_wait) #else #define MSAN_MAYBE_INTERCEPT_EPOLL_WAIT #endif #if !SANITIZER_FREEBSD && !SANITIZER_NETBSD INTERCEPTOR(int, epoll_pwait, int epfd, void *events, int maxevents, int timeout, void *sigmask) { ENSURE_MSAN_INITED(); int res = REAL(epoll_pwait)(epfd, events, maxevents, timeout, sigmask); if (res > 0) { __msan_unpoison(events, __sanitizer::struct_epoll_event_sz * res); } return res; } #define MSAN_MAYBE_INTERCEPT_EPOLL_PWAIT INTERCEPT_FUNCTION(epoll_pwait) #else #define MSAN_MAYBE_INTERCEPT_EPOLL_PWAIT #endif INTERCEPTOR(void *, calloc, SIZE_T nmemb, SIZE_T size) { GET_MALLOC_STACK_TRACE; if (UNLIKELY(!msan_inited)) // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym. return AllocateFromLocalPool(nmemb * size); return msan_calloc(nmemb, size, &stack); } INTERCEPTOR(void *, realloc, void *ptr, SIZE_T size) { GET_MALLOC_STACK_TRACE; if (UNLIKELY(IsInDlsymAllocPool(ptr))) { uptr offset = (uptr)ptr - (uptr)alloc_memory_for_dlsym; uptr copy_size = Min(size, kDlsymAllocPoolSize - offset); void *new_ptr; if (UNLIKELY(!msan_inited)) { new_ptr = AllocateFromLocalPool(copy_size); } else { copy_size = size; new_ptr = msan_malloc(copy_size, &stack); } internal_memcpy(new_ptr, ptr, copy_size); return new_ptr; } return msan_realloc(ptr, size, &stack); } INTERCEPTOR(void *, reallocarray, void *ptr, SIZE_T nmemb, SIZE_T size) { GET_MALLOC_STACK_TRACE; return msan_reallocarray(ptr, nmemb, size, &stack); } INTERCEPTOR(void *, malloc, SIZE_T size) { GET_MALLOC_STACK_TRACE; if (UNLIKELY(!msan_inited)) // Hack: dlsym calls malloc before REAL(malloc) is retrieved from dlsym. return AllocateFromLocalPool(size); return msan_malloc(size, &stack); } void __msan_allocated_memory(const void *data, uptr size) { GET_MALLOC_STACK_TRACE; if (flags()->poison_in_malloc) { stack.tag = STACK_TRACE_TAG_POISON; PoisonMemory(data, size, &stack); } } void __msan_copy_shadow(void *dest, const void *src, uptr n) { GET_STORE_STACK_TRACE; MoveShadowAndOrigin(dest, src, n, &stack); } void __sanitizer_dtor_callback(const void *data, uptr size) { GET_MALLOC_STACK_TRACE; if (flags()->poison_in_dtor) { stack.tag = STACK_TRACE_TAG_POISON; PoisonMemory(data, size, &stack); } } template static void *mmap_interceptor(Mmap real_mmap, void *addr, SIZE_T length, int prot, int flags, int fd, OFF64_T offset) { if (addr && !MEM_IS_APP(addr)) { if (flags & map_fixed) { errno = errno_EINVAL; return (void *)-1; } else { addr = nullptr; } } void *res = real_mmap(addr, length, prot, flags, fd, offset); if (res != (void *)-1) __msan_unpoison(res, RoundUpTo(length, GetPageSize())); return res; } INTERCEPTOR(int, getrusage, int who, void *usage) { ENSURE_MSAN_INITED(); int res = REAL(getrusage)(who, usage); if (res == 0) { __msan_unpoison(usage, __sanitizer::struct_rusage_sz); } return res; } class SignalHandlerScope { public: SignalHandlerScope() { if (MsanThread *t = GetCurrentThread()) t->EnterSignalHandler(); } ~SignalHandlerScope() { if (MsanThread *t = GetCurrentThread()) t->LeaveSignalHandler(); } }; // sigactions_mu guarantees atomicity of sigaction() and signal() calls. // Access to sigactions[] is gone with relaxed atomics to avoid data race with // the signal handler. const int kMaxSignals = 1024; static atomic_uintptr_t sigactions[kMaxSignals]; static StaticSpinMutex sigactions_mu; static void SignalHandler(int signo) { SignalHandlerScope signal_handler_scope; ScopedThreadLocalStateBackup stlsb; UnpoisonParam(1); typedef void (*signal_cb)(int x); signal_cb cb = (signal_cb)atomic_load(&sigactions[signo], memory_order_relaxed); cb(signo); } static void SignalAction(int signo, void *si, void *uc) { SignalHandlerScope signal_handler_scope; ScopedThreadLocalStateBackup stlsb; UnpoisonParam(3); __msan_unpoison(si, sizeof(__sanitizer_sigaction)); __msan_unpoison(uc, __sanitizer::ucontext_t_sz); typedef void (*sigaction_cb)(int, void *, void *); sigaction_cb cb = (sigaction_cb)atomic_load(&sigactions[signo], memory_order_relaxed); cb(signo, si, uc); } static void read_sigaction(const __sanitizer_sigaction *act) { CHECK_UNPOISONED(&act->sa_flags, sizeof(act->sa_flags)); if (act->sa_flags & __sanitizer::sa_siginfo) CHECK_UNPOISONED(&act->sigaction, sizeof(act->sigaction)); else CHECK_UNPOISONED(&act->handler, sizeof(act->handler)); CHECK_UNPOISONED(&act->sa_mask, sizeof(act->sa_mask)); } extern ""C"" int pthread_attr_init(void *attr); extern ""C"" int pthread_attr_destroy(void *attr); static void *MsanThreadStartFunc(void *arg) { MsanThread *t = (MsanThread *)arg; SetCurrentThread(t); return t->ThreadStart(); } INTERCEPTOR(int, pthread_create, void *th, void *attr, void *(*callback)(void*), void * param) { ENSURE_MSAN_INITED(); // for GetTlsSize() __sanitizer_pthread_attr_t myattr; if (!attr) { pthread_attr_init(&myattr); attr = &myattr; } AdjustStackSize(attr); MsanThread *t = MsanThread::Create(callback, param); int res = REAL(pthread_create)(th, attr, MsanThreadStartFunc, t); if (attr == &myattr) pthread_attr_destroy(&myattr); if (!res) { __msan_unpoison(th, __sanitizer::pthread_t_sz); } return res; } INTERCEPTOR(int, pthread_key_create, __sanitizer_pthread_key_t *key, void (*dtor)(void *value)) { if (msan_init_is_running) return REAL(pthread_key_create)(key, dtor); ENSURE_MSAN_INITED(); int res = REAL(pthread_key_create)(key, dtor); if (!res && key) __msan_unpoison(key, sizeof(*key)); return res; } #if SANITIZER_NETBSD INTERCEPTOR(int, __libc_thr_keycreate, __sanitizer_pthread_key_t *m, void (*dtor)(void *value)) ALIAS(WRAPPER_NAME(pthread_key_create)); #endif INTERCEPTOR(int, pthread_join, void *th, void **retval) { ENSURE_MSAN_INITED(); int res = REAL(pthread_join)(th, retval); if (!res && retval) __msan_unpoison(retval, sizeof(*retval)); return res; } extern char *tzname[2]; INTERCEPTOR(void, tzset, int fake) { ENSURE_MSAN_INITED(); InterceptorScope interceptor_scope; REAL(tzset)(fake); if (tzname[0]) __msan_unpoison(tzname[0], REAL(strlen)(tzname[0]) + 1); if (tzname[1]) __msan_unpoison(tzname[1], REAL(strlen)(tzname[1]) + 1); return; } struct MSanAtExitRecord { void (*func)(void *arg); void *arg; }; struct InterceptorContext { BlockingMutex atexit_mu; Vector AtExitStack; InterceptorContext() : AtExitStack() { } }; static ALIGNED(64) char interceptor_placeholder[sizeof(InterceptorContext)]; InterceptorContext *interceptor_ctx() { return reinterpret_cast(&interceptor_placeholder[0]); } void MSanAtExitWrapper() { MSanAtExitRecord *r; { BlockingMutexLock l(&interceptor_ctx()->atexit_mu); uptr element = interceptor_ctx()->AtExitStack.Size() - 1; r = interceptor_ctx()->AtExitStack[element]; interceptor_ctx()->AtExitStack.PopBack(); } UnpoisonParam(1); ((void(*)())r->func)(); InternalFree(r); } void MSanCxaAtExitWrapper(void *arg) { UnpoisonParam(1); MSanAtExitRecord *r = (MSanAtExitRecord *)arg; // libc before 2.27 had race which caused occasional double handler execution // https://sourceware.org/ml/libc-alpha/2017-08/msg01204.html if (!r->func) return; r->func(r->arg); r->func = nullptr; } static int setup_at_exit_wrapper(void(*f)(), void *arg, void *dso); // Unpoison argument shadow for C++ module destructors. INTERCEPTOR(int, __cxa_atexit, void (*func)(void *), void *arg, void *dso_handle) { if (msan_init_is_running) return REAL(__cxa_atexit)(func, arg, dso_handle); return setup_at_exit_wrapper((void(*)())func, arg, dso_handle); } // Unpoison argument shadow for C++ module destructors. INTERCEPTOR(int, atexit, void (*func)()) { // Avoid calling real atexit as it is unrechable on at least on Linux. if (msan_init_is_running) return REAL(__cxa_atexit)((void (*)(void *a))func, 0, 0); return setup_at_exit_wrapper((void(*)())func, 0, 0); } static int setup_at_exit_wrapper(void(*f)(), void *arg, void *dso) { ENSURE_MSAN_INITED(); MSanAtExitRecord *r = (MSanAtExitRecord *)InternalAlloc(sizeof(MSanAtExitRecord)); r->func = (void(*)(void *a))f; r->arg = arg; int res; if (!dso) { // NetBSD does not preserve the 2nd argument if dso is equal to 0 // Store ctx in a local stack-like structure BlockingMutexLock l(&interceptor_ctx()->atexit_mu); res = REAL(__cxa_atexit)((void (*)(void *a))MSanAtExitWrapper, 0, 0); if (!res) { interceptor_ctx()->AtExitStack.PushBack(r); } } else { res = REAL(__cxa_atexit)(MSanCxaAtExitWrapper, r, dso); } return res; } static void BeforeFork() { StackDepotLockAll(); ChainedOriginDepotLockAll(); } static void AfterFork() { ChainedOriginDepotUnlockAll(); StackDepotUnlockAll(); } INTERCEPTOR(int, fork, void) { ENSURE_MSAN_INITED(); BeforeFork(); int pid = REAL(fork)(); AfterFork(); return pid; } // NetBSD ships with openpty(3) in -lutil, that needs to be prebuilt explicitly // with MSan. #if SANITIZER_LINUX INTERCEPTOR(int, openpty, int *aparent, int *aworker, char *name, const void *termp, const void *winp) { ENSURE_MSAN_INITED(); InterceptorScope interceptor_scope; int res = REAL(openpty)(aparent, aworker, name, termp, winp); if (!res) { __msan_unpoison(aparent, sizeof(*aparent)); __msan_unpoison(aworker, sizeof(*aworker)); } return res; } #define MSAN_MAYBE_INTERCEPT_OPENPTY INTERCEPT_FUNCTION(openpty) #else #define MSAN_MAYBE_INTERCEPT_OPENPTY #endif // NetBSD ships with forkpty(3) in -lutil, that needs to be prebuilt explicitly // with MSan. #if SANITIZER_LINUX INTERCEPTOR(int, forkpty, int *aparent, char *name, const void *termp, const void *winp) { ENSURE_MSAN_INITED(); InterceptorScope interceptor_scope; int res = REAL(forkpty)(aparent, name, termp, winp); if (res != -1) __msan_unpoison(aparent, sizeof(*aparent)); return res; } #define MSAN_MAYBE_INTERCEPT_FORKPTY INTERCEPT_FUNCTION(forkpty) #else #define MSAN_MAYBE_INTERCEPT_FORKPTY #endif struct MSanInterceptorContext { bool in_interceptor_scope; }; namespace __msan { int OnExit() { // FIXME: ask frontend whether we need to return failure. return 0; } } // namespace __msan // A version of CHECK_UNPOISONED using a saved scope value. Used in common // interceptors. #define CHECK_UNPOISONED_CTX(ctx, x, n) \\ do { \\ if (!((MSanInterceptorContext *)ctx)->in_interceptor_scope) \\ CHECK_UNPOISONED_0(x, n); \\ } while (0) #define MSAN_INTERCEPT_FUNC(name) \\ do { \\ if (!INTERCEPT_FUNCTION(name)) \\ VReport(1, ""MemorySanitizer: failed to intercept '%s'\\n'"", #name); \\ } while (0) #define MSAN_INTERCEPT_FUNC_VER(name, ver) \\ do { \\ if (!INTERCEPT_FUNCTION_VER(name, ver)) \\ VReport(1, ""MemorySanitizer: failed to intercept '%s@@%s'\\n"", #name, \\ #ver); \\ } while (0) #define COMMON_INTERCEPT_FUNCTION(name) MSAN_INTERCEPT_FUNC(name) #define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \\ MSAN_INTERCEPT_FUNC_VER(name, ver) #define COMMON_INTERCEPTOR_UNPOISON_PARAM(count) \\ UnpoisonParam(count) #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \\ __msan_unpoison(ptr, size) #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \\ CHECK_UNPOISONED_CTX(ctx, ptr, size) #define COMMON_INTERCEPTOR_INITIALIZE_RANGE(ptr, size) \\ __msan_unpoison(ptr, size) #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \\ if (msan_init_is_running) return REAL(func)(__VA_ARGS__); \\ ENSURE_MSAN_INITED(); \\ MSanInterceptorContext msan_ctx = {IsInInterceptorScope()}; \\ ctx = (void *)&msan_ctx; \\ (void)ctx; \\ InterceptorScope interceptor_scope; \\ __msan_unpoison(__errno_location(), sizeof(int)); /* NOLINT */ #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \\ do { \\ } while (false) #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \\ do { \\ } while (false) #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \\ do { \\ } while (false) #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \\ do { \\ } while (false) #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \\ do { \\ } while (false) // FIXME #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \\ do { \\ } while (false) // FIXME #define COMMON_INTERCEPTOR_BLOCK_REAL(name) REAL(name) #define COMMON_INTERCEPTOR_ON_EXIT(ctx) OnExit() #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \\ do { \\ link_map *map = GET_LINK_MAP_BY_DLOPEN_HANDLE((handle)); \\ if (filename && map) \\ ForEachMappedRegion(map, __msan_unpoison); \\ } while (false) #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \\ if (MsanThread *t = GetCurrentThread()) { \\ *begin = t->tls_begin(); \\ *end = t->tls_end(); \\ } else { \\ *begin = *end = 0; \\ } #define COMMON_INTERCEPTOR_MEMSET_IMPL(ctx, block, c, size) \\ { \\ (void)ctx; \\ return __msan_memset(block, c, size); \\ } #define COMMON_INTERCEPTOR_MEMMOVE_IMPL(ctx, to, from, size) \\ { \\ (void)ctx; \\ return __msan_memmove(to, from, size); \\ } #define COMMON_INTERCEPTOR_MEMCPY_IMPL(ctx, to, from, size) \\ { \\ (void)ctx; \\ return __msan_memcpy(to, from, size); \\ } #define COMMON_INTERCEPTOR_COPY_STRING(ctx, to, from, size) \\ do { \\ GET_STORE_STACK_TRACE; \\ CopyShadowAndOrigin(to, from, size, &stack); \\ __msan_unpoison(to + size, 1); \\ } while (false) #define COMMON_INTERCEPTOR_MMAP_IMPL(ctx, mmap, addr, length, prot, flags, fd, \\ offset) \\ do { \\ return mmap_interceptor(REAL(mmap), addr, sz, prot, flags, fd, off); \\ } while (false) #include ""sanitizer_common/sanitizer_platform_interceptors.h"" #include ""sanitizer_common/sanitizer_common_interceptors.inc"" static uptr signal_impl(int signo, uptr cb); static int sigaction_impl(int signo, const __sanitizer_sigaction *act, __sanitizer_sigaction *oldact); #define SIGNAL_INTERCEPTOR_SIGACTION_IMPL(signo, act, oldact) \\ { return sigaction_impl(signo, act, oldact); } #define SIGNAL_INTERCEPTOR_SIGNAL_IMPL(func, signo, handler) \\ { \\ handler = signal_impl(signo, handler); \\ InterceptorScope interceptor_scope; \\ return REAL(func)(signo, handler); \\ } #include ""sanitizer_common/sanitizer_signal_interceptors.inc"" static int sigaction_impl(int signo, const __sanitizer_sigaction *act, __sanitizer_sigaction *oldact) { ENSURE_MSAN_INITED(); if (act) read_sigaction(act); int res; if (flags()->wrap_signals) { SpinMutexLock lock(&sigactions_mu); CHECK_LT(signo, kMaxSignals); uptr old_cb = atomic_load(&sigactions[signo], memory_order_relaxed); __sanitizer_sigaction new_act; __sanitizer_sigaction *pnew_act = act ? &new_act : nullptr; if (act) { REAL(memcpy)(pnew_act, act, sizeof(__sanitizer_sigaction)); uptr cb = (uptr)pnew_act->sigaction; uptr new_cb = (pnew_act->sa_flags & __sanitizer::sa_siginfo) ? (uptr)SignalAction : (uptr)SignalHandler; if (cb != __sanitizer::sig_ign && cb != __sanitizer::sig_dfl) { atomic_store(&sigactions[signo], cb, memory_order_relaxed); pnew_act->sigaction = (decltype(pnew_act->sigaction))new_cb; } } res = REAL(SIGACTION_SYMNAME)(signo, pnew_act, oldact); if (res == 0 && oldact) { uptr cb = (uptr)oldact->sigaction; if (cb == (uptr)SignalAction || cb == (uptr)SignalHandler) { oldact->sigaction = (decltype(oldact->sigaction))old_cb; } } } else { res = REAL(SIGACTION_SYMNAME)(signo, act, oldact); } if (res == 0 && oldact) { __msan_unpoison(oldact, sizeof(__sanitizer_sigaction)); } return res; } static uptr signal_impl(int signo, uptr cb) { ENSURE_MSAN_INITED(); if (flags()->wrap_signals) { CHECK_LT(signo, kMaxSignals); SpinMutexLock lock(&sigactions_mu); if (cb != __sanitizer::sig_ign && cb != __sanitizer::sig_dfl) { atomic_store(&sigactions[signo], cb, memory_order_relaxed); cb = (uptr)&SignalHandler; } } return cb; } #define COMMON_SYSCALL_PRE_READ_RANGE(p, s) CHECK_UNPOISONED(p, s) #define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \\ do { \\ } while (false) #define COMMON_SYSCALL_POST_READ_RANGE(p, s) \\ do { \\ } while (false) #define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) __msan_unpoison(p, s) #include ""sanitizer_common/sanitizer_common_syscalls.inc"" #include ""sanitizer_common/sanitizer_syscalls_netbsd.inc"" struct dlinfo { char *dli_fname; void *dli_fbase; char *dli_sname; void *dli_saddr; }; INTERCEPTOR(int, dladdr, void *addr, dlinfo *info) { void *ctx; COMMON_INTERCEPTOR_ENTER(ctx, dladdr, addr, info); int res = REAL(dladdr)(addr, info); if (res != 0) { __msan_unpoison(info, sizeof(*info)); if (info->dli_fname) __msan_unpoison(info->dli_fname, REAL(strlen)(info->dli_fname) + 1); if (info->dli_sname) __msan_unpoison(info->dli_sname, REAL(strlen)(info->dli_sname) + 1); } return res; } INTERCEPTOR(char *, dlerror, int fake) { void *ctx; COMMON_INTERCEPTOR_ENTER(ctx, dlerror, fake); char *res = REAL(dlerror)(fake); if (res) __msan_unpoison(res, REAL(strlen)(res) + 1); return res; } typedef int (*dl_iterate_phdr_cb)(__sanitizer_dl_phdr_info *info, SIZE_T size, void *data); struct dl_iterate_phdr_data { dl_iterate_phdr_cb callback; void *data; }; static int msan_dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size, void *data) { if (info) { __msan_unpoison(info, size); if (info->dlpi_phdr && info->dlpi_phnum) __msan_unpoison(info->dlpi_phdr, struct_ElfW_Phdr_sz * info->dlpi_phnum); if (info->dlpi_name) __msan_unpoison(info->dlpi_name, REAL(strlen)(info->dlpi_name) + 1); } dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data; UnpoisonParam(3); return cbdata->callback(info, size, cbdata->data); } INTERCEPTOR(void *, shmat, int shmid, const void *shmaddr, int shmflg) { ENSURE_MSAN_INITED(); void *p = REAL(shmat)(shmid, shmaddr, shmflg); if (p != (void *)-1) { __sanitizer_shmid_ds ds; int res = REAL(shmctl)(shmid, shmctl_ipc_stat, &ds); if (!res) { __msan_unpoison(p, ds.shm_segsz); } } return p; } INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb callback, void *data) { void *ctx; COMMON_INTERCEPTOR_ENTER(ctx, dl_iterate_phdr, callback, data); dl_iterate_phdr_data cbdata; cbdata.callback = callback; cbdata.data = data; int res = REAL(dl_iterate_phdr)(msan_dl_iterate_phdr_cb, (void *)&cbdata); return res; } // wchar_t *wcschr(const wchar_t *wcs, wchar_t wc); INTERCEPTOR(wchar_t *, wcschr, void *s, wchar_t wc, void *ps) { ENSURE_MSAN_INITED(); wchar_t *res = REAL(wcschr)(s, wc, ps); return res; } // wchar_t *wcscpy(wchar_t *dest, const wchar_t *src); INTERCEPTOR(wchar_t *, wcscpy, wchar_t *dest, const wchar_t *src) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; wchar_t *res = REAL(wcscpy)(dest, src); CopyShadowAndOrigin(dest, src, sizeof(wchar_t) * (REAL(wcslen)(src) + 1), &stack); return res; } INTERCEPTOR(wchar_t *, wcsncpy, wchar_t *dest, const wchar_t *src, SIZE_T n) { ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; SIZE_T copy_size = REAL(wcsnlen)(src, n); if (copy_size < n) copy_size++; // trailing \\0 wchar_t *res = REAL(wcsncpy)(dest, src, n); CopyShadowAndOrigin(dest, src, copy_size * sizeof(wchar_t), &stack); __msan_unpoison(dest + copy_size, (n - copy_size) * sizeof(wchar_t)); return res; } // These interface functions reside here so that they can use // REAL(memset), etc. void __msan_unpoison(const void *a, uptr size) { if (!MEM_IS_APP(a)) return; SetShadow(a, size, 0); } void __msan_poison(const void *a, uptr size) { if (!MEM_IS_APP(a)) return; SetShadow(a, size, __msan::flags()->poison_heap_with_zeroes ? 0 : -1); } void __msan_poison_stack(void *a, uptr size) { if (!MEM_IS_APP(a)) return; SetShadow(a, size, __msan::flags()->poison_stack_with_zeroes ? 0 : -1); } void __msan_unpoison_param(uptr n) { UnpoisonParam(n); } void __msan_clear_and_unpoison(void *a, uptr size) { REAL(memset)(a, 0, size); SetShadow(a, size, 0); } void *__msan_memcpy(void *dest, const void *src, SIZE_T n) { if (!msan_inited) return internal_memcpy(dest, src, n); if (msan_init_is_running || __msan::IsInSymbolizer()) return REAL(memcpy)(dest, src, n); ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; void *res = REAL(memcpy)(dest, src, n); CopyShadowAndOrigin(dest, src, n, &stack); return res; } void *__msan_memset(void *s, int c, SIZE_T n) { if (!msan_inited) return internal_memset(s, c, n); if (msan_init_is_running) return REAL(memset)(s, c, n); ENSURE_MSAN_INITED(); void *res = REAL(memset)(s, c, n); __msan_unpoison(s, n); return res; } void *__msan_memmove(void *dest, const void *src, SIZE_T n) { if (!msan_inited) return internal_memmove(dest, src, n); if (msan_init_is_running) return REAL(memmove)(dest, src, n); ENSURE_MSAN_INITED(); GET_STORE_STACK_TRACE; void *res = REAL(memmove)(dest, src, n); MoveShadowAndOrigin(dest, src, n, &stack); return res; } void __msan_unpoison_string(const char* s) { if (!MEM_IS_APP(s)) return; __msan_unpoison(s, REAL(strlen)(s) + 1); } namespace __msan { void InitializeInterceptors() { static int inited = 0; CHECK_EQ(inited, 0); new(interceptor_ctx()) InterceptorContext(); InitializeCommonInterceptors(); InitializeSignalInterceptors(); INTERCEPT_FUNCTION(posix_memalign); MSAN_MAYBE_INTERCEPT_MEMALIGN; MSAN_MAYBE_INTERCEPT___LIBC_MEMALIGN; INTERCEPT_FUNCTION(valloc); MSAN_MAYBE_INTERCEPT_PVALLOC; INTERCEPT_FUNCTION(malloc); INTERCEPT_FUNCTION(calloc); INTERCEPT_FUNCTION(realloc); INTERCEPT_FUNCTION(reallocarray); INTERCEPT_FUNCTION(free); MSAN_MAYBE_INTERCEPT_CFREE; MSAN_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE; MSAN_MAYBE_INTERCEPT_MALLINFO; MSAN_MAYBE_INTERCEPT_MALLOPT; MSAN_MAYBE_INTERCEPT_MALLOC_STATS; INTERCEPT_FUNCTION(fread); MSAN_MAYBE_INTERCEPT_FREAD_UNLOCKED; INTERCEPT_FUNCTION(memccpy); MSAN_MAYBE_INTERCEPT_MEMPCPY; INTERCEPT_FUNCTION(bcopy); INTERCEPT_FUNCTION(wmemset); INTERCEPT_FUNCTION(wmemcpy); MSAN_MAYBE_INTERCEPT_WMEMPCPY; INTERCEPT_FUNCTION(wmemmove); INTERCEPT_FUNCTION(strcpy); MSAN_MAYBE_INTERCEPT_STPCPY; INTERCEPT_FUNCTION(strdup); MSAN_MAYBE_INTERCEPT___STRDUP; INTERCEPT_FUNCTION(strncpy); MSAN_MAYBE_INTERCEPT_GCVT; INTERCEPT_FUNCTION(strcat); INTERCEPT_FUNCTION(strncat); INTERCEPT_STRTO(strtod); INTERCEPT_STRTO(strtof); INTERCEPT_STRTO(strtold); INTERCEPT_STRTO(strtol); INTERCEPT_STRTO(strtoul); INTERCEPT_STRTO(strtoll); INTERCEPT_STRTO(strtoull); INTERCEPT_STRTO(strtouq); INTERCEPT_STRTO(wcstod); INTERCEPT_STRTO(wcstof); INTERCEPT_STRTO(wcstold); INTERCEPT_STRTO(wcstol); INTERCEPT_STRTO(wcstoul); INTERCEPT_STRTO(wcstoll); INTERCEPT_STRTO(wcstoull); #ifdef SANITIZER_NLDBL_VERSION INTERCEPT_FUNCTION_VER(vswprintf, SANITIZER_NLDBL_VERSION); INTERCEPT_FUNCTION_VER(swprintf, SANITIZER_NLDBL_VERSION); #else INTERCEPT_FUNCTION(vswprintf); INTERCEPT_FUNCTION(swprintf); #endif INTERCEPT_FUNCTION(strftime); INTERCEPT_FUNCTION(strftime_l); MSAN_MAYBE_INTERCEPT___STRFTIME_L; INTERCEPT_FUNCTION(wcsftime); INTERCEPT_FUNCTION(wcsftime_l); MSAN_MAYBE_INTERCEPT___WCSFTIME_L; INTERCEPT_FUNCTION(mbtowc); INTERCEPT_FUNCTION(mbrtowc); INTERCEPT_FUNCTION(wcslen); INTERCEPT_FUNCTION(wcsnlen); INTERCEPT_FUNCTION(wcschr); INTERCEPT_FUNCTION(wcscpy); INTERCEPT_FUNCTION(wcsncpy); INTERCEPT_FUNCTION(wcscmp); INTERCEPT_FUNCTION(getenv); INTERCEPT_FUNCTION(setenv); INTERCEPT_FUNCTION(putenv); INTERCEPT_FUNCTION(gettimeofday); MSAN_MAYBE_INTERCEPT_FCVT; MSAN_MAYBE_INTERCEPT_FSTAT; MSAN_MAYBE_INTERCEPT___FXSTAT; MSAN_INTERCEPT_FSTATAT; MSAN_MAYBE_INTERCEPT___FXSTAT64; MSAN_MAYBE_INTERCEPT___FXSTATAT64; INTERCEPT_FUNCTION(pipe); INTERCEPT_FUNCTION(pipe2); INTERCEPT_FUNCTION(socketpair); MSAN_MAYBE_INTERCEPT_FGETS_UNLOCKED; INTERCEPT_FUNCTION(getrlimit); MSAN_MAYBE_INTERCEPT___GETRLIMIT; MSAN_MAYBE_INTERCEPT_GETRLIMIT64; MSAN_MAYBE_INTERCEPT_PRLIMIT; MSAN_MAYBE_INTERCEPT_PRLIMIT64; MSAN_INTERCEPT_UNAME; INTERCEPT_FUNCTION(gethostname); MSAN_MAYBE_INTERCEPT_EPOLL_WAIT; MSAN_MAYBE_INTERCEPT_EPOLL_PWAIT; INTERCEPT_FUNCTION(dladdr); INTERCEPT_FUNCTION(dlerror); INTERCEPT_FUNCTION(dl_iterate_phdr); INTERCEPT_FUNCTION(getrusage); #if defined(__mips__) INTERCEPT_FUNCTION_VER(pthread_create, ""GLIBC_2.2""); #else INTERCEPT_FUNCTION(pthread_create); #endif INTERCEPT_FUNCTION(pthread_key_create); #if SANITIZER_NETBSD INTERCEPT_FUNCTION(__libc_thr_keycreate); #endif INTERCEPT_FUNCTION(pthread_join); INTERCEPT_FUNCTION(tzset); INTERCEPT_FUNCTION(atexit); INTERCEPT_FUNCTION(__cxa_atexit); INTERCEPT_FUNCTION(shmat); INTERCEPT_FUNCTION(fork); MSAN_MAYBE_INTERCEPT_OPENPTY; MSAN_MAYBE_INTERCEPT_FORKPTY; inited = 1; } } // namespace __msan ",16184,True,3074.910412869437,median "[.configuration-legend] icon:lock[title=Fixed at build time] Configuration property fixed at build time - All other configuration properties are overridable at runtime [.configuration-reference, cols=""80,.^10,.^10""] |=== h|[[quarkus-oidc-general-config-items_configuration]]link:#quarkus-oidc-general-config-items_configuration[Configuration property] h|Type h|Default a| [[quarkus-oidc-general-config-items_quarkus.oidc.tenant-id]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.tenant-id[quarkus.oidc.tenant-id]` [.description] -- A unique tenant identifier. It must be set by `TenantConfigResolver` providers which resolve the tenant configuration dynamically and is optional in all other cases. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.tenant-enabled]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.tenant-enabled[quarkus.oidc.tenant-enabled]` [.description] -- If this tenant configuration is enabled. --|boolean |`true` a| [[quarkus-oidc-general-config-items_quarkus.oidc.application-type]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.application-type[quarkus.oidc.application-type]` [.description] -- The application type, which can be one of the following values from enum `ApplicationType`. --|`web-app`, `service` |`service` a| [[quarkus-oidc-general-config-items_quarkus.oidc.auth-server-url]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.auth-server-url[quarkus.oidc.auth-server-url]` [.description] -- The base URL of the OpenID Connect (OIDC) server, for example, 'https://host:port/auth'. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: 'https://host:port/auth/realms/++{++realm++}++' where '++{++realm++}++' has to be replaced by the name of the Keycloak realm. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.discovery-enabled]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.discovery-enabled[quarkus.oidc.discovery-enabled]` [.description] -- Enables OIDC discovery. If the discovery is disabled then the following properties must be configured: - 'authorization-path' and 'token-path' for the 'web-app' applications - 'jwks-path' or 'introspection-path' for both the 'web-app' and 'service' applications 'web-app' applications may also have 'user-info-path' and 'end-session-path' properties configured. --|boolean |`true` a| [[quarkus-oidc-general-config-items_quarkus.oidc.authorization-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authorization-path[quarkus.oidc.authorization-path]` [.description] -- Relative path of the OIDC authorization endpoint which authenticates the users. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.token-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.token-path[quarkus.oidc.token-path]` [.description] -- Relative path of the OIDC token endpoint which issues ID, access and refresh tokens. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.user-info-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.user-info-path[quarkus.oidc.user-info-path]` [.description] -- Relative path of the OIDC userinfo endpoint. This property must only be set for the 'web-app' applications if OIDC discovery is disabled and 'authentication.user-info-required' property is enabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.introspection-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.introspection-path[quarkus.oidc.introspection-path]` [.description] -- Relative path of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JWT tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens have to be verified or 2) JWT tokens have to be verified while the cached JWK verification set with no matching JWK is being refreshed. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.jwks-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.jwks-path[quarkus.oidc.jwks-path]` [.description] -- Relative path of the OIDC JWKS endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.end-session-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.end-session-path[quarkus.oidc.end-session-path]` [.description] -- Relative path of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the 'web-app' applications is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.connection-delay]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.connection-delay[quarkus.oidc.connection-delay]` [.description] -- The maximum amount of time the adapter will try connecting to the currently unavailable OIDC server for. For example, setting it to '20S' will let the adapter keep requesting the connection for up to 20 seconds. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-general-config-items_quarkus.oidc.public-key]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.public-key[quarkus.oidc.public-key]` [.description] -- Public key for the local JWT token verification. OIDC server connection will not be created when this property is set. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.client-id]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.client-id[quarkus.oidc.client-id]` [.description] -- The client-id of the application. Each application has a client-id that is used to identify the application --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.roles.role-claim-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.roles.role-claim-path[quarkus.oidc.roles.role-claim-path]` [.description] -- Path to the claim containing an array of groups. It starts from the top level JWT JSON object and can contain multiple segments where each segment represents a JSON object name only, example: ""realm/groups"". Use double quotes with the namespace qualified claim names. This property can be used if a token has no 'groups' claim but has the groups set in a different claim. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.roles.role-claim-separator]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.roles.role-claim-separator[quarkus.oidc.roles.role-claim-separator]` [.description] -- Separator for splitting a string which may contain multiple group values. It will only be used if the ""role-claim-path"" property points to a custom claim whose value is a string. A single space will be used by default because the standard 'scope' claim may contain a space separated sequence. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.roles.source]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.roles.source[quarkus.oidc.roles.source]` [.description] -- Source of the principal roles. --|`idtoken`, `accesstoken`, `userinfo` | a| [[quarkus-oidc-general-config-items_quarkus.oidc.token.issuer]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.token.issuer[quarkus.oidc.token.issuer]` [.description] -- Expected issuer 'iss' claim value. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.token.audience]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.token.audience[quarkus.oidc.token.audience]` [.description] -- Expected audience 'aud' claim value which may be a string or an array of strings. --|list of string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.token.token-type]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.token.token-type[quarkus.oidc.token.token-type]` [.description] -- Expected token type --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.token.lifespan-grace]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.token.lifespan-grace[quarkus.oidc.token.lifespan-grace]` [.description] -- Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds. --|int | a| [[quarkus-oidc-general-config-items_quarkus.oidc.token.principal-claim]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.token.principal-claim[quarkus.oidc.token.principal-claim]` [.description] -- Name of the claim which contains a principal name. By default, the 'upn', 'preferred_username' and `sub` claims are checked. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.token.refresh-expired]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.token.refresh-expired[quarkus.oidc.token.refresh-expired]` [.description] -- Refresh expired ID tokens. If this property is enabled then a refresh token request will be performed if the ID token has expired and, if successful, the local session will be updated with the new set of tokens. Otherwise, the local session will be invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case the user may not be challenged again if the OIDC provider session is still active. For this option be effective the `authentication.session-age-extension` property should also be set to a non-zero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type `ApplicationType++#++WEB_APP`++}++. --|boolean |`false` a| [[quarkus-oidc-general-config-items_quarkus.oidc.token.auto-refresh-interval]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.token.auto-refresh-interval[quarkus.oidc.token.auto-refresh-interval]` [.description] -- Token auto-refresh interval in seconds during the user re-authentication. If this option is set then the valid ID token will be refreshed if it will expire in less than a number of minutes set by this option. The user will still be authenticated if the ID token can no longer be refreshed but is still valid. This option will be ignored if the 'refresh-expired' property is not enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-general-config-items_quarkus.oidc.token.forced-jwk-refresh-interval]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.token.forced-jwk-refresh-interval[quarkus.oidc.token.forced-jwk-refresh-interval]` [.description] -- Forced JWK set refresh interval in minutes. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10M` a| [[quarkus-oidc-general-config-items_quarkus.oidc.credentials.secret]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.credentials.secret[quarkus.oidc.credentials.secret]` [.description] -- Client secret which is used for a 'client_secret_basic' authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.credentials.client-secret.value]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.credentials.client-secret.value[quarkus.oidc.credentials.client-secret.value]` [.description] -- The client secret --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.credentials.client-secret.method]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.credentials.client-secret.method[quarkus.oidc.credentials.client-secret.method]` [.description] -- Authentication method. --|`basic`, `post` | a| [[quarkus-oidc-general-config-items_quarkus.oidc.credentials.jwt.secret]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.credentials.jwt.secret[quarkus.oidc.credentials.jwt.secret]` [.description] -- client_secret_jwt: JWT which includes client id as one of its claims is signed by the client secret and is submitted as a 'client_assertion' form parameter, while 'client_assertion_type' parameter is set to ""urn:ietf:params:oauth:client-assertion-type:jwt-bearer"". --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.credentials.jwt.lifespan]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.credentials.jwt.lifespan[quarkus.oidc.credentials.jwt.lifespan]` [.description] -- JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time. --|int |`10` a| [[quarkus-oidc-general-config-items_quarkus.oidc.proxy.host]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.proxy.host[quarkus.oidc.proxy.host]` [.description] -- The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the ""host"" config item must be configured to enable the usage of a Proxy. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.proxy.port]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.proxy.port[quarkus.oidc.proxy.port]` [.description] -- The port number of the Proxy. Default value is 80. --|int |`80` a| [[quarkus-oidc-general-config-items_quarkus.oidc.proxy.username]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.proxy.username[quarkus.oidc.proxy.username]` [.description] -- The username, if Proxy needs authentication. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.proxy.password]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.proxy.password[quarkus.oidc.proxy.password]` [.description] -- The password, if Proxy needs authentication. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.redirect-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.redirect-path[quarkus.oidc.authentication.redirect-path]` [.description] -- Relative path for calculating a ""redirect_uri"" query parameter. It has to start from a forward slash and will be appended to the request URI's host and port. For example, if the current request URI is 'https://localhost:8080/service' then a 'redirect_uri' parameter will be set to 'https://localhost:8080/' if this property is set to '/' and be the same as the request URI if this property has not been configured. Note the original request URI will be restored after the user has authenticated. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.restore-path-after-redirect]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.restore-path-after-redirect[quarkus.oidc.authentication.restore-path-after-redirect]` [.description] -- If this property is set to 'true' then the original request URI which was used before the authentication will be restored after the user has been redirected back to the application. --|boolean |`true` a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.remove-redirect-parameters]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.remove-redirect-parameters[quarkus.oidc.authentication.remove-redirect-parameters]` [.description] -- Remove the query parameters such as 'code' and 'state' set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters. --|boolean |`true` a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.verify-access-token]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.verify-access-token[quarkus.oidc.authentication.verify-access-token]` [.description] -- Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow. ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles. Access token is not verified by default since it is meant to be propagated to the downstream services. The verification of the access token should be enabled if it is injected as a JWT token. Access tokens obtained as part of the code flow will always be verified if `quarkus.oidc.roles.source` property is set to `accesstoken` which means the authorization decision will be based on the roles extracted from the access token. Bearer access tokens are always verified. --|boolean |`false` a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.force-redirect-https-scheme]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.force-redirect-https-scheme[quarkus.oidc.authentication.force-redirect-https-scheme]` [.description] -- Force 'https' as the 'redirect_uri' parameter scheme when running behind an SSL terminating reverse proxy. This property, if enabled, will also affect the logout `post_logout_redirect_uri` and the local redirect requests. --|boolean |`false` a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.scopes]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.scopes[quarkus.oidc.authentication.scopes]` [.description] -- List of scopes --|list of string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.cookie-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.cookie-path[quarkus.oidc.authentication.cookie-path]` [.description] -- Cookie path parameter value which, if set, will be used for the session, state and post logout cookies. It may need to be set when the redirect path has a root different to that of the original request URL. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.cookie-domain]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.cookie-domain[quarkus.oidc.authentication.cookie-domain]` [.description] -- Cookie domain parameter value which, if set, will be used for the session, state and post logout cookies. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.user-info-required]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.user-info-required[quarkus.oidc.authentication.user-info-required]` [.description] -- If this property is set to 'true' then an OIDC UserInfo endpoint will be called --|boolean |`false` a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.session-age-extension]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.session-age-extension[quarkus.oidc.authentication.session-age-extension]` [.description] -- Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user will be redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a non-zero value then the expired ID token can be refreshed before the session has expired. This property will be ignored if the `token.refresh-expired` property has not been enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`5M` a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.xhr-auto-redirect]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.xhr-auto-redirect[quarkus.oidc.authentication.xhr-auto-redirect]` [.description] -- If this property is set to 'true' then a normal 302 redirect response will be returned if the request was initiated via XMLHttpRequest and the current user needs to be (re)authenticated which may not be desirable for Single Page Applications since XMLHttpRequest automatically following the redirect may not work given that OIDC authorization endpoints typically do not support CORS. If this property is set to `false` then a status code of '499' will be returned to allow the client to handle the redirect manually --|boolean |`true` a| [[quarkus-oidc-general-config-items_quarkus.oidc.tls.verification]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.tls.verification[quarkus.oidc.tls.verification]` [.description] -- Certificate validation and hostname verification, which can be one of the following values from enum `Verification`. Default is required. --|`required`, `none` |`required` a| [[quarkus-oidc-general-config-items_quarkus.oidc.logout.path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.logout.path[quarkus.oidc.logout.path]` [.description] -- The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.logout.post-logout-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.logout.post-logout-path[quarkus.oidc.logout.post-logout-path]` [.description] -- Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.authentication.extra-params-extra-params]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.authentication.extra-params-extra-params[quarkus.oidc.authentication.extra-params]` [.description] -- Additional properties which will be added as the query parameters to the authentication redirect URI. --|`Map` | h|[[quarkus-oidc-general-config-items_quarkus.oidc.named-tenants-additional-named-tenants]]link:#quarkus-oidc-general-config-items_quarkus.oidc.named-tenants-additional-named-tenants[Additional named tenants] h|Type h|Default a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.tenant-id]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.tenant-id[quarkus.oidc.""tenant"".tenant-id]` [.description] -- A unique tenant identifier. It must be set by `TenantConfigResolver` providers which resolve the tenant configuration dynamically and is optional in all other cases. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.tenant-enabled]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.tenant-enabled[quarkus.oidc.""tenant"".tenant-enabled]` [.description] -- If this tenant configuration is enabled. --|boolean |`true` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.application-type]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.application-type[quarkus.oidc.""tenant"".application-type]` [.description] -- The application type, which can be one of the following values from enum `ApplicationType`. --|`web-app`, `service` |`service` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.auth-server-url]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.auth-server-url[quarkus.oidc.""tenant"".auth-server-url]` [.description] -- The base URL of the OpenID Connect (OIDC) server, for example, 'https://host:port/auth'. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: 'https://host:port/auth/realms/++{++realm++}++' where '++{++realm++}++' has to be replaced by the name of the Keycloak realm. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.discovery-enabled]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.discovery-enabled[quarkus.oidc.""tenant"".discovery-enabled]` [.description] -- Enables OIDC discovery. If the discovery is disabled then the following properties must be configured: - 'authorization-path' and 'token-path' for the 'web-app' applications - 'jwks-path' or 'introspection-path' for both the 'web-app' and 'service' applications 'web-app' applications may also have 'user-info-path' and 'end-session-path' properties configured. --|boolean |`true` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authorization-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authorization-path[quarkus.oidc.""tenant"".authorization-path]` [.description] -- Relative path of the OIDC authorization endpoint which authenticates the users. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token-path[quarkus.oidc.""tenant"".token-path]` [.description] -- Relative path of the OIDC token endpoint which issues ID, access and refresh tokens. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.user-info-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.user-info-path[quarkus.oidc.""tenant"".user-info-path]` [.description] -- Relative path of the OIDC userinfo endpoint. This property must only be set for the 'web-app' applications if OIDC discovery is disabled and 'authentication.user-info-required' property is enabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.introspection-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.introspection-path[quarkus.oidc.""tenant"".introspection-path]` [.description] -- Relative path of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JWT tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens have to be verified or 2) JWT tokens have to be verified while the cached JWK verification set with no matching JWK is being refreshed. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.jwks-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.jwks-path[quarkus.oidc.""tenant"".jwks-path]` [.description] -- Relative path of the OIDC JWKS endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.end-session-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.end-session-path[quarkus.oidc.""tenant"".end-session-path]` [.description] -- Relative path of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the 'web-app' applications is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.connection-delay]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.connection-delay[quarkus.oidc.""tenant"".connection-delay]` [.description] -- The maximum amount of time the adapter will try connecting to the currently unavailable OIDC server for. For example, setting it to '20S' will let the adapter keep requesting the connection for up to 20 seconds. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.public-key]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.public-key[quarkus.oidc.""tenant"".public-key]` [.description] -- Public key for the local JWT token verification. OIDC server connection will not be created when this property is set. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.client-id]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.client-id[quarkus.oidc.""tenant"".client-id]` [.description] -- The client-id of the application. Each application has a client-id that is used to identify the application --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.roles.role-claim-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.roles.role-claim-path[quarkus.oidc.""tenant"".roles.role-claim-path]` [.description] -- Path to the claim containing an array of groups. It starts from the top level JWT JSON object and can contain multiple segments where each segment represents a JSON object name only, example: ""realm/groups"". Use double quotes with the namespace qualified claim names. This property can be used if a token has no 'groups' claim but has the groups set in a different claim. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.roles.role-claim-separator]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.roles.role-claim-separator[quarkus.oidc.""tenant"".roles.role-claim-separator]` [.description] -- Separator for splitting a string which may contain multiple group values. It will only be used if the ""role-claim-path"" property points to a custom claim whose value is a string. A single space will be used by default because the standard 'scope' claim may contain a space separated sequence. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.roles.source]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.roles.source[quarkus.oidc.""tenant"".roles.source]` [.description] -- Source of the principal roles. --|`idtoken`, `accesstoken`, `userinfo` | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.issuer]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.issuer[quarkus.oidc.""tenant"".token.issuer]` [.description] -- Expected issuer 'iss' claim value. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.audience]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.audience[quarkus.oidc.""tenant"".token.audience]` [.description] -- Expected audience 'aud' claim value which may be a string or an array of strings. --|list of string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.token-type]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.token-type[quarkus.oidc.""tenant"".token.token-type]` [.description] -- Expected token type --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.lifespan-grace]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.lifespan-grace[quarkus.oidc.""tenant"".token.lifespan-grace]` [.description] -- Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds. --|int | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.principal-claim]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.principal-claim[quarkus.oidc.""tenant"".token.principal-claim]` [.description] -- Name of the claim which contains a principal name. By default, the 'upn', 'preferred_username' and `sub` claims are checked. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.refresh-expired]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.refresh-expired[quarkus.oidc.""tenant"".token.refresh-expired]` [.description] -- Refresh expired ID tokens. If this property is enabled then a refresh token request will be performed if the ID token has expired and, if successful, the local session will be updated with the new set of tokens. Otherwise, the local session will be invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case the user may not be challenged again if the OIDC provider session is still active. For this option be effective the `authentication.session-age-extension` property should also be set to a non-zero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type `ApplicationType++#++WEB_APP`++}++. --|boolean |`false` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.auto-refresh-interval]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.auto-refresh-interval[quarkus.oidc.""tenant"".token.auto-refresh-interval]` [.description] -- Token auto-refresh interval in seconds during the user re-authentication. If this option is set then the valid ID token will be refreshed if it will expire in less than a number of minutes set by this option. The user will still be authenticated if the ID token can no longer be refreshed but is still valid. This option will be ignored if the 'refresh-expired' property is not enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.forced-jwk-refresh-interval]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.token.forced-jwk-refresh-interval[quarkus.oidc.""tenant"".token.forced-jwk-refresh-interval]` [.description] -- Forced JWK set refresh interval in minutes. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10M` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.credentials.secret]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.credentials.secret[quarkus.oidc.""tenant"".credentials.secret]` [.description] -- Client secret which is used for a 'client_secret_basic' authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.credentials.client-secret.value]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.credentials.client-secret.value[quarkus.oidc.""tenant"".credentials.client-secret.value]` [.description] -- The client secret --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.credentials.client-secret.method]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.credentials.client-secret.method[quarkus.oidc.""tenant"".credentials.client-secret.method]` [.description] -- Authentication method. --|`basic`, `post` | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.credentials.jwt.secret]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.credentials.jwt.secret[quarkus.oidc.""tenant"".credentials.jwt.secret]` [.description] -- client_secret_jwt: JWT which includes client id as one of its claims is signed by the client secret and is submitted as a 'client_assertion' form parameter, while 'client_assertion_type' parameter is set to ""urn:ietf:params:oauth:client-assertion-type:jwt-bearer"". --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.credentials.jwt.lifespan]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.credentials.jwt.lifespan[quarkus.oidc.""tenant"".credentials.jwt.lifespan]` [.description] -- JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time. --|int |`10` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.proxy.host]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.proxy.host[quarkus.oidc.""tenant"".proxy.host]` [.description] -- The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the ""host"" config item must be configured to enable the usage of a Proxy. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.proxy.port]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.proxy.port[quarkus.oidc.""tenant"".proxy.port]` [.description] -- The port number of the Proxy. Default value is 80. --|int |`80` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.proxy.username]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.proxy.username[quarkus.oidc.""tenant"".proxy.username]` [.description] -- The username, if Proxy needs authentication. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.proxy.password]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.proxy.password[quarkus.oidc.""tenant"".proxy.password]` [.description] -- The password, if Proxy needs authentication. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.redirect-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.redirect-path[quarkus.oidc.""tenant"".authentication.redirect-path]` [.description] -- Relative path for calculating a ""redirect_uri"" query parameter. It has to start from a forward slash and will be appended to the request URI's host and port. For example, if the current request URI is 'https://localhost:8080/service' then a 'redirect_uri' parameter will be set to 'https://localhost:8080/' if this property is set to '/' and be the same as the request URI if this property has not been configured. Note the original request URI will be restored after the user has authenticated. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.restore-path-after-redirect]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.restore-path-after-redirect[quarkus.oidc.""tenant"".authentication.restore-path-after-redirect]` [.description] -- If this property is set to 'true' then the original request URI which was used before the authentication will be restored after the user has been redirected back to the application. --|boolean |`true` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.remove-redirect-parameters]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.remove-redirect-parameters[quarkus.oidc.""tenant"".authentication.remove-redirect-parameters]` [.description] -- Remove the query parameters such as 'code' and 'state' set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters. --|boolean |`true` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.verify-access-token]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.verify-access-token[quarkus.oidc.""tenant"".authentication.verify-access-token]` [.description] -- Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow. ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles. Access token is not verified by default since it is meant to be propagated to the downstream services. The verification of the access token should be enabled if it is injected as a JWT token. Access tokens obtained as part of the code flow will always be verified if `quarkus.oidc.roles.source` property is set to `accesstoken` which means the authorization decision will be based on the roles extracted from the access token. Bearer access tokens are always verified. --|boolean |`false` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.force-redirect-https-scheme]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.force-redirect-https-scheme[quarkus.oidc.""tenant"".authentication.force-redirect-https-scheme]` [.description] -- Force 'https' as the 'redirect_uri' parameter scheme when running behind an SSL terminating reverse proxy. This property, if enabled, will also affect the logout `post_logout_redirect_uri` and the local redirect requests. --|boolean |`false` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.scopes]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.scopes[quarkus.oidc.""tenant"".authentication.scopes]` [.description] -- List of scopes --|list of string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.extra-params-extra-params]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.extra-params-extra-params[quarkus.oidc.""tenant"".authentication.extra-params]` [.description] -- Additional properties which will be added as the query parameters to the authentication redirect URI. --|`Map` | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.cookie-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.cookie-path[quarkus.oidc.""tenant"".authentication.cookie-path]` [.description] -- Cookie path parameter value which, if set, will be used for the session, state and post logout cookies. It may need to be set when the redirect path has a root different to that of the original request URL. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.cookie-domain]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.cookie-domain[quarkus.oidc.""tenant"".authentication.cookie-domain]` [.description] -- Cookie domain parameter value which, if set, will be used for the session, state and post logout cookies. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.user-info-required]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.user-info-required[quarkus.oidc.""tenant"".authentication.user-info-required]` [.description] -- If this property is set to 'true' then an OIDC UserInfo endpoint will be called --|boolean |`false` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.session-age-extension]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.session-age-extension[quarkus.oidc.""tenant"".authentication.session-age-extension]` [.description] -- Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user will be redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a non-zero value then the expired ID token can be refreshed before the session has expired. This property will be ignored if the `token.refresh-expired` property has not been enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`5M` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.xhr-auto-redirect]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.authentication.xhr-auto-redirect[quarkus.oidc.""tenant"".authentication.xhr-auto-redirect]` [.description] -- If this property is set to 'true' then a normal 302 redirect response will be returned if the request was initiated via XMLHttpRequest and the current user needs to be (re)authenticated which may not be desirable for Single Page Applications since XMLHttpRequest automatically following the redirect may not work given that OIDC authorization endpoints typically do not support CORS. If this property is set to `false` then a status code of '499' will be returned to allow the client to handle the redirect manually --|boolean |`true` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.tls.verification]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.tls.verification[quarkus.oidc.""tenant"".tls.verification]` [.description] -- Certificate validation and hostname verification, which can be one of the following values from enum `Verification`. Default is required. --|`required`, `none` |`required` a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.logout.path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.logout.path[quarkus.oidc.""tenant"".logout.path]` [.description] -- The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification. --|string | a| [[quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.logout.post-logout-path]]`link:#quarkus-oidc-general-config-items_quarkus.oidc.-tenant-.logout.post-logout-path[quarkus.oidc.""tenant"".logout.post-logout-path]` [.description] -- Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI. --|string | |=== ifndef::no-duration-note[] [NOTE] [[duration-note-anchor]] .About the Duration format ==== The format for durations uses the standard `java.time.Duration` format. You can learn more about it in the link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-[Duration#parse() javadoc]. You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, `PT` is implicitly prepended to the value to obtain a standard `java.time.Duration` format. ==== endif::no-duration-note[] ",12167,True,3755.4651214748083,median "//===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the SplitAnalysis class as well as mutator functions for // live range splitting. // //===----------------------------------------------------------------------===// #include ""SplitKit.h"" #include ""llvm/ADT/Statistic.h"" #include ""llvm/CodeGen/LiveIntervalAnalysis.h"" #include ""llvm/CodeGen/LiveRangeEdit.h"" #include ""llvm/CodeGen/MachineBlockFrequencyInfo.h"" #include ""llvm/CodeGen/MachineDominators.h"" #include ""llvm/CodeGen/MachineInstrBuilder.h"" #include ""llvm/CodeGen/MachineLoopInfo.h"" #include ""llvm/CodeGen/MachineRegisterInfo.h"" #include ""llvm/CodeGen/VirtRegMap.h"" #include ""llvm/Support/Debug.h"" #include ""llvm/Support/raw_ostream.h"" #include ""llvm/Target/TargetInstrInfo.h"" #include ""llvm/Target/TargetMachine.h"" using namespace llvm; #define DEBUG_TYPE ""regalloc"" STATISTIC(NumFinished, ""Number of splits finished""); STATISTIC(NumSimple, ""Number of splits that were simple""); STATISTIC(NumCopies, ""Number of copies inserted for splitting""); STATISTIC(NumRemats, ""Number of rematerialized defs for splitting""); STATISTIC(NumRepairs, ""Number of invalid live ranges repaired""); //===----------------------------------------------------------------------===// // Last Insert Point Analysis //===----------------------------------------------------------------------===// InsertPointAnalysis::InsertPointAnalysis(const LiveIntervals &lis, unsigned BBNum) : LIS(lis), LastInsertPoint(BBNum) {} SlotIndex InsertPointAnalysis::computeLastInsertPoint(const LiveInterval &CurLI, const MachineBasicBlock &MBB) { unsigned Num = MBB.getNumber(); std::pair &LIP = LastInsertPoint[Num]; SlotIndex MBBEnd = LIS.getMBBEndIdx(&MBB); SmallVector EHPadSucessors; for (const MachineBasicBlock *SMBB : MBB.successors()) if (SMBB->isEHPad()) EHPadSucessors.push_back(SMBB); // Compute insert points on the first call. The pair is independent of the // current live interval. if (!LIP.first.isValid()) { MachineBasicBlock::const_iterator FirstTerm = MBB.getFirstTerminator(); if (FirstTerm == MBB.end()) LIP.first = MBBEnd; else LIP.first = LIS.getInstructionIndex(*FirstTerm); // If there is a landing pad successor, also find the call instruction. if (EHPadSucessors.empty()) return LIP.first; // There may not be a call instruction (?) in which case we ignore LPad. LIP.second = LIP.first; for (MachineBasicBlock::const_iterator I = MBB.end(), E = MBB.begin(); I != E;) { --I; if (I->isCall()) { LIP.second = LIS.getInstructionIndex(*I); break; } } } // If CurLI is live into a landing pad successor, move the last insert point // back to the call that may throw. if (!LIP.second) return LIP.first; if (none_of(EHPadSucessors, [&](const MachineBasicBlock *EHPad) { return LIS.isLiveInToMBB(CurLI, EHPad); })) return LIP.first; // Find the value leaving MBB. const VNInfo *VNI = CurLI.getVNInfoBefore(MBBEnd); if (!VNI) return LIP.first; // If the value leaving MBB was defined after the call in MBB, it can't // really be live-in to the landing pad. This can happen if the landing pad // has a PHI, and this register is undef on the exceptional edge. // if (!SlotIndex::isEarlierInstr(VNI->def, LIP.second) && VNI->def < MBBEnd) return LIP.first; // Value is properly live-in to the landing pad. // Only allow inserts before the call. return LIP.second; } MachineBasicBlock::iterator InsertPointAnalysis::getLastInsertPointIter(const LiveInterval &CurLI, MachineBasicBlock &MBB) { SlotIndex LIP = getLastInsertPoint(CurLI, MBB); if (LIP == LIS.getMBBEndIdx(&MBB)) return MBB.end(); return LIS.getInstructionFromIndex(LIP); } //===----------------------------------------------------------------------===// // Split Analysis //===----------------------------------------------------------------------===// SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis, const MachineLoopInfo &mli) : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli), TII(*MF.getSubtarget().getInstrInfo()), CurLI(nullptr), IPA(lis, MF.getNumBlockIDs()) {} void SplitAnalysis::clear() { UseSlots.clear(); UseBlocks.clear(); ThroughBlocks.clear(); CurLI = nullptr; DidRepairRange = false; } /// analyzeUses - Count instructions, basic blocks, and loops using CurLI. void SplitAnalysis::analyzeUses() { assert(UseSlots.empty() && ""Call clear first""); // First get all the defs from the interval values. This provides the correct // slots for early clobbers. for (const VNInfo *VNI : CurLI->valnos) if (!VNI->isPHIDef() && !VNI->isUnused()) UseSlots.push_back(VNI->def); // Get use slots form the use-def chain. const MachineRegisterInfo &MRI = MF.getRegInfo(); for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg)) if (!MO.isUndef()) UseSlots.push_back(LIS.getInstructionIndex(*MO.getParent()).getRegSlot()); array_pod_sort(UseSlots.begin(), UseSlots.end()); // Remove duplicates, keeping the smaller slot for each instruction. // That is what we want for early clobbers. UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(), SlotIndex::isSameInstr), UseSlots.end()); // Compute per-live block info. if (!calcLiveBlockInfo()) { // FIXME: calcLiveBlockInfo found inconsistencies in the live range. // I am looking at you, RegisterCoalescer! DidRepairRange = true; ++NumRepairs; DEBUG(dbgs() << ""*** Fixing inconsistent live interval! ***\\n""); const_cast(LIS) .shrinkToUses(const_cast(CurLI)); UseBlocks.clear(); ThroughBlocks.clear(); bool fixed = calcLiveBlockInfo(); (void)fixed; assert(fixed && ""Couldn't fix broken live interval""); } DEBUG(dbgs() << ""Analyze counted "" << UseSlots.size() << "" instrs in "" << UseBlocks.size() << "" blocks, through "" << NumThroughBlocks << "" blocks.\\n""); } /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks /// where CurLI is live. bool SplitAnalysis::calcLiveBlockInfo() { ThroughBlocks.resize(MF.getNumBlockIDs()); NumThroughBlocks = NumGapBlocks = 0; if (CurLI->empty()) return true; LiveInterval::const_iterator LVI = CurLI->begin(); LiveInterval::const_iterator LVE = CurLI->end(); SmallVectorImpl::const_iterator UseI, UseE; UseI = UseSlots.begin(); UseE = UseSlots.end(); // Loop over basic blocks where CurLI is live. MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start)->getIterator(); for (;;) { BlockInfo BI; BI.MBB = &*MFI; SlotIndex Start, Stop; std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); // If the block contains no uses, the range must be live through. At one // point, RegisterCoalescer could create dangling ranges that ended // mid-block. if (UseI == UseE || *UseI >= Stop) { ++NumThroughBlocks; ThroughBlocks.set(BI.MBB->getNumber()); // The range shouldn't end mid-block if there are no uses. This shouldn't // happen. if (LVI->end < Stop) return false; } else { // This block has uses. Find the first and last uses in the block. BI.FirstInstr = *UseI; assert(BI.FirstInstr >= Start); do ++UseI; while (UseI != UseE && *UseI < Stop); BI.LastInstr = UseI[-1]; assert(BI.LastInstr < Stop); // LVI is the first live segment overlapping MBB. BI.LiveIn = LVI->start <= Start; // When not live in, the first use should be a def. if (!BI.LiveIn) { assert(LVI->start == LVI->valno->def && ""Dangling Segment start""); assert(LVI->start == BI.FirstInstr && ""First instr should be a def""); BI.FirstDef = BI.FirstInstr; } // Look for gaps in the live range. BI.LiveOut = true; while (LVI->end < Stop) { SlotIndex LastStop = LVI->end; if (++LVI == LVE || LVI->start >= Stop) { BI.LiveOut = false; BI.LastInstr = LastStop; break; } if (LastStop < LVI->start) { // There is a gap in the live range. Create duplicate entries for the // live-in snippet and the live-out snippet. ++NumGapBlocks; // Push the Live-in part. BI.LiveOut = false; UseBlocks.push_back(BI); UseBlocks.back().LastInstr = LastStop; // Set up BI for the live-out part. BI.LiveIn = false; BI.LiveOut = true; BI.FirstInstr = BI.FirstDef = LVI->start; } // A Segment that starts in the middle of the block must be a def. assert(LVI->start == LVI->valno->def && ""Dangling Segment start""); if (!BI.FirstDef) BI.FirstDef = LVI->start; } UseBlocks.push_back(BI); // LVI is now at LVE or LVI->end >= Stop. if (LVI == LVE) break; } // Live segment ends exactly at Stop. Move to the next segment. if (LVI->end == Stop && ++LVI == LVE) break; // Pick the next basic block. if (LVI->start < Stop) ++MFI; else MFI = LIS.getMBBFromIndex(LVI->start)->getIterator(); } assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && ""Bad block count""); return true; } unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const { if (cli->empty()) return 0; LiveInterval *li = const_cast(cli); LiveInterval::iterator LVI = li->begin(); LiveInterval::iterator LVE = li->end(); unsigned Count = 0; // Loop over basic blocks where li is live. MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start)->getIterator(); SlotIndex Stop = LIS.getMBBEndIdx(&*MFI); for (;;) { ++Count; LVI = li->advanceTo(LVI, Stop); if (LVI == LVE) return Count; do { ++MFI; Stop = LIS.getMBBEndIdx(&*MFI); } while (Stop <= LVI->start); } } bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const { unsigned OrigReg = VRM.getOriginal(CurLI->reg); const LiveInterval &Orig = LIS.getInterval(OrigReg); assert(!Orig.empty() && ""Splitting empty interval?""); LiveInterval::const_iterator I = Orig.find(Idx); // Range containing Idx should begin at Idx. if (I != Orig.end() && I->start <= Idx) return I->start == Idx; // Range does not contain Idx, previous must end at Idx. return I != Orig.begin() && (--I)->end == Idx; } void SplitAnalysis::analyze(const LiveInterval *li) { clear(); CurLI = li; analyzeUses(); } //===----------------------------------------------------------------------===// // Split Editor //===----------------------------------------------------------------------===// /// Create a new SplitEditor for editing the LiveInterval analyzed by SA. SplitEditor::SplitEditor(SplitAnalysis &sa, AliasAnalysis &aa, LiveIntervals &lis, VirtRegMap &vrm, MachineDominatorTree &mdt, MachineBlockFrequencyInfo &mbfi) : SA(sa), AA(aa), LIS(lis), VRM(vrm), MRI(vrm.getMachineFunction().getRegInfo()), MDT(mdt), TII(*vrm.getMachineFunction().getSubtarget().getInstrInfo()), TRI(*vrm.getMachineFunction().getSubtarget().getRegisterInfo()), MBFI(mbfi), Edit(nullptr), OpenIdx(0), SpillMode(SM_Partition), RegAssign(Allocator) {} void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) { Edit = &LRE; SpillMode = SM; OpenIdx = 0; RegAssign.clear(); Values.clear(); // Reset the LiveRangeCalc instances needed for this spill mode. LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, &LIS.getVNInfoAllocator()); if (SpillMode) LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, &LIS.getVNInfoAllocator()); // We don't need an AliasAnalysis since we will only be performing // cheap-as-a-copy remats anyway. Edit->anyRematerializable(nullptr); } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void SplitEditor::dump() const { if (RegAssign.empty()) { dbgs() << "" empty\\n""; return; } for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I) dbgs() << "" ["" << I.start() << ';' << I.stop() << ""):"" << I.value(); dbgs() << '\\n'; } #endif LiveInterval::SubRange &SplitEditor::getSubRangeForMask(LaneBitmask LM, LiveInterval &LI) { for (LiveInterval::SubRange &S : LI.subranges()) if (S.LaneMask == LM) return S; llvm_unreachable(""SubRange for this mask not found""); } void SplitEditor::addDeadDef(LiveInterval &LI, VNInfo *VNI, bool Original) { if (!LI.hasSubRanges()) { LI.createDeadDef(VNI); return; } SlotIndex Def = VNI->def; if (Original) { // If we are transferring a def from the original interval, make sure // to only update the subranges for which the original subranges had // a def at this location. for (LiveInterval::SubRange &S : LI.subranges()) { auto &PS = getSubRangeForMask(S.LaneMask, Edit->getParent()); VNInfo *PV = PS.getVNInfoAt(Def); if (PV != nullptr && PV->def == Def) S.createDeadDef(Def, LIS.getVNInfoAllocator()); } } else { // This is a new def: either from rematerialization, or from an inserted // copy. Since rematerialization can regenerate a definition of a sub- // register, we need to check which subranges need to be updated. const MachineInstr *DefMI = LIS.getInstructionFromIndex(Def); assert(DefMI != nullptr); LaneBitmask LM; for (const MachineOperand &DefOp : DefMI->defs()) { unsigned R = DefOp.getReg(); if (R != LI.reg) continue; if (unsigned SR = DefOp.getSubReg()) LM |= TRI.getSubRegIndexLaneMask(SR); else { LM = MRI.getMaxLaneMaskForVReg(R); break; } } for (LiveInterval::SubRange &S : LI.subranges()) if ((S.LaneMask & LM).any()) S.createDeadDef(Def, LIS.getVNInfoAllocator()); } } VNInfo *SplitEditor::defValue(unsigned RegIdx, const VNInfo *ParentVNI, SlotIndex Idx, bool Original) { assert(ParentVNI && ""Mapping NULL value""); assert(Idx.isValid() && ""Invalid SlotIndex""); assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && ""Bad Parent VNI""); LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); // Create a new value. VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator()); bool Force = LI->hasSubRanges(); ValueForcePair FP(Force ? nullptr : VNI, Force); // Use insert for lookup, so we can add missing values with a second lookup. std::pair InsP = Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id), FP)); // This was the first time (RegIdx, ParentVNI) was mapped, and it is not // forced. Keep it as a simple def without any liveness. if (!Force && InsP.second) return VNI; // If the previous value was a simple mapping, add liveness for it now. if (VNInfo *OldVNI = InsP.first->second.getPointer()) { addDeadDef(*LI, OldVNI, Original); // No longer a simple mapping. Switch to a complex mapping. If the // interval has subranges, make it a forced mapping. InsP.first->second = ValueForcePair(nullptr, Force); } // This is a complex mapping, add liveness for VNI addDeadDef(*LI, VNI, Original); return VNI; } void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) { assert(ParentVNI && ""Mapping NULL value""); ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)]; VNInfo *VNI = VFP.getPointer(); // ParentVNI was either unmapped or already complex mapped. Either way, just // set the force bit. if (!VNI) { VFP.setInt(true); return; } // This was previously a single mapping. Make sure the old def is represented // by a trivial live range. addDeadDef(LIS.getInterval(Edit->get(RegIdx)), VNI, false); // Mark as complex mapped, forced. VFP = ValueForcePair(nullptr, true); } VNInfo *SplitEditor::defFromParent(unsigned RegIdx, VNInfo *ParentVNI, SlotIndex UseIdx, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) { MachineInstr *CopyMI = nullptr; SlotIndex Def; LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); // We may be trying to avoid interference that ends at a deleted instruction, // so always begin RegIdx 0 early and all others late. bool Late = RegIdx != 0; // Attempt cheap-as-a-copy rematerialization. unsigned Original = VRM.getOriginal(Edit->get(RegIdx)); LiveInterval &OrigLI = LIS.getInterval(Original); VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx); bool DidRemat = false; if (OrigVNI) { LiveRangeEdit::Remat RM(ParentVNI); RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def); if (Edit->canRematerializeAt(RM, OrigVNI, UseIdx, true)) { Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late); ++NumRemats; DidRemat = true; } } if (!DidRemat) { // Can't remat, just insert a copy from parent. CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg) .addReg(Edit->getReg()); Def = LIS.getSlotIndexes() ->insertMachineInstrInMaps(*CopyMI, Late) .getRegSlot(); ++NumCopies; } // Define the value in Reg. return defValue(RegIdx, ParentVNI, Def, false); } /// Create a new virtual register and live interval. unsigned SplitEditor::openIntv() { // Create the complement as index 0. if (Edit->empty()) Edit->createEmptyInterval(); // Create the open interval. OpenIdx = Edit->size(); Edit->createEmptyInterval(); return OpenIdx; } void SplitEditor::selectIntv(unsigned Idx) { assert(Idx != 0 && ""Cannot select the complement interval""); assert(Idx < Edit->size() && ""Can only select previously opened interval""); DEBUG(dbgs() << "" selectIntv "" << OpenIdx << "" -> "" << Idx << '\\n'); OpenIdx = Idx; } SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) { assert(OpenIdx && ""openIntv not called before enterIntvBefore""); DEBUG(dbgs() << "" enterIntvBefore "" << Idx); Idx = Idx.getBaseIndex(); VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); if (!ParentVNI) { DEBUG(dbgs() << "": not live\\n""); return Idx; } DEBUG(dbgs() << "": valno "" << ParentVNI->id << '\\n'); MachineInstr *MI = LIS.getInstructionFromIndex(Idx); assert(MI && ""enterIntvBefore called with invalid index""); VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI); return VNI->def; } SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) { assert(OpenIdx && ""openIntv not called before enterIntvAfter""); DEBUG(dbgs() << "" enterIntvAfter "" << Idx); Idx = Idx.getBoundaryIndex(); VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); if (!ParentVNI) { DEBUG(dbgs() << "": not live\\n""); return Idx; } DEBUG(dbgs() << "": valno "" << ParentVNI->id << '\\n'); MachineInstr *MI = LIS.getInstructionFromIndex(Idx); assert(MI && ""enterIntvAfter called with invalid index""); VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), std::next(MachineBasicBlock::iterator(MI))); return VNI->def; } SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) { assert(OpenIdx && ""openIntv not called before enterIntvAtEnd""); SlotIndex End = LIS.getMBBEndIdx(&MBB); SlotIndex Last = End.getPrevSlot(); DEBUG(dbgs() << "" enterIntvAtEnd BB#"" << MBB.getNumber() << "", "" << Last); VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last); if (!ParentVNI) { DEBUG(dbgs() << "": not live\\n""); return End; } DEBUG(dbgs() << "": valno "" << ParentVNI->id); VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB, SA.getLastSplitPointIter(&MBB)); RegAssign.insert(VNI->def, End, OpenIdx); DEBUG(dump()); return VNI->def; } /// useIntv - indicate that all instructions in MBB should use OpenLI. void SplitEditor::useIntv(const MachineBasicBlock &MBB) { useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB)); } void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) { assert(OpenIdx && ""openIntv not called before useIntv""); DEBUG(dbgs() << "" useIntv ["" << Start << ';' << End << ""):""); RegAssign.insert(Start, End, OpenIdx); DEBUG(dump()); } SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) { assert(OpenIdx && ""openIntv not called before leaveIntvAfter""); DEBUG(dbgs() << "" leaveIntvAfter "" << Idx); // The interval must be live beyond the instruction at Idx. SlotIndex Boundary = Idx.getBoundaryIndex(); VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary); if (!ParentVNI) { DEBUG(dbgs() << "": not live\\n""); return Boundary.getNextSlot(); } DEBUG(dbgs() << "": valno "" << ParentVNI->id << '\\n'); MachineInstr *MI = LIS.getInstructionFromIndex(Boundary); assert(MI && ""No instruction at index""); // In spill mode, make live ranges as short as possible by inserting the copy // before MI. This is only possible if that instruction doesn't redefine the // value. The inserted COPY is not a kill, and we don't need to recompute // the source live range. The spiller also won't try to hoist this copy. if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) && MI->readsVirtualRegister(Edit->getReg())) { forceRecompute(0, ParentVNI); defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); return Idx; } VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(), std::next(MachineBasicBlock::iterator(MI))); return VNI->def; } SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) { assert(OpenIdx && ""openIntv not called before leaveIntvBefore""); DEBUG(dbgs() << "" leaveIntvBefore "" << Idx); // The interval must be live into the instruction at Idx. Idx = Idx.getBaseIndex(); VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); if (!ParentVNI) { DEBUG(dbgs() << "": not live\\n""); return Idx.getNextSlot(); } DEBUG(dbgs() << "": valno "" << ParentVNI->id << '\\n'); MachineInstr *MI = LIS.getInstructionFromIndex(Idx); assert(MI && ""No instruction at index""); VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); return VNI->def; } SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) { assert(OpenIdx && ""openIntv not called before leaveIntvAtTop""); SlotIndex Start = LIS.getMBBStartIdx(&MBB); DEBUG(dbgs() << "" leaveIntvAtTop BB#"" << MBB.getNumber() << "", "" << Start); VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); if (!ParentVNI) { DEBUG(dbgs() << "": not live\\n""); return Start; } VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB, MBB.SkipPHIsLabelsAndDebug(MBB.begin())); RegAssign.insert(Start, VNI->def, OpenIdx); DEBUG(dump()); return VNI->def; } void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) { assert(OpenIdx && ""openIntv not called before overlapIntv""); const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) && ""Parent changes value in extended range""); assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) && ""Range cannot span basic blocks""); // The complement interval will be extended as needed by LRCalc.extend(). if (ParentVNI) forceRecompute(0, ParentVNI); DEBUG(dbgs() << "" overlapIntv ["" << Start << ';' << End << ""):""); RegAssign.insert(Start, End, OpenIdx); DEBUG(dump()); } //===----------------------------------------------------------------------===// // Spill modes //===----------------------------------------------------------------------===// void SplitEditor::removeBackCopies(SmallVectorImpl &Copies) { LiveInterval *LI = &LIS.getInterval(Edit->get(0)); DEBUG(dbgs() << ""Removing "" << Copies.size() << "" back-copies.\\n""); RegAssignMap::iterator AssignI; AssignI.setMap(RegAssign); for (unsigned i = 0, e = Copies.size(); i != e; ++i) { SlotIndex Def = Copies[i]->def; MachineInstr *MI = LIS.getInstructionFromIndex(Def); assert(MI && ""No instruction for back-copy""); MachineBasicBlock *MBB = MI->getParent(); MachineBasicBlock::iterator MBBI(MI); bool AtBegin; do AtBegin = MBBI == MBB->begin(); while (!AtBegin && (--MBBI)->isDebugValue()); DEBUG(dbgs() << ""Removing "" << Def << '\\t' << *MI); LIS.removeVRegDefAt(*LI, Def); LIS.RemoveMachineInstrFromMaps(*MI); MI->eraseFromParent(); // Adjust RegAssign if a register assignment is killed at Def. We want to // avoid calculating the live range of the source register if possible. AssignI.find(Def.getPrevSlot()); if (!AssignI.valid() || AssignI.start() >= Def) continue; // If MI doesn't kill the assigned register, just leave it. if (AssignI.stop() != Def) continue; unsigned RegIdx = AssignI.value(); if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) { DEBUG(dbgs() << "" cannot find simple kill of RegIdx "" << RegIdx << '\\n'); forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def)); } else { SlotIndex Kill = LIS.getInstructionIndex(*MBBI).getRegSlot(); DEBUG(dbgs() << "" move kill to "" << Kill << '\\t' << *MBBI); AssignI.setStop(Kill); } } } MachineBasicBlock* SplitEditor::findShallowDominator(MachineBasicBlock *MBB, MachineBasicBlock *DefMBB) { if (MBB == DefMBB) return MBB; assert(MDT.dominates(DefMBB, MBB) && ""MBB must be dominated by the def.""); const MachineLoopInfo &Loops = SA.Loops; const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB); MachineDomTreeNode *DefDomNode = MDT[DefMBB]; // Best candidate so far. MachineBasicBlock *BestMBB = MBB; unsigned BestDepth = UINT_MAX; for (;;) { const MachineLoop *Loop = Loops.getLoopFor(MBB); // MBB isn't in a loop, it doesn't get any better. All dominators have a // higher frequency by definition. if (!Loop) { DEBUG(dbgs() << ""Def in BB#"" << DefMBB->getNumber() << "" dominates BB#"" << MBB->getNumber() << "" at depth 0\\n""); return MBB; } // We'll never be able to exit the DefLoop. if (Loop == DefLoop) { DEBUG(dbgs() << ""Def in BB#"" << DefMBB->getNumber() << "" dominates BB#"" << MBB->getNumber() << "" in the same loop\\n""); return MBB; } // Least busy dominator seen so far. unsigned Depth = Loop->getLoopDepth(); if (Depth < BestDepth) { BestMBB = MBB; BestDepth = Depth; DEBUG(dbgs() << ""Def in BB#"" << DefMBB->getNumber() << "" dominates BB#"" << MBB->getNumber() << "" at depth "" << Depth << '\\n'); } // Leave loop by going to the immediate dominator of the loop header. // This is a bigger stride than simply walking up the dominator tree. MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom(); // Too far up the dominator tree? if (!IDom || !MDT.dominates(DefDomNode, IDom)) return BestMBB; MBB = IDom->getBlock(); } } void SplitEditor::computeRedundantBackCopies( DenseSet &NotToHoistSet, SmallVectorImpl &BackCopies) { LiveInterval *LI = &LIS.getInterval(Edit->get(0)); LiveInterval *Parent = &Edit->getParent(); SmallVector, 8> EqualVNs(Parent->getNumValNums()); SmallPtrSet DominatedVNIs; // Aggregate VNIs having the same value as ParentVNI. for (VNInfo *VNI : LI->valnos) { if (VNI->isUnused()) continue; VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); EqualVNs[ParentVNI->id].insert(VNI); } // For VNI aggregation of each ParentVNI, collect dominated, i.e., // redundant VNIs to BackCopies. for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { VNInfo *ParentVNI = Parent->getValNumInfo(i); if (!NotToHoistSet.count(ParentVNI->id)) continue; SmallPtrSetIterator It1 = EqualVNs[ParentVNI->id].begin(); SmallPtrSetIterator It2 = It1; for (; It1 != EqualVNs[ParentVNI->id].end(); ++It1) { It2 = It1; for (++It2; It2 != EqualVNs[ParentVNI->id].end(); ++It2) { if (DominatedVNIs.count(*It1) || DominatedVNIs.count(*It2)) continue; MachineBasicBlock *MBB1 = LIS.getMBBFromIndex((*It1)->def); MachineBasicBlock *MBB2 = LIS.getMBBFromIndex((*It2)->def); if (MBB1 == MBB2) { DominatedVNIs.insert((*It1)->def < (*It2)->def ? (*It2) : (*It1)); } else if (MDT.dominates(MBB1, MBB2)) { DominatedVNIs.insert(*It2); } else if (MDT.dominates(MBB2, MBB1)) { DominatedVNIs.insert(*It1); } } } if (!DominatedVNIs.empty()) { forceRecompute(0, ParentVNI); for (auto VNI : DominatedVNIs) { BackCopies.push_back(VNI); } DominatedVNIs.clear(); } } } /// For SM_Size mode, find a common dominator for all the back-copies for /// the same ParentVNI and hoist the backcopies to the dominator BB. /// For SM_Speed mode, if the common dominator is hot and it is not beneficial /// to do the hoisting, simply remove the dominated backcopies for the same /// ParentVNI. void SplitEditor::hoistCopies() { // Get the complement interval, always RegIdx 0. LiveInterval *LI = &LIS.getInterval(Edit->get(0)); LiveInterval *Parent = &Edit->getParent(); // Track the nearest common dominator for all back-copies for each ParentVNI, // indexed by ParentVNI->id. typedef std::pair DomPair; SmallVector NearestDom(Parent->getNumValNums()); // The total cost of all the back-copies for each ParentVNI. SmallVector Costs(Parent->getNumValNums()); // The ParentVNI->id set for which hoisting back-copies are not beneficial // for Speed. DenseSet NotToHoistSet; // Find the nearest common dominator for parent values with multiple // back-copies. If a single back-copy dominates, put it in DomPair.second. for (VNInfo *VNI : LI->valnos) { if (VNI->isUnused()) continue; VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); assert(ParentVNI && ""Parent not live at complement def""); // Don't hoist remats. The complement is probably going to disappear // completely anyway. if (Edit->didRematerialize(ParentVNI)) continue; MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def); DomPair &Dom = NearestDom[ParentVNI->id]; // Keep directly defined parent values. This is either a PHI or an // instruction in the complement range. All other copies of ParentVNI // should be eliminated. if (VNI->def == ParentVNI->def) { DEBUG(dbgs() << ""Direct complement def at "" << VNI->def << '\\n'); Dom = DomPair(ValMBB, VNI->def); continue; } // Skip the singly mapped values. There is nothing to gain from hoisting a // single back-copy. if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) { DEBUG(dbgs() << ""Single complement def at "" << VNI->def << '\\n'); continue; } if (!Dom.first) { // First time we see ParentVNI. VNI dominates itself. Dom = DomPair(ValMBB, VNI->def); } else if (Dom.first == ValMBB) { // Two defs in the same block. Pick the earlier def. if (!Dom.second.isValid() || VNI->def < Dom.second) Dom.second = VNI->def; } else { // Different basic blocks. Check if one dominates. MachineBasicBlock *Near = MDT.findNearestCommonDominator(Dom.first, ValMBB); if (Near == ValMBB) // Def ValMBB dominates. Dom = DomPair(ValMBB, VNI->def); else if (Near != Dom.first) // None dominate. Hoist to common dominator, need new def. Dom = DomPair(Near, SlotIndex()); Costs[ParentVNI->id] += MBFI.getBlockFreq(ValMBB); } DEBUG(dbgs() << ""Multi-mapped complement "" << VNI->id << '@' << VNI->def << "" for parent "" << ParentVNI->id << '@' << ParentVNI->def << "" hoist to BB#"" << Dom.first->getNumber() << ' ' << Dom.second << '\\n'); } // Insert the hoisted copies. for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { DomPair &Dom = NearestDom[i]; if (!Dom.first || Dom.second.isValid()) continue; // This value needs a hoisted copy inserted at the end of Dom.first. VNInfo *ParentVNI = Parent->getValNumInfo(i); MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def); // Get a less loopy dominator than Dom.first. Dom.first = findShallowDominator(Dom.first, DefMBB); if (SpillMode == SM_Speed && MBFI.getBlockFreq(Dom.first) > Costs[ParentVNI->id]) { NotToHoistSet.insert(ParentVNI->id); continue; } SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot(); Dom.second = defFromParent(0, ParentVNI, Last, *Dom.first, SA.getLastSplitPointIter(Dom.first))->def; } // Remove redundant back-copies that are now known to be dominated by another // def with the same value. SmallVector BackCopies; for (VNInfo *VNI : LI->valnos) { if (VNI->isUnused()) continue; VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); const DomPair &Dom = NearestDom[ParentVNI->id]; if (!Dom.first || Dom.second == VNI->def || NotToHoistSet.count(ParentVNI->id)) continue; BackCopies.push_back(VNI); forceRecompute(0, ParentVNI); } // If it is not beneficial to hoist all the BackCopies, simply remove // redundant BackCopies in speed mode. if (SpillMode == SM_Speed && !NotToHoistSet.empty()) computeRedundantBackCopies(NotToHoistSet, BackCopies); removeBackCopies(BackCopies); } /// transferValues - Transfer all possible values to the new live ranges. /// Values that were rematerialized are left alone, they need LRCalc.extend(). bool SplitEditor::transferValues() { bool Skipped = false; RegAssignMap::const_iterator AssignI = RegAssign.begin(); for (const LiveRange::Segment &S : Edit->getParent()) { DEBUG(dbgs() << "" blit "" << S << ':'); VNInfo *ParentVNI = S.valno; // RegAssign has holes where RegIdx 0 should be used. SlotIndex Start = S.start; AssignI.advanceTo(Start); do { unsigned RegIdx; SlotIndex End = S.end; if (!AssignI.valid()) { RegIdx = 0; } else if (AssignI.start() <= Start) { RegIdx = AssignI.value(); if (AssignI.stop() < End) { End = AssignI.stop(); ++AssignI; } } else { RegIdx = 0; End = std::min(End, AssignI.start()); } // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI. DEBUG(dbgs() << "" ["" << Start << ';' << End << "")="" << RegIdx << '(' << PrintReg(Edit->get(RegIdx)) << ')'); LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); // Check for a simply defined value that can be blitted directly. ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id)); if (VNInfo *VNI = VFP.getPointer()) { DEBUG(dbgs() << ':' << VNI->id); LI.addSegment(LiveInterval::Segment(Start, End, VNI)); Start = End; continue; } // Skip values with forced recomputation. if (VFP.getInt()) { DEBUG(dbgs() << ""(recalc)""); Skipped = true; Start = End; continue; } LiveRangeCalc &LRC = getLRCalc(RegIdx); // This value has multiple defs in RegIdx, but it wasn't rematerialized, // so the live range is accurate. Add live-in blocks in [Start;End) to the // LiveInBlocks. MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); SlotIndex BlockStart, BlockEnd; std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(&*MBB); // The first block may be live-in, or it may have its own def. if (Start != BlockStart) { VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End)); assert(VNI && ""Missing def for complex mapped value""); DEBUG(dbgs() << ':' << VNI->id << ""*BB#"" << MBB->getNumber()); // MBB has its own def. Is it also live-out? if (BlockEnd <= End) LRC.setLiveOutValue(&*MBB, VNI); // Skip to the next block for live-in. ++MBB; BlockStart = BlockEnd; } // Handle the live-in blocks covered by [Start;End). assert(Start <= BlockStart && ""Expected live-in block""); while (BlockStart < End) { DEBUG(dbgs() << "">BB#"" << MBB->getNumber()); BlockEnd = LIS.getMBBEndIdx(&*MBB); if (BlockStart == ParentVNI->def) { // This block has the def of a parent PHI, so it isn't live-in. assert(ParentVNI->isPHIDef() && ""Non-phi defined at block start?""); VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End)); assert(VNI && ""Missing def for complex mapped parent PHI""); if (End >= BlockEnd) LRC.setLiveOutValue(&*MBB, VNI); // Live-out as well. } else { // This block needs a live-in value. The last block covered may not // be live-out. if (End < BlockEnd) LRC.addLiveInBlock(LI, MDT[&*MBB], End); else { // Live-through, and we don't know the value. LRC.addLiveInBlock(LI, MDT[&*MBB]); LRC.setLiveOutValue(&*MBB, nullptr); } } BlockStart = BlockEnd; ++MBB; } Start = End; } while (Start != S.end); DEBUG(dbgs() << '\\n'); } LRCalc[0].calculateValues(); if (SpillMode) LRCalc[1].calculateValues(); return Skipped; } static bool removeDeadSegment(SlotIndex Def, LiveRange &LR) { const LiveRange::Segment *Seg = LR.getSegmentContaining(Def); if (Seg == nullptr) return true; if (Seg->end != Def.getDeadSlot()) return false; // This is a dead PHI. Remove it. LR.removeSegment(*Seg, true); return true; } void SplitEditor::extendPHIRange(MachineBasicBlock &B, LiveRangeCalc &LRC, LiveRange &LR, LaneBitmask LM, ArrayRef Undefs) { for (MachineBasicBlock *P : B.predecessors()) { SlotIndex End = LIS.getMBBEndIdx(P); SlotIndex LastUse = End.getPrevSlot(); // The predecessor may not have a live-out value. That is OK, like an // undef PHI operand. LiveInterval &PLI = Edit->getParent(); // Need the cast because the inputs to ?: would otherwise be deemed // ""incompatible"": SubRange vs LiveInterval. LiveRange &PSR = !LM.all() ? getSubRangeForMask(LM, PLI) : static_cast(PLI); if (PSR.liveAt(LastUse)) LRC.extend(LR, End, /*PhysReg=*/0, Undefs); } } void SplitEditor::extendPHIKillRanges() { // Extend live ranges to be live-out for successor PHI values. // Visit each PHI def slot in the parent live interval. If the def is dead, // remove it. Otherwise, extend the live interval to reach the end indexes // of all predecessor blocks. LiveInterval &ParentLI = Edit->getParent(); for (const VNInfo *V : ParentLI.valnos) { if (V->isUnused() || !V->isPHIDef()) continue; unsigned RegIdx = RegAssign.lookup(V->def); LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); LiveRangeCalc &LRC = getLRCalc(RegIdx); MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def); if (!removeDeadSegment(V->def, LI)) extendPHIRange(B, LRC, LI, LaneBitmask::getAll(), /*Undefs=*/{}); } SmallVector Undefs; LiveRangeCalc SubLRC; for (LiveInterval::SubRange &PS : ParentLI.subranges()) { for (const VNInfo *V : PS.valnos) { if (V->isUnused() || !V->isPHIDef()) continue; unsigned RegIdx = RegAssign.lookup(V->def); LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); LiveInterval::SubRange &S = getSubRangeForMask(PS.LaneMask, LI); if (removeDeadSegment(V->def, S)) continue; MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def); SubLRC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, &LIS.getVNInfoAllocator()); Undefs.clear(); LI.computeSubRangeUndefs(Undefs, PS.LaneMask, MRI, *LIS.getSlotIndexes()); extendPHIRange(B, SubLRC, S, PS.LaneMask, Undefs); } } } /// rewriteAssigned - Rewrite all uses of Edit->getReg(). void SplitEditor::rewriteAssigned(bool ExtendRanges) { struct ExtPoint { ExtPoint(const MachineOperand &O, unsigned R, SlotIndex N) : MO(O), RegIdx(R), Next(N) {} MachineOperand MO; unsigned RegIdx; SlotIndex Next; }; SmallVector ExtPoints; for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()), RE = MRI.reg_end(); RI != RE;) { MachineOperand &MO = *RI; MachineInstr *MI = MO.getParent(); ++RI; // LiveDebugVariables should have handled all DBG_VALUE instructions. if (MI->isDebugValue()) { DEBUG(dbgs() << ""Zapping "" << *MI); MO.setReg(0); continue; } // operands don't really read the register, so it doesn't matter // which register we choose. When the use operand is tied to a def, we must // use the same register as the def, so just do that always. SlotIndex Idx = LIS.getInstructionIndex(*MI); if (MO.isDef() || MO.isUndef()) Idx = Idx.getRegSlot(MO.isEarlyClobber()); // Rewrite to the mapped register at Idx. unsigned RegIdx = RegAssign.lookup(Idx); LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); MO.setReg(LI.reg); DEBUG(dbgs() << "" rewr BB#"" << MI->getParent()->getNumber() << '\\t' << Idx << ':' << RegIdx << '\\t' << *MI); // Extend liveness to Idx if the instruction reads reg. if (!ExtendRanges || MO.isUndef()) continue; // Skip instructions that don't read Reg. if (MO.isDef()) { if (!MO.getSubReg() && !MO.isEarlyClobber()) continue; // We may want to extend a live range for a partial redef, or for a use // tied to an early clobber. Idx = Idx.getPrevSlot(); if (!Edit->getParent().liveAt(Idx)) continue; } else Idx = Idx.getRegSlot(true); SlotIndex Next = Idx.getNextSlot(); if (LI.hasSubRanges()) { // We have to delay extending subranges until we have seen all operands // defining the register. This is because a operand // will create an ""undef"" point, and we cannot extend any subranges // until all of them have been accounted for. if (MO.isUse()) ExtPoints.push_back(ExtPoint(MO, RegIdx, Next)); } else { LiveRangeCalc &LRC = getLRCalc(RegIdx); LRC.extend(LI, Next, 0, ArrayRef()); } } for (ExtPoint &EP : ExtPoints) { LiveInterval &LI = LIS.getInterval(Edit->get(EP.RegIdx)); assert(LI.hasSubRanges()); LiveRangeCalc SubLRC; unsigned Reg = EP.MO.getReg(), Sub = EP.MO.getSubReg(); LaneBitmask LM = Sub != 0 ? TRI.getSubRegIndexLaneMask(Sub) : MRI.getMaxLaneMaskForVReg(Reg); for (LiveInterval::SubRange &S : LI.subranges()) { if ((S.LaneMask & LM).none()) continue; // The problem here can be that the new register may have been created // for a partially defined original register. For example: // %vreg827:subreg_hireg = ... // ... // %vreg828 = COPY %vreg827 if (S.empty()) continue; SubLRC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, &LIS.getVNInfoAllocator()); SmallVector Undefs; LI.computeSubRangeUndefs(Undefs, S.LaneMask, MRI, *LIS.getSlotIndexes()); SubLRC.extend(S, EP.Next, 0, Undefs); } } for (unsigned R : *Edit) { LiveInterval &LI = LIS.getInterval(R); if (!LI.hasSubRanges()) continue; LI.clear(); LI.removeEmptySubRanges(); LIS.constructMainRangeFromSubranges(LI); } } void SplitEditor::deleteRematVictims() { SmallVector Dead; for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){ LiveInterval *LI = &LIS.getInterval(*I); for (const LiveRange::Segment &S : LI->segments) { // Dead defs end at the dead slot. if (S.end != S.valno->def.getDeadSlot()) continue; if (S.valno->isPHIDef()) continue; MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def); assert(MI && ""Missing instruction for dead def""); MI->addRegisterDead(LI->reg, &TRI); if (!MI->allDefsAreDead()) continue; DEBUG(dbgs() << ""All defs dead: "" << *MI); Dead.push_back(MI); } } if (Dead.empty()) return; Edit->eliminateDeadDefs(Dead, None, &AA); } void SplitEditor::finish(SmallVectorImpl *LRMap) { ++NumFinished; // At this point, the live intervals in Edit contain VNInfos corresponding to // the inserted copies. // Add the original defs from the parent interval. for (const VNInfo *ParentVNI : Edit->getParent().valnos) { if (ParentVNI->isUnused()) continue; unsigned RegIdx = RegAssign.lookup(ParentVNI->def); defValue(RegIdx, ParentVNI, ParentVNI->def, true); // Force rematted values to be recomputed everywhere. // The new live ranges may be truncated. if (Edit->didRematerialize(ParentVNI)) for (unsigned i = 0, e = Edit->size(); i != e; ++i) forceRecompute(i, ParentVNI); } // Hoist back-copies to the complement interval when in spill mode. switch (SpillMode) { case SM_Partition: // Leave all back-copies as is. break; case SM_Size: case SM_Speed: // hoistCopies will behave differently between size and speed. hoistCopies(); } // Transfer the simply mapped values, check if any are skipped. bool Skipped = transferValues(); // Rewrite virtual registers, possibly extending ranges. rewriteAssigned(Skipped); if (Skipped) extendPHIKillRanges(); else ++NumSimple; // Delete defs that were rematted everywhere. if (Skipped) deleteRematVictims(); // Get rid of unused values and set phi-kill flags. for (unsigned Reg : *Edit) { LiveInterval &LI = LIS.getInterval(Reg); LI.removeEmptySubRanges(); LI.RenumberValues(); } // Provide a reverse mapping from original indices to Edit ranges. if (LRMap) { LRMap->clear(); for (unsigned i = 0, e = Edit->size(); i != e; ++i) LRMap->push_back(i); } // Now check if any registers were separated into multiple components. ConnectedVNInfoEqClasses ConEQ(LIS); for (unsigned i = 0, e = Edit->size(); i != e; ++i) { // Don't use iterators, they are invalidated by create() below. unsigned VReg = Edit->get(i); LiveInterval &LI = LIS.getInterval(VReg); SmallVector SplitLIs; LIS.splitSeparateComponents(LI, SplitLIs); unsigned Original = VRM.getOriginal(VReg); for (LiveInterval *SplitLI : SplitLIs) VRM.setIsSplitFromReg(SplitLI->reg, Original); // The new intervals all map back to i. if (LRMap) LRMap->resize(Edit->size(), i); } // Calculate spill weight and allocation hints for new intervals. Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI); assert(!LRMap || LRMap->size() == Edit->size()); } //===----------------------------------------------------------------------===// // Single Block Splitting //===----------------------------------------------------------------------===// bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI, bool SingleInstrs) const { // Always split for multiple instructions. if (!BI.isOneInstr()) return true; // Don't split for single instructions unless explicitly requested. if (!SingleInstrs) return false; // Splitting a live-through range always makes progress. if (BI.LiveIn && BI.LiveOut) return true; // No point in isolating a copy. It has no register class constraints. if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike()) return false; // Finally, don't isolate an end point that was created by earlier splits. return isOriginalEndpoint(BI.FirstInstr); } void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) { openIntv(); SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber()); SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr, LastSplitPoint)); if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) { useIntv(SegStart, leaveIntvAfter(BI.LastInstr)); } else { // The last use is after the last valid split point. SlotIndex SegStop = leaveIntvBefore(LastSplitPoint); useIntv(SegStart, SegStop); overlapIntv(SegStop, BI.LastInstr); } } //===----------------------------------------------------------------------===// // Global Live Range Splitting Support //===----------------------------------------------------------------------===// // These methods support a method of global live range splitting that uses a // global algorithm to decide intervals for CFG edges. They will insert split // points and color intervals in basic blocks while avoiding interference. // // Note that splitSingleBlock is also useful for blocks where both CFG edges // are on the stack. void SplitEditor::splitLiveThroughBlock(unsigned MBBNum, unsigned IntvIn, SlotIndex LeaveBefore, unsigned IntvOut, SlotIndex EnterAfter){ SlotIndex Start, Stop; std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum); DEBUG(dbgs() << ""BB#"" << MBBNum << "" ["" << Start << ';' << Stop << "") intf "" << LeaveBefore << '-' << EnterAfter << "", live-through "" << IntvIn << "" -> "" << IntvOut); assert((IntvIn || IntvOut) && ""Use splitSingleBlock for isolated blocks""); assert((!LeaveBefore || LeaveBefore < Stop) && ""Interference after block""); assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && ""Impossible intf""); assert((!EnterAfter || EnterAfter >= Start) && ""Interference before block""); MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum); if (!IntvOut) { DEBUG(dbgs() << "", spill on entry.\\n""); // // <<<<<<<<< Possible LeaveBefore interference. // |-----------| Live through. // -____________ Spill on entry. // selectIntv(IntvIn); SlotIndex Idx = leaveIntvAtTop(*MBB); assert((!LeaveBefore || Idx <= LeaveBefore) && ""Interference""); (void)Idx; return; } if (!IntvIn) { DEBUG(dbgs() << "", reload on exit.\\n""); // // >>>>>>> Possible EnterAfter interference. // |-----------| Live through. // ___________-- Reload on exit. // selectIntv(IntvOut); SlotIndex Idx = enterIntvAtEnd(*MBB); assert((!EnterAfter || Idx >= EnterAfter) && ""Interference""); (void)Idx; return; } if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) { DEBUG(dbgs() << "", straight through.\\n""); // // |-----------| Live through. // ------------- Straight through, same intv, no interference. // selectIntv(IntvOut); useIntv(Start, Stop); return; } // We cannot legally insert splits after LSP. SlotIndex LSP = SA.getLastSplitPoint(MBBNum); assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && ""Impossible intf""); if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter || LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) { DEBUG(dbgs() << "", switch avoiding interference.\\n""); // // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference. // |-----------| Live through. // ------======= Switch intervals between interference. // selectIntv(IntvOut); SlotIndex Idx; if (LeaveBefore && LeaveBefore < LSP) { Idx = enterIntvBefore(LeaveBefore); useIntv(Idx, Stop); } else { Idx = enterIntvAtEnd(*MBB); } selectIntv(IntvIn); useIntv(Start, Idx); assert((!LeaveBefore || Idx <= LeaveBefore) && ""Interference""); assert((!EnterAfter || Idx >= EnterAfter) && ""Interference""); return; } DEBUG(dbgs() << "", create local intv for interference.\\n""); // // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference. // |-----------| Live through. // ==---------== Switch intervals before/after interference. // assert(LeaveBefore <= EnterAfter && ""Missed case""); selectIntv(IntvOut); SlotIndex Idx = enterIntvAfter(EnterAfter); useIntv(Idx, Stop); assert((!EnterAfter || Idx >= EnterAfter) && ""Interference""); selectIntv(IntvIn); Idx = leaveIntvBefore(LeaveBefore); useIntv(Start, Idx); assert((!LeaveBefore || Idx <= LeaveBefore) && ""Interference""); } void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI, unsigned IntvIn, SlotIndex LeaveBefore) { SlotIndex Start, Stop; std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); DEBUG(dbgs() << ""BB#"" << BI.MBB->getNumber() << "" ["" << Start << ';' << Stop << ""), uses "" << BI.FirstInstr << '-' << BI.LastInstr << "", reg-in "" << IntvIn << "", leave before "" << LeaveBefore << (BI.LiveOut ? "", stack-out"" : "", killed in block"")); assert(IntvIn && ""Must have register in""); assert(BI.LiveIn && ""Must be live-in""); assert((!LeaveBefore || LeaveBefore > Start) && ""Bad interference""); if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) { DEBUG(dbgs() << "" before interference.\\n""); // // <<< Interference after kill. // |---o---x | Killed in block. // ========= Use IntvIn everywhere. // selectIntv(IntvIn); useIntv(Start, BI.LastInstr); return; } SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber()); if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) { // // <<< Possible interference after last use. // |---o---o---| Live-out on stack. // =========____ Leave IntvIn after last use. // // < Interference after last use. // |---o---o--o| Live-out on stack, late last use. // ============ Copy to stack after LSP, overlap IntvIn. // \\_____ Stack interval is live-out. // if (BI.LastInstr < LSP) { DEBUG(dbgs() << "", spill after last use before interference.\\n""); selectIntv(IntvIn); SlotIndex Idx = leaveIntvAfter(BI.LastInstr); useIntv(Start, Idx); assert((!LeaveBefore || Idx <= LeaveBefore) && ""Interference""); } else { DEBUG(dbgs() << "", spill before last split point.\\n""); selectIntv(IntvIn); SlotIndex Idx = leaveIntvBefore(LSP); overlapIntv(Idx, BI.LastInstr); useIntv(Start, Idx); assert((!LeaveBefore || Idx <= LeaveBefore) && ""Interference""); } return; } // The interference is overlapping somewhere we wanted to use IntvIn. That // means we need to create a local interval that can be allocated a // different register. unsigned LocalIntv = openIntv(); (void)LocalIntv; DEBUG(dbgs() << "", creating local interval "" << LocalIntv << "".\\n""); if (!BI.LiveOut || BI.LastInstr < LSP) { // // <<<<<<< Interference overlapping uses. // |---o---o---| Live-out on stack. // =====----____ Leave IntvIn before interference, then spill. // SlotIndex To = leaveIntvAfter(BI.LastInstr); SlotIndex From = enterIntvBefore(LeaveBefore); useIntv(From, To); selectIntv(IntvIn); useIntv(Start, From); assert((!LeaveBefore || From <= LeaveBefore) && ""Interference""); return; } // <<<<<<< Interference overlapping uses. // |---o---o--o| Live-out on stack, late last use. // =====------- Copy to stack before LSP, overlap LocalIntv. // \\_____ Stack interval is live-out. // SlotIndex To = leaveIntvBefore(LSP); overlapIntv(To, BI.LastInstr); SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore)); useIntv(From, To); selectIntv(IntvIn); useIntv(Start, From); assert((!LeaveBefore || From <= LeaveBefore) && ""Interference""); } void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI, unsigned IntvOut, SlotIndex EnterAfter) { SlotIndex Start, Stop; std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); DEBUG(dbgs() << ""BB#"" << BI.MBB->getNumber() << "" ["" << Start << ';' << Stop << ""), uses "" << BI.FirstInstr << '-' << BI.LastInstr << "", reg-out "" << IntvOut << "", enter after "" << EnterAfter << (BI.LiveIn ? "", stack-in"" : "", defined in block"")); SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber()); assert(IntvOut && ""Must have register out""); assert(BI.LiveOut && ""Must be live-out""); assert((!EnterAfter || EnterAfter < LSP) && ""Bad interference""); if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) { DEBUG(dbgs() << "" after interference.\\n""); // // >>>> Interference before def. // | o---o---| Defined in block. // ========= Use IntvOut everywhere. // selectIntv(IntvOut); useIntv(BI.FirstInstr, Stop); return; } if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) { DEBUG(dbgs() << "", reload after interference.\\n""); // // >>>> Interference before def. // |---o---o---| Live-through, stack-in. // ____========= Enter IntvOut before first use. // selectIntv(IntvOut); SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr)); useIntv(Idx, Stop); assert((!EnterAfter || Idx >= EnterAfter) && ""Interference""); return; } // The interference is overlapping somewhere we wanted to use IntvOut. That // means we need to create a local interval that can be allocated a // different register. DEBUG(dbgs() << "", interference overlaps uses.\\n""); // // >>>>>>> Interference overlapping uses. // |---o---o---| Live-through, stack-in. // ____---====== Create local interval for interference range. // selectIntv(IntvOut); SlotIndex Idx = enterIntvAfter(EnterAfter); useIntv(Idx, Stop); assert((!EnterAfter || Idx >= EnterAfter) && ""Interference""); openIntv(); SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr)); useIntv(From, Idx); } ",16254,True,2795.186484024822,median "= EDGE2AI Workshop == Introduction The Cloudera Self Driving Vehicle (CSDV) is a miniature autonomous car which is trained to follow markers along a race track, the team achieved this by rapidly sampling photographs and using them to run inference to adjust the steering angle of the vehicle. ===== Labs summary: * *Lab 1* - On the Gateway host, run a simulator to send IoT sensors data to the MQTT broker. * *Lab 2* - On the Gateway host, configure and start **MiNiFi**, which will read from the MQTT broker, filter and forward to the **NiFi** cluster. * *Lab 3* - Create the MiNiFi flow on the Edge Flow Manager and publish it for the MiNiFi agent to start sending data to the NiFi cluster. * *Lab 4* - On Schema Registry, register the schema describing the data generated by the IoT sensors. * *Lab 5* - On the NiFi cluster, prepare the data and send it to the **Kafka** cluster. * *Lab 6* - On the *Streams Messaging Manager (SMM)* Web UI, monitor the Kafka cluster and confirm data is being ingested correctly. * *Lab 7* - Use the Edge Flow Manager to update existing edge flows and perform additional processing on the edge * *Lab 8* - Use NiFi to process each record, calling the **Model endpoint** and save results to **Kudu**. * *Lab 9* - On the CDH cluster, process each record using **Spark Streaming**, calling the **Model endpoint** and save results to **Kudu**. * *Lab 10* - On the CDH cluster, pull reports on upcoming predicted machine failures using **Impala** and **Hue**. * *Lab 11* - On the **CDSW** cluster, train your model with the **Experiment** feature. * *Lab 12* - On the **CDSW** cluster, deploy the model into production with the **Model** feature. ===== Pre-requisites * Laptop with a supported OS (Windows 7 not supported). * Ability to SSH into remote hosts from Windows or Mac. For Windows machines, install Putty or even better link:https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse[install OpenSSH for PowerShell]. * A modern browser like Google Chrome (IE not supported). ===== Connecting to your cluster You should have 2 addresses for you one-node cluster: the public DNS name and the public IP address. With those addresses you can test the following connectivity to your cluster: . It is convenient to export the DNS, IP, and path to the PEM of your cluster for future use: + [source, shell] ---- export WDNS= export WIP= export WPEM= ---- . Ensure you can SSH into the cluster (using either the DNS name or IP address) + [source,shell] ---- ssh -i $WPEM centos@$WDNS ---- . Ensure you can connect to the following service using your browser: + [%autowidth,options=""header""] |=== |Service|URL|Credentials |Cloudera Manager|http://:7180/|`admin/admin` |Edge Flow Manager|http://:10088/efm/ui/| |NiFi|http://:8080/nifi/| |NiFi Registry|http://:18080/nifi-registry/| |Schema Registry|http://:7788/| |SMM|http://:9991/| |Hue|http://:8888/| |CDSW|http://cdsw..nip.io/|`admin/supersecret1` |=== . Login into *Cloudera Manager* and familiarize yourself with the services installed . Login into *Hue*. As you are the first user to login into Hue, you are granted admin privileges. At this point, you won't need to do anything on Hue, but by logging in, CDH has created your HDFS user and folder. Below a screenshot of Chrome open with 8 tabs, one for each service. image::images/browser.png[width=800] [[lab_1, Lab 1]] == Lab 1 - Configure and run MiNiFi MiNiFi is installed on the host. In this lab you will configure and run MiNiFi to read from the MQTT broker and forward to the NiFi cluster, but it's only in the next lab that you will provide the flow to execute. . Sudo to the root user + [source,shell] ---- sudo su - ---- . Start the MiNiFi agent: + [source,shell] ---- systemctl start minifi ---- . Exit the root session + [source,shell] ---- exit ---- [[lab_2, Lab2]] == Lab 2 - Configuring the NiFi Flow In order to connect MiNiFi to NiFi we need to know where we are going so let's create a path for our data to slowly build a flow. Open NiFi UI on your CDF cluster and create a new input source named `AWS_MiNiFi_CSV` leave it alone for now, we will need the input id to set our connection from MiNiFi processor to NiFi Remote Process Group (RPG) [[lab_3, Lab3]] == Lab 3 - Configuring Edge Flow Management Cloudera Edge Flow Management gives you a visual overview of all MiNiFi agents in your environment, and allows you to update the flow configuration for each one, with versioning control thanks to the **NiFi Registry** integration. In this lab, you will create the MiNiFi flow and publish it for the MiNiFi agent to pick it up. . Open the EFM Web UI at http://:10088/efm/ui/. Ensure you see your minifi agent's heartbeat messages in the **Events Monitor**. + image::images/cem_heartbeats.png[width=800] . You can then select the **Flow Designer** tab (image:images/flow_designer_icon.png[width=30]). To build a dataflow, select the desired class (`iot-1`) from the table and click OPEN. Alternatively, you can double-click on the desired class. . Add a _GetFile_ processor onto canvas to get csv data: + Update processor name to **GetCSVFile**. . Add a _Remote Process Group_ (RPG) to the canvas and configure it as follows: + [source] ---- URL: http://edge2ai-1.dim.local:8080/nifi ---- + image::images/add_rpg.png[width=800] . At this point you need to connect the ConsumerMQTT processor to the RPG. For this, you first need to add an Input Port to the remote NiFi server. Open the NiFi Web UI at `\\http://:8080/nifi/` and drag the _Input Port_ to the canvas. Call it something like ""from Gateway"". + image::images/add_input_port.png[width=800] . To terminate the NiFI _Input Port_ let's, for now, add a _Funnel_ to the canvas... + image::images/add_funnel.png[width=600] . ... and setup a connection from the Input Port to it. To setup a connection, hover the mouse over the Input Port until an arrow symbol is shown in the center. Click on the arrow, drag it and drop it on the Funnel to connect the two elements. + image::images/connecting.png[width=800] . Right-click on the Input Port and start it. Alternatively, click on the Input Port to select it and then press the start (""play"") button on the Operate panel: + image::images/operate_panel.png[width=300] . You will need the ID of the _Input Port_ to complete the connection of the _ConsumeMQTT_ processor to the RPG (NiFi). Double-click on the _Input Port_ and copy its ID. + image::images/input_port_id.png[width=800] . Back to the Flow Designer, connect the ConsumeMQTT processor to the RPG. The connection requires an ID and you can paste here the ID you copied from the Input Port. + image::images/connect_to_rpg.png[width=800] . The Flow is now complete, but before publishing it, create the Bucket in the _NiFi Registry_ so that all versions of your flows are stored for review and audit. Open the NiFi Registry at `\\http://:18080/nifi-registry`, click on the wrench/spanner icon (image:images/spanner_icon.png[width=20]) on the top-right corner on and create a bucket called `IoT`. + image::images/create_bucket.png[width=800] . You can now publish the flow for the MiNiFi agent to automatically pick up. Click *Publish*, add a descriptive comment for your changes and click *Apply*. + image::images/publish_flow.png[width=800] + image::images/cem_first_version.png[width=800] . Go back to the *NiFi Registry* Web UI and click on the *NiFi Registry* name, next to the Cloudera logo. If the flow publishing was successful, you should see the flow's version details in the NiFi Registry. + image::images/flow_in_nifi_registry.png[width=800] . At this point, you can test the edge flow up until NiFi. Start the simulator again and confirm you can see the messages queued in NiFi. + [source] ---- python mqtt.iot_simulator.py mqtt.iot.config ---- + image::images/running_simulator.png[width=800] + image::images/queued_events.png[width=300] . You can stop the simulator once you confirm that the flow is working correctly. [[lab_4, Lab 4]] == Lab 4 - Registering our schema in Schema Registry The data produced by the temperature sensors is described by the schema in file `link:https://raw.githubusercontent.com/cloudera-labs/edge2ai-workshop/master/sensor.avsc[sensor.avsc]`. In this lab we will register this schema in Schema Registry so that our flows in NiFi can refer to schema using an unified service. This will also allow us to evolve the schema in the future, if needed, keeping older versions under version control, so that existing flows and flowfiles will continue to work. . Go the following URL, which contains the schema definition we'll use for this lab. Select all contents of the page and copy it. + `link:https://raw.githubusercontent.com/cloudera-labs/edge2ai-workshop/master/sensor.avsc[https://raw.githubusercontent.com/cloudera-labs/edge2ai-workshop/master/sensor.avsc, window=""_blank""]` . In the Schema Registry Web UI, click the `+` sign to register a new schema. . Click on a blank area in the *Schema Text* field and paste the contents you copied. . Complete the schema creation by filling the following properties: + [source] ---- Name: SensorReading Description: Schema for the data generated by the IoT sensors Type: Avro schema provider Schema Group: Kafka Compatibility: Backward Evolve: checked ---- image::images/register_schema.png[width=800] . Save the schema [[lab_5, Lab 5]] == Lab 5 - Configuring the NiFi flow and pushing data to Kafka In this lab, you will create a NiFi flow to receive the data from all gateways and push it to **Kafka**. === Creating a Process Group Before we start building our flow, let's create a Process Group to help organizing the flows in the NiFi canvas and also to enable flow version control. . Open the NiFi Web UI, create a new Process Group and name it something like *Process Sensor Data*. + image::images/create_pgroup.png[width=800] . We want to be able to version control the flows we will add to the Process Group. In order to do that, we first need to connect NiFi to the *NiFi Registry*. On the NiFi global menu, click on ""Controller Services"", navigate to the ""Registry Clients"" tab and add a Registry client with the following URL: + ---- Name: NiFi Registry URL: http://edge2ai-1.dim.local:18080 ---- + image::images/global_controller_settings.png[width=800] + image::images/add_registry_client.png[width=800] . On the *NiFi Registry* Web UI, add another bucket for storing the Sensor flow we're about to build'. Call it `SensorFlows`: + image::images/sensor_flows_bucket.png[width=800] . Back on the *NiFi* Web UI, to enable version control for the Process Group, right-click on it and select *Version > Start version control* and enter the details below. Once you complete, a image:images/version_control_tick.png[width=20] will appear on the Process Group, indicating that version control is now enabled for it. + [source] ---- Registry: NiFi Registry Bucket: SensorFlows Flow Name: SensorProcessGroup ---- . Let's also enable processors in this Process Group to use schemas stored in Schema Registry. Right-click on the Process Group, select *Configure* and navigate to the *Controller Services* tab. Click the *`+`* icon and add a *HortonworksSchemaRegistry* service. After the service is added, click on the service's _cog_ icon (image:images/cog_icon.png[width=20]), go to the *Properties* tab and configure it with the following *Schema Registry URL* and click *Apply*. + [source] ---- URL: http://edge2ai-1.dim.local:7788/api/v1 ---- + image::images/added_hwx_sr_service.png[width=800] . Click on the _lightning bolt_ icon (image:images/enable_icon.png[width=20]) to *enable* the *HortonworksSchemaRegistry* Controller Service. . Still on the *Controller Services* screen, let's add two additional services to handle the reading and writing of JSON records. Click on the image:images/plus_button.png[width=25] button and add the following two services: ** *`JsonTreeReader`*, with the following properties: + [source] ---- Schema Access Strategy: Use 'Schema Name' Property Schema Registry: HortonworksSchemaRegistry Schema Name: ${schema.name} -> already set by default! ---- ** *`JsonRecordSetWriter`*, with the following properties: + [source] ---- Schema Write Strategy: HWX Schema Reference Attributes Schema Access Strategy: Inherit Record Schema Schema Registry: HortonworksSchemaRegistry ---- . Enable the *JsonTreeReader* and the *JsonRecordSetWriter* Controller Services you just created, by clicking on their respective _lightning bolt_ icons (image:images/enable_icon.png[width=20]). + image::images/controller_services.png[width=800] === Creating the flow . Double-click on the newly created process group to expand it. . Inside the process group, add a new _Input Port_ and name it ""Sensor Data"" . We need to tell NiFi which schema should be used to read and write the Sensor data. For this we'll use an _UpdateAttribute_ processor to add an attribute to the FlowFile indicating the schema name. + Add an _UpdateAttribute_ processor by dragging the processor icon to the canvas: + image::images/add_updateattribute.png[width=800] . Double-click the _UpdateAttribute_ processor and configure it as follows: .. In the _SETTINGS_ tab: + [source] ---- Name: Set Schema Name ---- .. In the _PROPERTIES_ tab: ** Click on the image:images/plus_button.png[width=25] button and add the following property: + [source] ---- Property Name: schema.name Property Value: SensorReading ---- .. Click *Apply* . Connect the *Sensor Data* input port to the *Set Schema Name* processor. . Add a _PublishKafkaRecord_2.0_ processor and configure it as follows: + *SETTINGS* tab: + [source] ---- Name: Publish to Kafka topic: iot ---- + *PROPERTIES* tab: + [source] ---- Kafka Brokers: edge2ai-1.dim.local:9092 Topic Name: iot Record Reader: JsonTreeReader Record Writer: JsonRecordSetWriter Use Transactions: false Attributes to Send as Headers (Regex): schema.* ---- + NOTE: Make sure you use the PublishKafkaRecord_2.0 processor and *not* the PublishKafka_2.0 one . While still in the _PROPERTIES_ tab of the _PublishKafkaRecord_2.0_ processor, click on the image:images/plus_button.png[width=25] button and add the following property: + [source] ---- Property Name: client.id Property Value: nifi-sensor-data ---- + Later, this will help us clearly identify who is producing data into the Kafka topic. . Connect the *Set Schema Name* processor to the *Publish to Kafka topic: iot* processor. . Add a new _Funnel_ to the canvas and connect the PublishKafkaRecord processor to it. When the ""Create connection"" dialog appears, select ""*failure*"" and click *Add*. + image::images/add_kafka_failure_connection.png[width=600] . Double-click on the *Publish to Kafka topic: iot* processor, go to the *SETTINGS* tab, check the ""*success*"" relationship in the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section. Click *Apply*. + image::images/terminate_publishkafka_relationship.png[width=600] . Start the input port and the two processors. Your canvas should now look like the one below: + image::images/publishKafka_flow.png[width=800] . The only thing that remains to be configured now is to finally connect the ""*from Gateway*"" Input Port to the flow in the ""*Processor Sensor Data*"" group. To do that, first go back to the root canvas by clicking on the *NiFi Flow* link on the status bar. + image::images/breadcrumbs.png[width=400] . Connect the Input Port to the *Process Sensor Data* Process Group by dragging the destination of the current connection from the funnel to the Process Group. When prompted, ensure the ""To input"" fields is set to the *Sensor data* Input Port. + image::images/connect_input.png[width=800] + image::images/to_input.png[width=800] . Refresh the screen (`Ctrl+R` on Linux/Windows; `Cmd+R` on Mac) and you should see that the records that were queued on the ""*from Gateway*"" Input Port disappeared. They flowed into the *Process Sensor Data* flow. If you expand the Process Group you should see that those records were processed by the _PublishKafkaRecord_ processor and there should be no records queued on the ""failure"" output queue. + image::images/kafka_success.png[width=800] + At this point, the messages are already in the Kafka topic. You can add more processors as needed to process, split, duplicate or re-route your FlowFiles to all other destinations and processors. . To complete this Lab, let's commit and version the work we've just done. Go back to the NiFi root canvas, clicking on the ""Nifi Flow"" breadcrumb. Right-click on the *Process Sensor Data* Process Group and select *Version > Commit local changes*. Enter a descriptive comment and save. [[lab_6, Lab 6]] == Lab 6 - Use SMM to confirm that the data is flowing correctly Now that our NiFi flow is pushing data to Kafka, it would be good to have a confirmation that everything is running as expected. In this lab you will use Streams Messaging Manager (SMM) to check and monitor Kafka. . Start the simulator again and confirm you can see the messages queued in NiFi. Leave it running. + [source] ---- python mqtt.iot_simulator.py mqtt.iot.config ---- . Go to the Stream Messaging Manager (SMM) Web UI and familiarize yourself with the options there. Notice the filters (blue boxes) at the top of the screen. + image::images/smm.png[width=800] . Click on the *Producers* filter and select only the *`nifi-sensor-data`* producer. This will hide all the irrelevant topics and show only the ones that producer is writing to. . If you filter by *Topic* instead and select the `iot` topic, you'll be able to see all the *producers* and *consumers* that are writing to and reading from it, respectively. Since we haven't implemented any consumers yet, the consumer list should be empty. . Click on the topic to explore its details. You can see more details, metrics and the break down per partition. Click on one of the partitions and you'll see additional information and which producers and consumers interact with that partition. + image::images/producers.png[width=800] . Click on the *EXPLORE* link to visualize the data in a particular partition. Confirm that there's data in the Kafka topic and it looks like the JSON produced by the sensor simulator. + image::images/explore_partition.png[width=800] . Check the data from the partition. You'll notice something odd. These are readings from temperature sensors and we don't expect any of the sensors to measure temperatures greater than 150 degrees in the conditions they are used. It seems, though, that `sensor_0` and `sensor_1` are intermittently producing noise and some of the measurements have very high values for these measurements. + image::images/troubled_sensors.png[width=800] . Stop the simulator with CTRL-C. . In the next Lab we'll eliminate with these problematic measurements to avoid problems later in our data flow. [[lab_7, Lab 7]] == Lab 7 - Update the edge flows to perform additional processing on the data In the previous lab we noticed that some of the sensors were sending erroneous measurements intermittently. If we let these measurements to be processed by our data flow we might have problems with the quality of our flow output and we want to avoid that. We could use our *Process Sensor Data* flow in NiFi to filter out those problematic measurements. However, if their volume is large we could be wasting network bandwidth and causing additional overhead in NiFi to process the bogus data. What we'd like to do instead is to push additional logic to the edge to identify and filter those problems in place and avoiding sending them to NiFi in the first place. We've noticed that the problem always happen with the temperatures in measurements `sensor_0` and `sensor_1`, only. If any of these two temperatures are *greater than 500* we *must discard* the entire sensor reading. If both of these temperatures are in the normal range (< 500) we can guarantee that all temperatures reported are correct and can be sent to NiFi. . Go to the CEM Web UI and add a new processor to the canvas. In the Filter box of the dialog that appears, type ""JsonPath"". Select the _EvaluateJSONPath_ processor and click *Add*. . Double-click on the new processor and configure it with the following properties: + [source,python] ---- Processor Name: Extract sensor_0 and sensor1 values Destination: flowfile-attribute ---- + image::images/EvaluateJsonPath.png[width=800] . Click on the *Add Property* button and enter the following properties: + [%autowidth,cols=""1a,1a"",options=""header""] |=== |Property Name|Property Value |`sensor_0`|`$.sensor_0` |`sensor_1`|`$.sensor_1` |=== + image::images/extract_attributes.png[width=800] . Click *Apply* to save the processor configuration. . Drag one more new processor to the canvas. In the Filter box of the dialog that appears, type ""Route"". Select the _RouteOnAttribute_ processor and click *Add*. + image::images/route_on_attribute.png[width=800] . Double-click on the new processor and configure it with the following properties: + [source,python] ---- Processor Name: Filter Errors Route Strategy: Route to Property name ---- . Click on the *Add Property* button and enter the following properties: + [%autowidth,cols=""1a,1a"",options=""header""] |=== |Property Name|Property Value |`error`|`${sensor_0:ge(500):or(${sensor_1:ge(500)})}` |=== + image::images/route_on_attribute_config.png[width=800] . Click *Apply* to save the processor configuration. . Reconnect the _ConsumeMQTT_ processor to the _Extract sensor_0 and sensor1 values_ processor: .. Click on the existing connection between _ConsumeMQTT_ and the _RPG_ to select it. .. Drag the destination end of the connection to the _Extract sensor_0 and sensor1 values_ processor. + image::images/reconnect_consume_mqtt.png[width=800] . Connect the _Extract sensor_0 and sensor1 values_ to the _Filter errors_ processor. When the *Create Connection* dialog appear, select ""*matched*"" and click *Create*. + image::images/connect_extract_to_route.png[width-800] + image::images/create_connection.png[width=800] . Double-click the _Extract sensor_0 and sensor1 values_ and check the following values in the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section and click *Apply*: ** failure ** unmatched ** sensor_0 ** sensor_1 + image::images/terminations.png[width=800] . Before creating the last connection, you will need (again) the ID of the NiFi _Input Port_. Go to the NiFi Web UI , double-click on the ""*from Gateway*"" _Input Port_ and copy its ID. + image::images/input_port_id.png[width=800] . Back on the CEM Web UI, connect the _Filter errors_ processor to the RPG: + image::images/connect_filter_ro_rpg.png[width=800] . In the *Create Connection* dialog, check the ""*unmatched*"" checkbox and enter the copied input port ID, and click on *Create*: + image::images/create_last_connection.png[width=800] . To ignore the errors, double-click on the _Filter errors_ processor, check the *error* checkbox under the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section and click *Apply*: + image::images/terminate_errors.png[width=800] . Finally, click on *ACTIONS > Publish...* on the CEM canvas, enter a descriptive comment like ""Added filtering of erroneous readings"" and click *Publish*. . Start the simulator again. . Go to the NiFi Web UI and confirm that the data is flowing without errors within the *Process Sensor Data* process group. Refresh a few times and check that the numbers are changing. . Use the *EXPLORE* feature on the SMM Web UI to confirm that the bogus readings have been filtered out. . Stop the simulator once you have verified the data. [[lab_8, Lab 8]] == Lab 8 - Use NiFi to call the CDSW model endpoint and save to Kudu In this lab, you will use NiFi to consume the Kafka messages containing the IoT data we ingested in the previous lab, call a CDSW model API endpoint to predict whether the machine where the readings came from is likely to break or not. In preparation for the workshop we trained and deployed a Machine Learning model on the Cloudera Data Science Workbench (CDSW) running on your cluster. The model API can take a feature vector with the reading for the 12 temperature readings provided by the sensor and predict, based on that vector, if the machine is likely to break or not. === Add new Controller Services When the sensor data was sent to Kafka using the _PublishKafkaRecord_ processor, we chose to attach the schema information in the header of Kafka messages. Now, instead of hard-coding which schema we should use to read the message, we can leverage that metadata to dynamically load the correct schema for each message. To do this, though, we need to configure a different _JsonTreeReader_ that will use the schema properties in the header, instead of the `${schema.name}` attribute, as we did before. We'll also add a new _RestLookupService_ controller service to perform the calls to the CDSW model API endpoint. . If you're not in the *Process Sensor Data* process group, double-click on it to expand it. On the *Operate* panel (left-hand side), click on the _cog_ icon (image:images/cog_icon.png[width=25]) to access the *Process Sensor Data* process group's configuration page. + image::images/operate_panel_cog.png[width=300] . Click on the _plus_ button (image:images/plus_button.png[width=25]), add a new *JsonTreeReader*, configure it as shown below and click *Apply* when you're done: + On the *SETTINGS* tab: + [source] ---- Name: JsonTreeReader - With schema identifier ---- + On the *PROPERTIES* tab: + [source] ---- Schema Access Strategy: HWX Schema Reference Attributes Schema Registry: HortonworksSchemaRegistry ---- . Click on the _lightning bolt_ icon (image:images/enable_icon.png[width=20]) to *enable* the *JsonTreeReader - With schema identifier* controller service. . Click again on the _plus_ button (image:images/plus_button.png[width=25]), add a *RestLookupService* controller service, configure it as shown below and click *Apply* when you're done: + On the *PROPERTIES* tab: + [source] ---- URL: http://cdsw..nip.io/api/altus-ds-1/models/call-model Record Reader: JsonTreeReader Record Path: /response ---- + NOTE: `` above must be replaced with your cluster's public IP, *not* DNS name. The final URL should look something like this: `\\http://cdsw.12.34.56.78.nip.io/api/altus-ds-1/models/call-model` . Click on the _lightning bolt_ icon (image:images/enable_icon.png[width=20]) to *enable* the *RestLookupService* controller service. + image::images/additional_controller_services.png[width=800] . Close the *Process Sensor Data Configuration* page. === Create the flow We'll now create the flow to read the sensor data from Kafka, execute a model prediction for each of them and write the results to Kudu. At the end of this section you flow should look like the one below: image::images/from_kafka_to_kudu_flow.png[width=800] ==== ConsumeKafkaRecord_2_0 processor . We'll add a new flow to the same canvas we were using before (inside the *Process Sensor Data* Process Group). Click on an empty area of the canvas and drag it to the side to give you more space to add new processors. . Add a *ConsumeKafkaRecord_2_0* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Consume Kafka iot messages ---- + *PROPERTIES* tab: + [source] ---- Kafka Brokers: edge2ai-1.dim.local:9092 Topic Name(s): iot Topic Name Format: names Record Reader: JsonTreeReader - With schema identifier Record Writer: JsonRecordSetWriter Honor Transactions: false Group ID: iot-sensor-consumer Offset Reset: latest Headers to Add as Attributes (Regex): schema.* ---- . Add a new _Funnel_ to the canvas and connect the *Consume Kafka iot messages* to it. When prompted, check the *parse.failure* relationship for this connection: + image:images/parse_failure_relationship.png[width=500] ==== LookupRecord processor . Add a *LookupRecord* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Predict machine health ---- + *PROPERTIES* tab: + [source] ---- Record Reader: JsonTreeReader - With schema identifier Record Writer: JsonRecordSetWriter Lookup Service: RestLookupService Result RecordPath: /response Routing Strategy: Route to 'success' Record Result Contents: Insert Entire Record ---- . Add 3 more user-defined properties by clicking on the _plus_ button (image:images/plus_button.png[width=25]) for each of them: + [source] ---- mime.type: toString('application/json', 'UTF-8') request.body: concat('{""accessKey"":""', '${cdsw.access.key}', '"",""request"":{""feature"":""', /sensor_0, ', ', /sensor_1, ', ', /sensor_2, ', ', /sensor_3, ', ', /sensor_4, ', ', /sensor_5, ', ', /sensor_6, ', ', /sensor_7, ', ', /sensor_8, ', ', /sensor_9, ', ', /sensor_10, ', ', /sensor_11, '""}}') request.method: toString('post', 'UTF-8') ---- . Click *Apply* to save the changes to the *Predict machine health* processor. . Connect the *Consume Kafka iot messages* processor to the *Predict machine health* one. When prompted, check the *success* relationship for this connection. . Connect the *Predict machine health* to the same _Funnel_ you had created above. When prompted, check the *failure* relationship for this connection. ==== UpdateRecord processor . Add a *UpdateRecord* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Update health flag ---- + *PROPERTIES* tab: + [source] ---- Record Reader: JsonTreeReader - With schema identifier Record Writer: JsonRecordSetWriter Replacement Value Strategy: Record Path Value ---- . Add one more user-defined propertie by clicking on the _plus_ button (image:images/plus_button.png[width=25]): + [source] ---- /is_healthy: /response/result ---- . Connect the *Predict machine health* processor to the *Update health flag* one. When prompted, check the *success* relationship for this connection. . Connect the *Update health flag* to the same _Funnel_ you had created above. When prompted, check the *failure* relationship for this connection. ==== PutKudu processor . Add a *PutKudu* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Write to Kudu ---- + *PROPERTIES* tab: + [source] ---- Kudu Masters: edge2ai-1.dim.local:7051 Table Name: impala::default.sensors Record Reader: JsonTreeReader - With schema identifier ---- . Connect the *Update health flag* processor to the *Write to Kudu* one. When prompted, check the *success* relationship for this connection. . Connect the *Write to Kudu* to the same _Funnel_ you had created above. When prompted, check the *failure* relationship for this connection. . Double-click on the *Write to Kudu* processor, go to the *SETTINGS* tab, check the ""*success*"" relationship in the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section. Click *Apply*. ==== CDSW Access Key When we added the *Predict machine health* above, you may have noticed that one of the properties (`request.body`) makes a reference to a variable called `cdsw.access.key`. This is an application key required to authenticate with the CDSW Model API when requesting predictions. So, we need to provide the key to the _LookupRecord_ processor by setting a variable with its value. . To get the Access Key, go to the CDSW Web UI and click on *Models > Iot Prediction Model > Settings*. Copy the Access Key. + image::images/model_access_key.png[width=800] . Go back to the NiFi Web UI, right-click on an empty area of the *Process Sensor Data* canvas, and click on *Variables*. . Click on the _plus_ button (image:images/plus_button.png[width=25]) and add the following variable: + [source] ---- Variable Name: cdsw.access.key Variable Value: ---- + image::images/access_key_variable.png[width=800] . Click *Apply* ==== Create the Kudu table . Go to the Hue Web UI and login. The first user to login to a Hue installation is automatically created and granted admin privileges in Hue. . The Hue UI should open with the Impala Query Editor by default. If it doesn't, you can always find it by clicking on *Query button > Editor -> Impala*: + image::images/impala_editor.png[width=800] . First, create the Kudu table. Login into Hue, and in the Impala Query, run this statement: + [source,sql] ---- CREATE TABLE sensors ( sensor_id INT, sensor_ts TIMESTAMP, sensor_0 DOUBLE, sensor_1 DOUBLE, sensor_2 DOUBLE, sensor_3 DOUBLE, sensor_4 DOUBLE, sensor_5 DOUBLE, sensor_6 DOUBLE, sensor_7 DOUBLE, sensor_8 DOUBLE, sensor_9 DOUBLE, sensor_10 DOUBLE, sensor_11 DOUBLE, is_healthy INT, PRIMARY KEY (sensor_ID, sensor_ts) ) PARTITION BY HASH PARTITIONS 16 STORED AS KUDU TBLPROPERTIES ('kudu.num_tablet_replicas' = '1'); ---- + image::images/create_table.png[width=800] ==== Running the flow We're ready not to run and test our flow. Follow the steps below: . Start all the processors in your flow. . If the simulator is not already running, start it again on your SSH window: + [source] ---- python mqtt.iot_simulator.py mqtt.iot.config ---- . Refresh your NiFi page and you should see messages passing through your flow. The failure queues should have no records queued up. + image::images/kudu_success.png[width=800] . On Lab 10, you will learn how to query and verify the records inserted into Kudu. [[lab_9, Lab 9]] == Lab 9 - Use Spark to call the CDSW model endpoint and save to Kudu NOTE: This lab is optional, since it does the same processing we performed in Lab 8 but using Spark instead of NiFi. If you want to run this lab, stop the flow created in Lab 8 first, to avoid duplicated data being sent into Kudu. Otherwise, just skip to *Lab 10* Spark Streaming is a processing framework for (near) real-time data. In this lab, you will use Spark to consume Kafka messages which contains the IoT data from the machine, and call the model API endpoint to predict whether, with those IoT values the machine sent, the machine is likely to break. Then save the results to Kudu for fast analytics. ==== Create the Kudu table NOTE: If you already executed this step in the previous lab, please skip the table creation here. . Go to the Hue Web UI and login. The first user to login to a Hue installation is automatically created and granted admin privileges in Hue. . The Hue UI should open with the Impala Query Editor by default. If it doesn't, you can always find it by clicking on *Query button > Editor -> Impala*: + image::images/impala_editor.png[width=800] . First, create the Kudu table. Login into Hue, and in the Impala Query, run this statement: + [source,sql] ---- CREATE TABLE sensors ( sensor_id INT, sensor_ts TIMESTAMP, sensor_0 DOUBLE, sensor_1 DOUBLE, sensor_2 DOUBLE, sensor_3 DOUBLE, sensor_4 DOUBLE, sensor_5 DOUBLE, sensor_6 DOUBLE, sensor_7 DOUBLE, sensor_8 DOUBLE, sensor_9 DOUBLE, sensor_10 DOUBLE, sensor_11 DOUBLE, is_healthy INT, PRIMARY KEY (sensor_ID, sensor_ts) ) PARTITION BY HASH PARTITIONS 16 STORED AS KUDU TBLPROPERTIES ('kudu.num_tablet_replicas' = '1'); ---- + image::images/create_table.png[width=800] ==== CDSW Access Key . To configure and run the Spark Streaming job, you will need a CDSW Access Key to connect to the model endpoint that has been deployed there. To get the Access Key, go to the CDSW Web UI and click on *Models > Iot Prediction Model > Settings*. Copy the Access Key. + image::images/model_access_key.png[width=800] ==== Running the Spark job . Open a second Terminal and SSH into the VM. The first is running the sensor data simulator, so you can't use it. + [source,shell] ---- ACCESS_KEY= PUBLIC_IP=$(curl https://api.ipify.org/) mv ~/edge2ai-workshop/spark.iot.py ~ sed -i ""s/YourHostname/$(hostname -f)/"" spark.iot.py sed -i ""s/YourCDSWDomain/cdsw.$PUBLIC_IP.nip.io/"" spark.iot.py sed -i ""s/YourAccessKey/$ACCESS_KEY/"" spark.iot.py wget http://central.maven.org/maven2/org/apache/kudu/kudu-spark2_2.11/1.9.0/kudu-spark2_2.11-1.9.0.jar wget https://raw.githubusercontent.com/swordsmanliu/SparkStreamingHbase/master/lib/spark-core_2.11-1.5.2.logging.jar rm -rf ~/.m2 ~/.ivy2/ spark-submit \\ --master local[2] \\ --jars kudu-spark2_2.11-1.9.0.jar,spark-core_2.11-1.5.2.logging.jar \\ --packages org.apache.spark:spark-streaming-kafka_2.11:1.6.3 \\ spark.iot.py ---- + . Spark Streaming will flood your screen with log messages, however, at a 5 seconds interval, you should be able to spot a table: these are the messages that were consumed from Kafka and processed by Spark. You can configure Spark for a smaller time window, however, for this exercise 5 seconds is sufficient. + image::images/spark_job_output.png[width=800] [[lab_10, Lab 10]] == Lab 10 - Fast analytics on fast data with Kudu and Impala In this lab, you will run some SQL queries using the Impala engine. You can run a report to inform you which machines are likely to break in the near future. . Login into Hue and run the following queries in the Impala Query Editor: + [source,sql] ---- SELECT sensor_id, sensor_ts FROM sensors WHERE is_healthy = 0; ---- + [source,sql] ---- SELECT is_healthy, count(*) as occurrences FROM sensors GROUP BY is_healthy; ---- . Run a few times the SQL statements and verify that the number of occurrences are increasing as the data is ingested by either NiFi or the Spark job. This allows you to build real-time reports for fast action. + image::images/table_select.png[width=800] [[lab_11, Lab 11]] == Lab 11 - CDSW: Train the model In this and the following lab, you will wear the hat of a Data Scientist. You will write the model code, train it several times and finally deploy the model to Production. All within 30 minutes! === STEP 1: Configure CDSW . Open CDSW Web UI and log in as `admin`, if you haven't yet done so. . Navigate to the CDSW **Admin** page to fine tune the environment: .. In the **Engines** tab, add in _Engines Profiles_ a new engine (docker image) with 2 vCPUs and 4 GB RAM, while deleting the default engine. .. Check if the following variable already exists under _Environmental Variables_. If not, add it: + [source] ---- HADOOP_CONF_DIR=/etc/hadoop/conf/ ---- + image::images/engines.png[width=800] === STEP 2: Create the project . Return to the main page and click on *New Project*, using this GitHub project as the source: `https://github.com/cloudera-labs/edge2ai-workshop` + image::images/create_project.png[width=800] . Now that your project has been created, click on *Open Workbench* and start a Python3 session: + image::images/open_workbench.png[width=800] . Once the Engine is ready, run the following command to install some required libraries: + [source] ---- !pip3 install --upgrade pip scikit-learn ---- . The project comes with a historical dataset. Copy this dataset into HDFS: + [source] ---- !hdfs dfs -put -f data/historical_iot.txt /user/$HADOOP_USER_NAME ---- + image::images/session_prep.png[width=800] . You're now ready to run the Experiment to train the model on your historical data. . You can stop the Engine at this point. === STEP 3: Examine `cdsw.iot_exp.py` Open the file `cdsw.iot_exp.py`. This is a python program that builds a model to predict machine failure (the likelihood that this machine is going to fail). There is a dataset available on hdfs with customer data, including a failure indicator field. The program is going to build a failure prediction model using the Random Forest algorithm. Random forests are ensembles of decision trees. Random forests are one of the most successful machine learning models for classification and regression. They combine many decision trees in order to reduce the risk of overfitting. Like decision trees, random forests handle categorical features, extend to the multiclass classification setting, do not require feature scaling, and are able to capture non-linearities and feature interactions. `spark.mllib` supports random forests for binary and multiclass classification and for regression, using both continuous and categorical features. `spark.mllib` implements random forests using the existing decision tree implementation. Please see the decision tree guide for more information on trees. The Random Forest algorithm expects a couple of parameters: * *numTrees*: Number of trees in the forest. + Increasing the number of trees will decrease the variance in predictions, improving the model’s test-time accuracy. Training time increases roughly linearly in the number of trees. * *maxDepth*: Maximum depth of each tree in the forest. + Increasing the depth makes the model more expressive and powerful. However, deep trees take longer to train and are also more prone to overfitting. In general, it is acceptable to train deeper trees when using random forests than when using a single decision tree. One tree is more likely to overfit than a random forest (because of the variance reduction from averaging multiple trees in the forest). In the `cdsw.iot_exp.py` program, these parameters can be passed to the program at runtime, to these python variables: [source,python] ---- param_numTrees = int(sys.argv[1]) param_maxDepth = int(sys.argv[2]) ---- Also note the quality indicator for the Random Forest model, are written back to the Data Science Workbench repository: [source,python] ---- cdsw.track_metric(""auroc"", auroc) cdsw.track_metric(""ap"", ap) ---- These indicators will show up later in the **Experiments** dashboard. === STEP 4: Run the experiment for the first time . Now, run the experiment using the following parameters: + [source,python] ---- numTrees = 20 numDepth = 20 ---- . From the menu, select `Run -> Run Experiments...`. Now, in the background, the Data Science Workbench environment will spin up a new docker container, where this program will run. + image::images/run_experiment.png[width=800] . Go back to the **Projects** page in CDSW, and hit the **Experiments** button. . If the Status indicates `Running`, you have to wait till the run is completed. In case the status is `Build Failed` or `Failed` , check the log information. This is accessible by clicking on the run number of your experiments. There you can find the session log, as well as the build information. + image::images/experiment_details.png[width=800] . In case your status indicates `Success`, you should be able to see the *auroc* (Area Under the Curve) model quality indicator. It might be that this value is hidden by the CDSW user interface. In that case, click on the ‘3 metrics’ links, and select the auroc field. It might be needed to de-select some other fields, since the interface can only show 3 metrics at the same time. + image::images/exp_metrics.png[width=800] . In this example, `~0.8383`. Not bad, but maybe there are better hyper parameter values available. === STEP 5: Re-run the experiment several times . Go back to the Workbench and run the experiment 2 more times and try different values for NumTrees and NumDepth. Try the following values: + [source,python] ---- NumTrees NumDepth 15 25 25 20 ---- . When all runs have completed successfully, check which parameters had the best quality (best predictive value). This is represented by the highest _area under the curve_: `auroc` metric. + image::images/best_model.png[width=800] === STEP 6: Save the best model to your environment . Select the run number with the best predictive value (in the example above, experiment *4*). . In the *Overview* screen of the experiment, you can see that the model, in Pickle format (`.pkl`), is captured in the file `iot_model.pkl`. Select this file and hit the **Add to Project** button. This will copy the model to your project directory. + image::images/save_model.png[width=800] + image::images/model_saved.png[width=800] [[lab_12, Lab 12]] == Lab 12 - CDSW: Deploy the model === STEP 1: Examine the program `cdsw.iot_model.py` . Open the project you created in the previous lab and examine the file in the Workbench. This PySpark program uses the `pickle.load` mechanism to deploy models. The model is loaded from the `iot_modelf.pkl` file, which was saved in the previous lab from the experiment with the best predictive model. + There program also contains the `predict` definition, which is the function that calls the model, passing the features as parameters, and will return a result variable. . Before deploying the model, try it out in the Workbench: launch a Python3 engine and run the code in file `cdsw.iot_model.py`. Then call the `predict()` method from the prompt: + [source,python] ---- predict({""feature"": ""0, 65, 0, 137, 21.95, 83, 19.42, 111, 9.4, 6, 3.43, 4""}) ---- + image::images/predict.png[width=800] . The functions returns successfully, so we know we can now deploy the model. You can now stop the engine. === STEP 2: Deploy the model . From the main page of your project, select the *Models* button. Select *New Model* and specify the following configuration: + [source, python] ---- Name: IoT Prediction Model Description: IoT Prediction Model File: cdsw.iot_model.py Function: predict Example Input: {""feature"": ""0, 65, 0, 137, 21.95, 83, 19.42, 111, 9.4, 6, 3.43, 4""} Kernel: Python 3 Engine: 2 vCPU / 4 GB Memory Replicas: 1 ---- + image:images/create_model.png[width=800] . After all parameters are set, click on the *Deploy Model* button. Wait till the model is deployed. This can take several minutes. === STEP 3: Test the deployed model . When your model status change to `Deployed`, click on the model name link to go to the Model's *Overview* page. From the that page, click on the *Test* button to check if the model is working. . The green circle with the `success` status indicates that our REST call to the model is working. The `1` in the response `{""result"": 1}`, means that the machine from where these temperature readings were collected is _unlikely_ to experience a failure. + image::images/test_model.png[width=800] . Now, lets change the input parameters and call the predict function again. Put the following values in the Input field: + [source,python] ---- { ""feature"": ""0, 95, 0, 88, 26.62, 75, 21.05, 115, 8.65, 5, 3.32, 3"" } ---- . With these input parameters, the model returns `0`, which means that the machine is likely to break. == Resources * link:https://medium.freecodecamp.org/building-an-iiot-system-using-apache-nifi-mqtt-and-raspberry-pi-ce1d6ed565bc[Original blog by Abdelkrim Hadjidj] * This workshop was based on the following work by Fabio Ghirardello: ** https://github.com/fabiog1901/IoT-predictive-maintenance ** https://github.com/fabiog1901/OneNodeCDHCluster * link:https://www.cloudera.com/documentation.html[Cloudera Documentation] == Troubleshooting ==== *CEM doesn't pick up new NARs* . Delete the agent manifest manually using the EFM API: . Verify each class has the same agent manifest ID: + [source] ---- http://hostname:10088/efm/api/agent-classes [{""name"":""iot1"",""agentManifests"":[""agent-manifest-id""]},{""name"":""iot4"",""agentManifests"":[""agent-manifest-id""]}] ---- . Confirm the manifest doesn't have the NAR you installed + [source] ---- http://hostname:10088/efm/api/agent-manifests?class=iot4 [{""identifier"":""agent-manifest-id"",""agentType"":""minifi-java"",""version"":""1"",""buildInfo"":{""timestamp"":1556628651811,""compiler"":""JDK 8""},""bundles"":[{""group"":""default"",""artifact"":""system"",""version"":""unversioned"",""componentManifest"":{""controllerServices"":[],""processors"": ---- . Call the API endpoint: + [source] ---- http://hostname:10088/efm/swagger/ ---- . Hit the `DELETE - Delete the agent manifest specified by id` button, and in the id field, enter `agent-manifest-id` ",12196,False,2078.838978788437,median "//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the ""License""); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an ""AS IS"" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Simon Grätzer //////////////////////////////////////////////////////////////////////////////// #include ""RocksDBMetaCollection.h"" #include ""ApplicationFeatures/ApplicationServer.h"" #include ""Basics/ReadLocker.h"" #include ""Basics/RecursiveLocker.h"" #include ""Basics/VelocyPackHelper.h"" #include ""Basics/WriteLocker.h"" #include ""Basics/hashes.h"" #include ""Basics/system-functions.h"" #include ""Cluster/ServerState.h"" #include ""Random/RandomGenerator.h"" #include ""RocksDBEngine/RocksDBColumnFamilyManager.h"" #include ""RocksDBEngine/RocksDBFormat.h"" #include ""RocksDBEngine/RocksDBIndex.h"" #include ""RocksDBEngine/RocksDBLogValue.h"" #include ""RocksDBEngine/RocksDBMethods.h"" #include ""RocksDBEngine/RocksDBReplicationContext.h"" #include ""RocksDBEngine/RocksDBReplicationManager.h"" #include ""RocksDBEngine/RocksDBSettingsManager.h"" #include ""RocksDBEngine/RocksDBTransactionCollection.h"" #include ""RocksDBEngine/RocksDBTransactionState.h"" #include ""StorageEngine/EngineSelectorFeature.h"" #include ""Transaction/Context.h"" #include ""Transaction/Methods.h"" #include ""Transaction/StandaloneContext.h"" #include ""Utils/CollectionGuard.h"" #include ""Utils/OperationOptions.h"" #include ""Utils/SingleCollectionTransaction.h"" #include #include #include using namespace arangodb; namespace { rocksdb::SequenceNumber forceWrite(RocksDBEngine& engine) { auto* sm = engine.settingsManager(); if (sm) { sm->sync(true); // force } return engine.db()->GetLatestSequenceNumber(); } } // namespace RocksDBMetaCollection::RocksDBMetaCollection(LogicalCollection& collection, VPackSlice const& info) : PhysicalCollection(collection, info), _objectId(basics::VelocyPackHelper::stringUInt64( info, StaticStrings::ObjectId)), _revisionTreeApplied(0), _revisionTreeCreationSeq(0), _revisionTreeSerializedSeq(0), _revisionTreeSerializedTime(std::chrono::steady_clock::now()) { TRI_ASSERT(!ServerState::instance()->isCoordinator()); TRI_ASSERT(_logicalCollection.isAStub() || _objectId != 0); collection.vocbase() .server() .getFeature() .engine() .addCollectionMapping(_objectId, _logicalCollection.vocbase().id(), _logicalCollection.id()); } std::string const& RocksDBMetaCollection::path() const { return StaticStrings::Empty; // we do not have any path } void RocksDBMetaCollection::deferDropCollection( std::function const&) { TRI_ASSERT(!_logicalCollection.syncByRevision()); std::unique_lock guard(_revisionTreeLock); _revisionTree.reset(); } RevisionId RocksDBMetaCollection::revision(transaction::Methods* trx) const { auto* state = RocksDBTransactionState::toState(trx); auto trxCollection = static_cast( state->findCollection(_logicalCollection.id())); TRI_ASSERT(trxCollection != nullptr); return trxCollection->revision(); } uint64_t RocksDBMetaCollection::numberDocuments( transaction::Methods* trx) const { TRI_ASSERT(!ServerState::instance()->isCoordinator()); auto* state = RocksDBTransactionState::toState(trx); auto trxCollection = static_cast( state->findCollection(_logicalCollection.id())); TRI_ASSERT(trxCollection != nullptr); return trxCollection->numberDocuments(); } /// @brief write locks a collection, with a timeout ErrorCode RocksDBMetaCollection::lockWrite(double timeout) { return doLock(timeout, AccessMode::Type::WRITE); } /// @brief write unlocks a collection void RocksDBMetaCollection::unlockWrite() noexcept { _exclusiveLock.unlockWrite(); } /// @brief read locks a collection, with a timeout ErrorCode RocksDBMetaCollection::lockRead(double timeout) { return doLock(timeout, AccessMode::Type::READ); } /// @brief read unlocks a collection void RocksDBMetaCollection::unlockRead() { _exclusiveLock.unlockRead(); } void RocksDBMetaCollection::trackWaitForSync( arangodb::transaction::Methods* trx, OperationOptions& options) { if (_logicalCollection.waitForSync() && !options.isRestore) { options.waitForSync = true; } if (options.waitForSync) { trx->state()->waitForSync(true); } } // rescans the collection to update document count uint64_t RocksDBMetaCollection::recalculateCounts() { std::unique_lock guard(_recalculationLock); RocksDBEngine& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); rocksdb::TransactionDB* db = engine.db(); const rocksdb::Snapshot* snapshot = nullptr; // start transaction to get a collection lock TRI_vocbase_t& vocbase = _logicalCollection.vocbase(); if (!vocbase.use()) { // someone dropped the database return _meta.numberDocuments(); } auto useGuard = scopeGuard([&]() noexcept { // cppcheck-suppress knownConditionTrueFalse if (snapshot) { db->ReleaseSnapshot(snapshot); } vocbase.release(); }); // makes sure collection doesn't get unloaded CollectionGuard collGuard(&vocbase, _logicalCollection.id()); RocksDBBlockerGuard blocker(&_logicalCollection); uint64_t snapNumberOfDocuments = 0; { // fetch number docs and snapshot under exclusive lock // this should enable us to correct the count later auto lockGuard = scopeGuard([this]() noexcept { unlockWrite(); }); auto res = lockWrite(transaction::Options::defaultLockTimeout); if (res != TRI_ERROR_NO_ERROR) { lockGuard.cancel(); THROW_ARANGO_EXCEPTION(res); } // place a blocker. will be removed by blockerGuard automatically blocker.placeBlocker(); snapshot = engine.db()->GetSnapshot(); snapNumberOfDocuments = _meta.numberDocuments(); TRI_ASSERT(snapshot); } auto snapSeq = snapshot->GetSequenceNumber(); auto bounds = RocksDBKeyBounds::Empty(); bool set = false; { RECURSIVE_READ_LOCKER(_indexesLock, _indexesLockWriteOwner); for (auto it : _indexes) { if (it->type() == Index::TRI_IDX_TYPE_PRIMARY_INDEX) { RocksDBIndex const* rix = static_cast(it.get()); bounds = RocksDBKeyBounds::PrimaryIndex(rix->objectId()); set = true; break; } } } if (!set) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, ""did not find primary index""); } // count documents rocksdb::Slice upper(bounds.end()); rocksdb::ReadOptions ro; ro.snapshot = snapshot; ro.prefix_same_as_start = true; ro.iterate_upper_bound = &upper; ro.verify_checksums = false; ro.fill_cache = false; rocksdb::ColumnFamilyHandle* cf = bounds.columnFamily(); std::unique_ptr it(db->NewIterator(ro, cf)); std::size_t count = 0; application_features::ApplicationServer& server = vocbase.server(); for (it->Seek(bounds.start()); it->Valid(); it->Next()) { TRI_ASSERT(it->key().compare(upper) < 0); ++count; if (count % 4096 == 0 && server.isStopping()) { // check for server shutdown THROW_ARANGO_EXCEPTION(TRI_ERROR_SHUTTING_DOWN); } } int64_t adjustment = count - snapNumberOfDocuments; TRI_IF_FAILURE(""disableCountAdjustment"") { adjustment = 0; } if (adjustment != 0) { LOG_TOPIC(""ad613"", WARN, Logger::REPLICATION) << ""inconsistent collection count detected for "" << vocbase.name() << ""/"" << _logicalCollection.name() << "": counted value: "" << count << "", snapshot value: "" << snapNumberOfDocuments << "", current value: "" << _meta.numberDocuments() << "", an offset of "" << adjustment << "" will be applied""; auto adjustSeq = engine.db()->GetLatestSequenceNumber(); if (adjustSeq <= snapSeq) { adjustSeq = ::forceWrite(engine); TRI_ASSERT(adjustSeq > snapSeq); } _meta.adjustNumberDocuments(adjustSeq, RevisionId::none(), adjustment); } else { LOG_TOPIC(""55df5"", INFO, Logger::REPLICATION) << ""no collection count adjustment needs to be applied for "" << vocbase.name() << ""/"" << _logicalCollection.name() << "": counted value: "" << count; } return _meta.numberDocuments(); } void RocksDBMetaCollection::compact() { auto& selector = _logicalCollection.vocbase().server().getFeature(); auto& engine = selector.engine(); engine.compactRange(bounds()); RECURSIVE_READ_LOCKER(_indexesLock, _indexesLockWriteOwner); for (std::shared_ptr i : _indexes) { RocksDBIndex* index = static_cast(i.get()); index->compact(); } } void RocksDBMetaCollection::estimateSize(velocypack::Builder& builder) { TRI_ASSERT(!builder.isOpenObject() && !builder.isOpenArray()); auto& selector = _logicalCollection.vocbase().server().getFeature(); auto& engine = selector.engine(); rocksdb::TransactionDB* db = engine.db(); RocksDBKeyBounds bounds = this->bounds(); rocksdb::Range r(bounds.start(), bounds.end()); uint64_t out = 0, total = 0; db->GetApproximateSizes( bounds.columnFamily(), &r, 1, &out, static_cast( rocksdb::DB::SizeApproximationFlags::INCLUDE_MEMTABLES | rocksdb::DB::SizeApproximationFlags::INCLUDE_FILES)); total += out; builder.openObject(); builder.add(""documents"", VPackValue(out)); builder.add(""indexes"", VPackValue(VPackValueType::Object)); RECURSIVE_READ_LOCKER(_indexesLock, _indexesLockWriteOwner); for (std::shared_ptr i : _indexes) { RocksDBIndex* index = static_cast(i.get()); out = index->memory(); builder.add(std::to_string(index->id().id()), VPackValue(out)); total += out; } builder.close(); builder.add(""total"", VPackValue(total)); builder.close(); } void RocksDBMetaCollection::setRevisionTree( std::unique_ptr&& tree, uint64_t seq) { TRI_ASSERT(_logicalCollection.useSyncByRevision()); TRI_ASSERT(_logicalCollection.syncByRevision()); TRI_ASSERT(tree != nullptr); TRI_ASSERT(tree->depth() == revisionTreeDepth); std::unique_lock guard(_revisionTreeLock); _revisionTree = std::make_unique(std::move(tree), _logicalCollection); _revisionTreeApplied = seq; _revisionTreeCreationSeq = seq; _revisionTreeSerializedSeq = seq; _revisionTreeSerializedTime = std::chrono::steady_clock::time_point(); _revisionTreeCanBeSerialized = true; } std::unique_ptr RocksDBMetaCollection::revisionTree( rocksdb::SequenceNumber notAfter, std::function( std::unique_ptr, std::unique_lock&)> const& callback) { if (!_logicalCollection.useSyncByRevision()) { return nullptr; } RocksDBEngine& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); rocksdb::DB* db = engine.db()->GetRootDB(); std::unique_lock lock(_revisionTreeLock); // first apply any updates that can be safely applied rocksdb::SequenceNumber safeSeq = meta().committableSeq(db->GetLatestSequenceNumber()); if (notAfter < safeSeq) { safeSeq = notAfter; } if (!_revisionTree && !haveBufferedOperations(lock)) { // we only need to return an empty tree here. lock.unlock(); return allocateEmptyRevisionTree(revisionTreeDepth); } // If the tree has already moved past `notAfter`, then all is lost and we can // only give up: if (_revisionTreeApplied > notAfter) { return nullptr; } applyUpdates(safeSeq, lock); // will not go beyond `notAfter` because code above! TRI_ASSERT(_revisionTree != nullptr); TRI_ASSERT(_revisionTree->depth() == revisionTreeDepth); // now clone the tree so we can apply all updates consistent with our ongoing // trx auto tree = _revisionTree->clone(); TRI_ASSERT(tree != nullptr); return callback(std::move(tree), lock); } std::unique_ptr RocksDBMetaCollection::revisionTree( transaction::Methods& trx) { rocksdb::SequenceNumber trxSeq = RocksDBTransactionState::toState(&trx)->beginSeq(); TRI_ASSERT(trxSeq != 0); return revisionTree( trxSeq, [this, &trx, trxSeq](std::unique_ptr tree, std::unique_lock& lock) -> std::unique_ptr { TRI_ASSERT(lock.owns_lock()); // apply any which are buffered and older than our ongoing transaction // start Result res = applyUpdatesForTransaction(*tree, trxSeq, lock); if (res.fail()) { return nullptr; } // now peek at updates buffered inside transaction and apply those too auto const& operations = RocksDBTransactionState::toState(&trx)->trackedOperations( _logicalCollection.id()); // this revision tree exists only temporarily, so we do not track its // memory usage tree->insert(operations.inserts); tree->remove(operations.removals); return tree; }); } std::unique_ptr RocksDBMetaCollection::revisionTree( uint64_t batchId) { RocksDBEngine& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); RocksDBReplicationManager* manager = engine.replicationManager(); RocksDBReplicationContext* ctx = batchId == 0 ? nullptr : manager->find(batchId); if (!ctx) { return nullptr; } auto guard = scopeGuard([manager, ctx]() noexcept -> void { manager->release(ctx); }); rocksdb::SequenceNumber trxSeq = ctx->snapshotTick(); TRI_ASSERT(trxSeq != 0); return revisionTree( trxSeq, [this, trxSeq](std::unique_ptr tree, std::unique_lock& lock) -> std::unique_ptr { TRI_ASSERT(lock.owns_lock()); // apply any which are buffered and older than our ongoing transaction // start Result res = applyUpdatesForTransaction(*tree, trxSeq, lock); if (res.fail()) { return nullptr; } return tree; }); } std::unique_ptr RocksDBMetaCollection::computeRevisionTree(uint64_t batchId) { std::unique_ptr iter = _logicalCollection.getPhysical()->getReplicationIterator( ReplicationIterator::Ordering::Revision, batchId); if (!iter) { LOG_TOPIC(""52617"", WARN, arangodb::Logger::ENGINES) << ""failed to retrieve replication iterator to build revision tree "" ""for collection '"" << _logicalCollection.id().id() << ""'""; return nullptr; } RevisionReplicationIterator& it = *static_cast(iter.get()); // the tree may only be there temporarily, so we intentionally do // not track its memory usage here, but rather at some indirect call sites // only. return buildTreeFromIterator(it); } Result RocksDBMetaCollection::takeCareOfRevisionTreePersistence( LogicalCollection& coll, RocksDBEngine& engine, rocksdb::WriteBatch& batch, rocksdb::ColumnFamilyHandle* const cf, rocksdb::SequenceNumber maxCommitSeq, bool force, std::string const& context, std::string& scratch, rocksdb::SequenceNumber& appliedSeq) { TRI_ASSERT(coll.useSyncByRevision()); // might lower `appliedSeq`! // Get lock on revision tree: std::unique_lock guard(_revisionTreeLock); if (maxCommitSeq < _revisionTreeApplied) { // this function is called indirectly from RocksDBSettingsManager::sync // which passes in a seq nr that it has previously obtained, but it can // happen that in the meantime the tree has been moved forward or a tree was // rebuilt and _revisionTreeApplied is now greater than the seq nr we get // passed in. In this case we have to bump the seq nr forward, because we // cannot generate a tree from the past. maxCommitSeq = _revisionTreeApplied; } maxCommitSeq = _meta.committableSeq(maxCommitSeq); if ((force || needToPersistRevisionTree(maxCommitSeq, guard)) && _revisionTreeCanBeSerialized) { rocksdb::SequenceNumber seq = maxCommitSeq; TRI_ASSERT(maxCommitSeq >= _revisionTreeApplied); scratch.clear(); try { seq = serializeRevisionTree(scratch, seq, force, guard); } catch (std::exception const& ex) { LOG_TOPIC(""33691"", WARN, Logger::ENGINES) << context << "": caught exception during revision tree serialization: "" << ex.what(); auto& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); auto* db = engine.db(); rocksdb::WriteOptions wo; RocksDBKey key; // remove revision tree from rocksdb key.constructRevisionTreeValue(_objectId); rocksdb::Status s = batch.Delete(cf, key.string()); if (s.ok() || s.IsNotFound()) { s = db->Write(wo, &batch); } if (!s.ok()) { LOG_TOPIC(""af3de"", WARN, Logger::ENGINES) << context << "": could not delete invalid revision tree: "" << s.ToString(); // continue and schedule a tree rebuild } batch.Clear(); // if we crash now, we won't have a revision tree and can rebuild it from // scratch on restart. // now also prevent this revision tree from being serialized... _revisionTreeCanBeSerialized = false; // you can take our trees, but you cannot take our souls! // schedule a rebuild for the tree: engine.scheduleTreeRebuild(coll.vocbase().id(), coll.guid()); // we cannot move beyond the seq no that we have already serialized up to. // this will effectively keep the background thread from making progress, // but the scheduled tree rebuild operation should unblock it eventually. appliedSeq = std::min(appliedSeq, _revisionTreeSerializedSeq); return {}; } guard.unlock(); appliedSeq = std::min(appliedSeq, seq); if (!scratch.empty()) { rocksutils::uint64ToPersistent(scratch, seq); RocksDBKey key; key.constructRevisionTreeValue(objectId()); rocksdb::Slice value(scratch); rocksdb::Status s = batch.Put(cf, key.string(), value); if (!s.ok()) { LOG_TOPIC(""ff234"", WARN, Logger::ENGINES) << context << "": writing revision tree failed""; return Result(rocksutils::convertStatus(s)); } else { LOG_TOPIC(""92a08"", TRACE, Logger::ENGINES) << context << "": serialized revision tree for "" << ""collection with objectId '"" << objectId() << ""' "" << ""through sequence number "" << seq; } } else { LOG_TOPIC(""92b07"", TRACE, Logger::ENGINES) << context << "": skipping serialization of revision tree for "" << ""collection with objectId '"" << objectId() << ""'""; } } else { LOG_TOPIC(""92ba9"", TRACE, Logger::ENGINES) << context << "": no need to serialize revision tree for "" << ""collection with objectId '"" << objectId() << ""'""; TRI_IF_FAILURE(""serializeMeta::delayCallToLastSerializedRevisionTree"") { if (!coll.system()) { std::this_thread::sleep_for(std::chrono::seconds(5)); } } // Find out up to which sequence the tree of this collection has been // persisted to RocksDB. We need this to compute the minimum over all // collections for the persisted `lastSync` value (in `appliedSeq`). // Note that on recovery after a crash (or restart) all WAL entries // lower than the persisted `lastSync` are ignored. Therefore it // is imperative that there are no pending or actual changes for // the revision tree in memory, which will end up in the WAL with a // sequence number less than the computed `seq` number here! rocksdb::SequenceNumber seq = lastSerializedRevisionTree(maxCommitSeq, guard); appliedSeq = std::min(appliedSeq, seq); // set the tree to sleep (note: hibernation requests may be ignored if there // is not yet a need to hibernate) hibernateRevisionTree(guard); } return Result{}; } bool RocksDBMetaCollection::needToPersistRevisionTree( rocksdb::SequenceNumber maxCommitSeq, std::unique_lock const& lock) const { TRI_ASSERT(lock.owns_lock()); TRI_ASSERT(_logicalCollection.useSyncByRevision()); if (!_revisionTreeCanBeSerialized) { return false; } bool checkBuffers = true; TRI_IF_FAILURE(""needToPersistRevisionTree::checkBuffers"") { checkBuffers = false; } if (checkBuffers) { // have a truncate to apply if (!_revisionTruncateBuffer.empty() && *_revisionTruncateBuffer.begin() <= maxCommitSeq) { return true; } // have insertions to apply if (!_revisionInsertBuffers.empty() && _revisionInsertBuffers.begin()->first <= maxCommitSeq) { return true; } // have removals to apply if (!_revisionRemovalBuffers.empty() && _revisionRemovalBuffers.begin()->first <= maxCommitSeq) { return true; } } // have applied updates that we haven't persisted if (_revisionTreeSerializedSeq < _revisionTreeApplied) { return true; } // tree has never been persisted if (_revisionTreeSerializedSeq <= _revisionTreeCreationSeq) { return true; } return false; } rocksdb::SequenceNumber RocksDBMetaCollection::lastSerializedRevisionTree( rocksdb::SequenceNumber seq, std::unique_lock const& lock) { TRI_ASSERT(lock.owns_lock()); // As explained at the call site in RocksDBMetadata.cpp the purpose of // this function is to compute a sequence number s, which is as large // as possible with the property, that there are and will never be // any changes to the collection with a sequence number larger than // the sequence number of the last persisted version of the revision tree // *and* smaller than s. Therefore, we can in the end move the in memory // sequence number forward of the latest serialized revision tree. // See below for a proof that we do not miss any transactions! // A transaction commit proceeds as follows: // // 1. Note the latest sequence number in the RocksDB WAL, call it ""beginSeq"" // 2. Create a blocker for all collections involved with beginSeq, if this // is not possible, bump beginSeq forward (by getting a new latest // sequence number from RocksDB). After this step, we have blockers // on all collections involved for sequence numbers, which are all // at most beginSeq in its final state. // 3. Commit the rocksDB transaction, this will result in a WAL sequence // number for the commit marker called ""postCommitSeq"". It and all // sequence numbers of write operations for the transaction are larger // than beginSeq. // 4. Call `bufferUpdates` on the `RocksDBMetaCollection and submit all // revisions which have been inserted or removed, which in turns // queues these operations in `_revisionInsertBuffers` and // `_revisionRemoveBuffers` for the revision tree, filed under // the sequence number `postCommitSeq`. // 5. Remove the blockers for the transaction. // // After that, at some stage the pending insertions and removals are // actually applied to the tree and its `_revisionTreeApplied` is moved // forward. The new tree will eventually be persisted again. // Note that since `beginSeq` is always smaller than any sequence number // involved in the transaction (including `postCommitSeq`), // we always have a blocker with `beginSeq` (or smaller) whenever // we write operations to the WAL. // bump sequence number forward for the tree only if this is safe if (_revisionTruncateBuffer.empty() && _revisionInsertBuffers.empty() && _revisionRemovalBuffers.empty() && _revisionTreeApplied < seq && _revisionTreeSerializedSeq < seq && _revisionTreeCanBeSerialized && !_meta.hasBlockerUpTo(seq)) { // If we get here, we can advance `_revisionTreeSerializedSeq` // and `_revisionTreeApplied` to `seq`, // although we have not actually persisted the tree at `seq`. // All we have to ensure that no transaction has or will ever again // produce a change with a sequence number larger than // `_revisitionTreeSerializedSeq` and smaller than or equal to `seq`. // This is true, because of the following: // Assume some transaction that touches this collection would end up // with its commit marker at a sequence number between // `_revisionTreeSerializedSeq` and `seq` (i.e. its // `postCommitSeq`). Then it must have before got a blocker for its // `beginSeq` number in Step 2 above. So either, we still see the blocker, // or the corresponding operations have already been added to the buffers, // or they have already been applied to the tree, in which case // `_revisionTreeApplied` would be larger than `seq`. q.e.d. LOG_TOPIC(""32d45"", TRACE, Logger::ENGINES) << ""adjusting sequence number for "" << _logicalCollection.name() << "" from "" << _revisionTreeSerializedSeq << "" to "" << seq; _revisionTreeSerializedSeq = seq; _revisionTreeApplied = seq; // This allows to uphold the invariants that // _revisionTreeCreationSeq <= _revisionTreeSerializedSeq and // _revisionTreeSerializedSeq <= _revisionTreeApplied. } return _revisionTreeSerializedSeq; } rocksdb::SequenceNumber RocksDBMetaCollection::serializeRevisionTree( std::string& output, rocksdb::SequenceNumber commitSeq, bool force, std::unique_lock const& lock) { TRI_ASSERT(lock.owns_lock()); TRI_ASSERT(_logicalCollection.useSyncByRevision()); if (!_revisionTree && !haveBufferedOperations(lock)) { // empty collection return commitSeq; } if (!_revisionTreeCanBeSerialized) { // previously, a revision tree was found to be bad and is now being // repaired, in the meantime we return the number when it was last persisted // to avoid lastSync jumping down again later return _revisionTreeSerializedSeq; } applyUpdates(commitSeq, lock); // always apply updates... TRI_ASSERT(_revisionTreeApplied == commitSeq); // applyUpdates will make sure we will have a valid tree TRI_ASSERT(_revisionTree != nullptr); TRI_ASSERT(_revisionTree->depth() == revisionTreeDepth); bool neverDone = _revisionTreeSerializedSeq <= _revisionTreeCreationSeq; bool coinFlip = RandomGenerator::interval(static_cast(5)) == 0; bool beenTooLong = 30 < std::chrono::duration_cast( std::chrono::steady_clock::now() - _revisionTreeSerializedTime) .count(); TRI_IF_FAILURE(""RocksDBMetaCollection::forceSerialization"") { coinFlip = true; } TRI_IF_FAILURE(""RocksDBMetaCollection::serializeRevisionTree"") { return _revisionTreeSerializedSeq; } if (force || neverDone || coinFlip || beenTooLong) { // ...but only write the tree out sometimes _revisionTree->serializeBinary(output); _revisionTreeSerializedSeq = commitSeq; _revisionTreeSerializedTime = std::chrono::steady_clock::now(); if (_revisionTreeSerializedSeq < _revisionTreeCreationSeq) { _revisionTreeCreationSeq = _revisionTreeSerializedSeq; } } return _revisionTreeSerializedSeq; } ResultT, rocksdb::SequenceNumber>> RocksDBMetaCollection::revisionTreeFromCollection(bool checkForBlockers) { auto ctxt = transaction::StandaloneContext::Create(_logicalCollection.vocbase()); SingleCollectionTransaction trx(ctxt, _logicalCollection, AccessMode::Type::READ); Result res = trx.begin(); if (res.fail()) { LOG_TOPIC(""d1e53"", WARN, arangodb::Logger::ENGINES) << ""failed to begin transaction to rebuild revision tree "" ""for collection '"" << _logicalCollection.id().id() << ""'""; return res; } auto* state = RocksDBTransactionState::toState(&trx); if (checkForBlockers && _meta.hasBlockerUpTo(state->beginSeq())) { return Result(TRI_ERROR_LOCKED, ""cannot rebuild revision tree now as there are still "" ""transaction blockers in place""); } auto iter = getReplicationIterator(ReplicationIterator::Ordering::Revision, trx); if (!iter) { LOG_TOPIC(""d1e54"", WARN, arangodb::Logger::ENGINES) << ""failed to retrieve replication iterator to rebuild revision tree "" ""for collection '"" << _logicalCollection.id().id() << ""'""; return Result(TRI_ERROR_INTERNAL); } RevisionReplicationIterator& it = *static_cast(iter.get()); // the tree may only be there temporarily, so we intentionally do // not track its memory usage here, but rather at some indirect call sites // only. auto newTree = buildTreeFromIterator(it); return std::make_pair(std::move(newTree), state->beginSeq()); } std::unique_ptr RocksDBMetaCollection::buildTreeFromIterator( RevisionReplicationIterator& it) const { std::vector revisions; revisions.reserve(1024); auto newTree = allocateEmptyRevisionTree(revisionTreeDepth); while (it.hasMore()) { revisions.emplace_back(it.revision().id()); if (revisions.size() >= 4096) { // arbitrary batch size newTree->insert(revisions); revisions.clear(); if (_logicalCollection.vocbase().server().isStopping()) { THROW_ARANGO_EXCEPTION(TRI_ERROR_SHUTTING_DOWN); } } it.next(); } if (!revisions.empty()) { newTree->insert(revisions); } #ifdef ARANGODB_ENABLE_MAINTAINER_MODE newTree->checkConsistency(); #endif return newTree; } #ifdef ARANGODB_ENABLE_FAILURE_TESTS void RocksDBMetaCollection::corruptRevisionTree(uint64_t count, uint64_t hash) { if (!_logicalCollection.useSyncByRevision()) { return; } std::unique_lock guard(_revisionTreeLock); if (_revisionTree != nullptr) { _revisionTree->corrupt(count, hash); } } #endif Result RocksDBMetaCollection::rebuildRevisionTree() { if (!_logicalCollection.useSyncByRevision()) { return {}; } return basics::catchToResult([this]() -> Result { auto lockGuard = scopeGuard([this]() noexcept { unlockWrite(); }); // get the exclusive lock on the collection, so that no new write // transactions can start for this collection auto res = lockWrite(/*timeout*/ 180.0); if (res != TRI_ERROR_NO_ERROR) { lockGuard.cancel(); THROW_ARANGO_EXCEPTION(res); } // we now have the exclusive lock on the collection! // utility function to remove buffered updates up to (including) seq. // requires the buffer lock to be held! auto removeBufferedUpdatesUpTo = [this](rocksdb::SequenceNumber seq) { { auto it = _revisionTruncateBuffer.begin(); while (it != _revisionTruncateBuffer.end() && *it <= seq) { it = _revisionTruncateBuffer.erase(it); } } { auto it = _revisionInsertBuffers.begin(); while (it != _revisionInsertBuffers.end() && it->first <= seq) { it = _revisionInsertBuffers.erase(it); } } { auto it = _revisionRemovalBuffers.begin(); while (it != _revisionRemovalBuffers.end() && it->first <= seq) { it = _revisionRemovalBuffers.erase(it); } } }; // place a blocker and add a guard to remove it at the end TransactionId trxId = TransactionId(transaction::Context::makeTransactionId()); auto blockerGuard = scopeGuard([&]() noexcept { // remove blocker afterwards removeRevisionTreeBlocker(trxId); }); TRI_IF_FAILURE(""rebuildRevisionTree::sleep"") { std::this_thread::sleep_for( std::chrono::milliseconds(RandomGenerator::interval(uint32_t(2000)))); } // we now have a blocker in place that will prevent updates from being // applied rocksdb::SequenceNumber blockerSeq = placeRevisionTreeBlocker(trxId); TRI_IF_FAILURE(""rebuildRevisionTree::sleep"") { std::this_thread::sleep_for( std::chrono::milliseconds(RandomGenerator::interval(uint32_t(2000)))); } { // we may still have some buffered updates, so let's remove them. std::unique_lock guard(_revisionTreeLock); removeBufferedUpdatesUpTo(blockerSeq - 1); _revisionTreeApplied = blockerSeq - 1; } // unlock the collection again lockGuard.fire(); TRI_IF_FAILURE(""rebuildRevisionTree::sleep"") { std::this_thread::sleep_for( std::chrono::milliseconds(RandomGenerator::interval(uint32_t(2000)))); } // now rebuild the tree from the collection data, using a // snapshot that will be acquired inside `revisionTreeFromCollection`. // note that the snapshot may have a sequence number > blockerSeq! auto result = revisionTreeFromCollection(false); if (result.fail()) { return result.result(); } auto&& [newTree, beginSeq] = result.get(); TRI_ASSERT(blockerSeq <= beginSeq); // update our blocker to the sequence number from the snapshot _meta.updateBlocker(trxId, beginSeq); TRI_IF_FAILURE(""rebuildRevisionTree::sleep"") { std::this_thread::sleep_for( std::chrono::milliseconds(RandomGenerator::interval(uint32_t(2000)))); } // we need to set a timeout for this operation, because if it does not // complete within reasonable bounds, we need to relinquish the thread that // is kept busy waiting here. auto const endTime = std::chrono::steady_clock::now() + std::chrono::minutes(2); // wait until all blockers before the snapshot have been removed while (true) { std::unique_lock guard(_revisionTreeLock); if (_revisionTreeApplied < beginSeq) { _revisionTreeApplied = beginSeq; } TRI_IF_FAILURE(""rebuildRevisionTree::sleep"") { if (RandomGenerator::interval(uint32_t(2000)) > 1750) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_DEBUG, ""intentional error during testing""); } } if (_meta.hasBlockerUpTo(beginSeq - 1)) { guard.unlock(); if (_logicalCollection.vocbase().server().isStopping()) { // react on server shutdown THROW_ARANGO_EXCEPTION(TRI_ERROR_SHUTTING_DOWN); } if (std::chrono::steady_clock::now() > endTime) { // timeout reached. abort and later try again std::string msg( ""unable to establish new revision tree for collection '""); msg.append(_logicalCollection.name()); msg.append(""' in time""); LOG_TOPIC(""d7560"", WARN, Logger::ENGINES) << msg; THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, std::move(msg)); } std::this_thread::sleep_for(std::chrono::milliseconds(50)); continue; } TRI_ASSERT(_revisionTreeApplied <= beginSeq); TRI_ASSERT(_revisionTreeSerializedSeq <= beginSeq); // establish the new tree. this will also track the memory usage of the // tree _revisionTree = std::make_unique( std::move(newTree), _logicalCollection); _revisionTreeApplied = beginSeq; _revisionTreeCreationSeq = beginSeq; _revisionTreeSerializedSeq = beginSeq; _revisionTreeSerializedTime = std::chrono::steady_clock::time_point(); _revisionTreeCanBeSerialized = true; // finally remove all pending updates up to including our own sequence // number removeBufferedUpdatesUpTo(beginSeq); return {}; } }); } void RocksDBMetaCollection::rebuildRevisionTree( std::unique_ptr& iter) { auto newTree = allocateEmptyRevisionTree(revisionTreeDepth); // okay, we are in recovery and can't open a transaction, so we need to // read the raw RocksDB data; on the plus side, we are in recovery, so we // are single-threaded and don't need to worry about transactions anyway RocksDBKeyBounds documentBounds = RocksDBKeyBounds::CollectionDocuments(_objectId); rocksdb::Comparator const* cmp = RocksDBColumnFamilyManager::get( RocksDBColumnFamilyManager::Family::Documents) ->GetComparator(); rocksdb::Slice const end = documentBounds.end(); auto& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); auto* db = engine.db(); std::vector revisions; revisions.reserve(1024); std::unique_lock guard(_revisionTreeLock); for (iter->Seek(documentBounds.start()); iter->Valid() && cmp->Compare(iter->key(), end) < 0; iter->Next()) { LocalDocumentId const docId = RocksDBKey::documentId(iter->key()); revisions.emplace_back(docId.id()); if (revisions.size() >= 4096) { // arbitrary batch size newTree->insert(revisions); revisions.clear(); if (_logicalCollection.vocbase().server().isStopping()) { THROW_ARANGO_EXCEPTION(TRI_ERROR_SHUTTING_DOWN); } } } if (!revisions.empty()) { newTree->insert(revisions); } #ifdef ARANGODB_ENABLE_MAINTAINER_MODE newTree->checkConsistency(); #endif rocksdb::SequenceNumber seq = db->GetLatestSequenceNumber(); _revisionTree = std::make_unique(std::move(newTree), _logicalCollection); _revisionTreeApplied = seq; _revisionTreeCreationSeq = seq; _revisionTreeSerializedSeq = seq; _revisionTreeSerializedTime = std::chrono::steady_clock::time_point(); _revisionTreeCanBeSerialized = true; } // returns a pair with the number of documents and the tree's seq number. std::pair RocksDBMetaCollection::revisionTreeInfo() const { TRI_ASSERT(_logicalCollection.useSyncByRevision()); std::unique_lock guard(_revisionTreeLock); if (_revisionTree != nullptr) { return {_revisionTree->count(), _revisionTreeApplied}; } return {0, 0}; } void RocksDBMetaCollection::revisionTreeSummary(VPackBuilder& builder, bool fromCollection) { if (!_logicalCollection.useSyncByRevision()) { return; } uint64_t count = 0; uint64_t hash = 0; uint64_t byteSize = 0; if (fromCollection) { // rebuild a temporary tree from the collection auto result = revisionTreeFromCollection(false); // the tree is only there temporarily, so we intentionally do // not track its memory usage! if (result.fail()) { THROW_ARANGO_EXCEPTION(result.result()); } auto&& [tree, beginSeq] = result.get(); count = tree->count(); hash = tree->rootValue(); byteSize = tree->byteSize(); } else { // use existing revision tree std::unique_lock guard(_revisionTreeLock); if (_revisionTree != nullptr) { count = _revisionTree->count(); hash = _revisionTree->rootValue(); byteSize = _revisionTree->compressedSize(); } } VPackObjectBuilder obj(&builder); obj->add(StaticStrings::RevisionTreeCount, VPackValue(count)); obj->add(StaticStrings::RevisionTreeHash, VPackValue(hash)); obj->add(""byteSize"", VPackValue(byteSize)); } void RocksDBMetaCollection::revisionTreePendingUpdates(VPackBuilder& builder) { VPackObjectBuilder obj(&builder); if (!_logicalCollection.useSyncByRevision()) { // empty object return; } std::unique_lock guard(_revisionTreeLock); if (_revisionTree == nullptr) { // no revision tree yet return; } uint64_t inserts = _revisionInsertBuffers.size(); uint64_t removes = _revisionRemovalBuffers.size(); uint64_t truncates = _revisionTruncateBuffer.size(); guard.unlock(); obj->add(""inserts"", VPackValue(inserts)); obj->add(""removes"", VPackValue(removes)); obj->add(""truncates"", VPackValue(truncates)); } uint64_t RocksDBMetaCollection::placeRevisionTreeBlocker( TransactionId transactionId) { auto& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); rocksdb::TransactionDB* db = engine.db(); // make sure that the global revision tree in _revisionTree does not move // beyond the sequence number we get here from RocksDB: std::unique_lock guard(_revisionTreeLock); while (true) { rocksdb::SequenceNumber preSeq = db->GetLatestSequenceNumber(); // Since we have the lock above, the revision tree cannot move beyond // this sequence number before we have actually placed the blocker. if (preSeq >= _revisionTreeApplied && preSeq >= _revisionTreeSerializedSeq && preSeq >= _meta.countCommitted()) { _meta.placeBlocker(transactionId, preSeq); return preSeq; } if (_logicalCollection.vocbase().server().isStopping()) { THROW_ARANGO_EXCEPTION(TRI_ERROR_SHUTTING_DOWN); } std::this_thread::yield(); } } void RocksDBMetaCollection::removeRevisionTreeBlocker( TransactionId transactionId) { _meta.removeBlocker(transactionId); } void RocksDBMetaCollection::bufferUpdates( rocksdb::SequenceNumber seq, std::vector&& inserts, std::vector&& removals) { if (!_logicalCollection.useSyncByRevision()) { return; } TRI_ASSERT(!inserts.empty() || !removals.empty()); std::unique_lock guard(_revisionTreeLock); if (_revisionTreeApplied >= seq) { LOG_TOPIC(""1fe4d"", TRACE, Logger::ENGINES) << ""rejecting change with too low sequence number "" << seq << "" for collection "" << _logicalCollection.name(); TRI_ASSERT(_logicalCollection.vocbase() .server() .getFeature() .engine() .inRecovery()); return; } TRI_IF_FAILURE(""TransactionChaos::randomSleep"") { std::this_thread::sleep_for( std::chrono::milliseconds(RandomGenerator::interval(uint32_t(5)))); } LOG_TOPIC(""bafcf"", TRACE, Logger::ENGINES) << ""buffering "" << inserts.size() << ""inserts and "" << removals.size() << "" removals "" << ""for collection "" << _logicalCollection.name(); if (!inserts.empty()) { // will default-construct an empty entry if it does not yet exist TRI_ASSERT(_revisionInsertBuffers.find(seq) == _revisionInsertBuffers.end()); auto& elem = _revisionInsertBuffers[seq]; if (elem.empty()) { elem = std::move(inserts); } else { // should only happen in recovery, if at all TRI_ASSERT(_logicalCollection.vocbase() .server() .getFeature() .engine() .inRecovery()); elem.insert(elem.end(), inserts.begin(), inserts.end()); } } if (!removals.empty()) { // will default-construct an empty entry if it does not yet exist TRI_ASSERT(_revisionRemovalBuffers.find(seq) == _revisionRemovalBuffers.end()); auto& elem = _revisionRemovalBuffers[seq]; if (elem.empty()) { elem = std::move(removals); } else { // should only happen in recovery, if at all TRI_ASSERT(_logicalCollection.vocbase() .server() .getFeature() .engine() .inRecovery()); elem.insert(elem.end(), removals.begin(), removals.end()); } } } Result RocksDBMetaCollection::bufferTruncate(rocksdb::SequenceNumber seq) { if (!_logicalCollection.useSyncByRevision()) { return Result(); } Result res = basics::catchVoidToResult([&]() -> void { std::unique_lock guard(_revisionTreeLock); if (_revisionTreeApplied >= seq) { return; } _revisionTruncateBuffer.emplace(seq); }); return res; } void RocksDBMetaCollection::hibernateRevisionTree( std::unique_lock const& lock) { TRI_ASSERT(lock.owns_lock()); if (_revisionTree && !haveBufferedOperations(lock)) { _revisionTree->hibernate(/*force*/ false); } } void RocksDBMetaCollection::applyUpdates( rocksdb::SequenceNumber commitSeq, std::unique_lock const& lock) { TRI_ASSERT(lock.owns_lock()); TRI_ASSERT(_logicalCollection.useSyncByRevision()); TRI_ASSERT(_revisionTree || haveBufferedOperations(lock)); TRI_IF_FAILURE(""applyUpdates::forceHibernation1"") { if (_revisionTree != nullptr) { _revisionTree->hibernate(/*force*/ true); } } // make sure we will have a _revisionTree ready after this ensureRevisionTree(); TRI_ASSERT(_revisionTree != nullptr); TRI_ASSERT(_revisionTree->depth() == revisionTreeDepth); if (!_revisionTreeCanBeSerialized) { return; } auto oldMemoryUsage = _revisionTree->memoryUsage(); Result res = basics::catchVoidToResult([&]() -> void { // bump sequence number upwards auto bumpSequence = [this](rocksdb::SequenceNumber seq) noexcept { if (seq > _revisionTreeApplied) { _revisionTreeApplied = seq; } }; TRI_IF_FAILURE(""TransactionChaos::randomSleep"") { std::this_thread::sleep_for( std::chrono::milliseconds(RandomGenerator::interval(uint32_t(5)))); } auto insertIt = _revisionInsertBuffers.begin(); auto removeIt = _revisionRemovalBuffers.begin(); auto checkIterators = [&]() { TRI_ASSERT(insertIt == _revisionInsertBuffers.begin() || _revisionInsertBuffers.empty() || _revisionInsertBuffers.begin()->first > commitSeq); TRI_ASSERT(removeIt == _revisionRemovalBuffers.begin() || _revisionRemovalBuffers.empty() || _revisionRemovalBuffers.begin()->first > commitSeq); }; auto it = _revisionTruncateBuffer.begin(); // sorted ASC { // check for a truncate marker rocksdb::SequenceNumber ignoreSeq = 0; // truncate will increase this sequence bool foundTruncate = false; while (it != _revisionTruncateBuffer.end() && *it <= commitSeq) { ignoreSeq = *it; TRI_ASSERT(ignoreSeq > _revisionTreeApplied); TRI_ASSERT(ignoreSeq != 0); foundTruncate = true; it = _revisionTruncateBuffer.erase(it); } if (foundTruncate) { TRI_ASSERT(ignoreSeq <= commitSeq); while (insertIt != _revisionInsertBuffers.end() && insertIt->first <= ignoreSeq) { insertIt = _revisionInsertBuffers.erase(insertIt); } while (removeIt != _revisionRemovalBuffers.end() && removeIt->first <= ignoreSeq) { removeIt = _revisionRemovalBuffers.erase(removeIt); } checkIterators(); // clear out any revision structure, now empty _revisionTree->clear(); checkIterators(); // we have applied all changes up to here bumpSequence(ignoreSeq); } } // still holding the mutex here while (true) { checkIterators(); // find out if we still have buffers to apply bool haveInserts = insertIt != _revisionInsertBuffers.end() && insertIt->first <= commitSeq; bool haveRemovals = removeIt != _revisionRemovalBuffers.end() && removeIt->first <= commitSeq; bool applyInserts = haveInserts && (!haveRemovals || removeIt->first >= insertIt->first); bool applyRemovals = haveRemovals && !applyInserts; // no inserts or removals left to apply, drop out of loop if (!applyInserts && !applyRemovals) { // we have applied all changes up to including commitSeq TRI_IF_FAILURE(""TransactionChaos::randomSleep"") { std::this_thread::sleep_for(std::chrono::milliseconds( RandomGenerator::interval(uint32_t(5)))); } bumpSequence(commitSeq); return; } // another concurrent thread may insert new elements into // _revisionInsertBuffers or _revisionRemovalBuffers while we are here. it // is safe for us to access the elements pointed to by insertIt and // removeIt here without holding the lock on these containers though, // because of std::map's iterator invalidation rules: // - emplace / insert: No iterators or references are invalidated. // - erase: References and iterators to the erased elements are // invalidated. Other references and iterators are not affected. // check for inserts if (applyInserts) { TRI_ASSERT(!applyRemovals); TRI_IF_FAILURE(""RevisionTree::applyInserts"") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } TRI_ASSERT(insertIt->first > _revisionTreeApplied); // apply inserts, without holding the lock // if this throws we will not have modified _revisionInsertBuffers try { _revisionTree->insert(insertIt->second); } catch (std::exception const& ex) { LOG_TOPIC(""27811"", ERR, Logger::ENGINES) << ""unable to apply revision tree inserts for "" << _logicalCollection.vocbase().name() << ""/"" << _logicalCollection.name() << "": "" << ex.what(); // it is pretty bad if this fails, so we want to see it in our tests // and not overlook it. TRI_ASSERT(false); // if an exception escapes from here, the insert will not have // happened. it is safe to retry it next time. throw; } TRI_IF_FAILURE(""TransactionChaos::randomSleep"") { std::this_thread::sleep_for(std::chrono::milliseconds( RandomGenerator::interval(uint32_t(5)))); } // if the insert succeeded, we remove it from the list of operations, // so it won't be reapplied even if subsequent operations fail. insertIt = _revisionInsertBuffers.erase(insertIt); } // check for removals if (applyRemovals) { TRI_ASSERT(!applyInserts); TRI_ASSERT(removeIt->first > _revisionTreeApplied); TRI_IF_FAILURE(""RevisionTree::applyRemoves"") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } // apply removals, without holding the lock // if this throws we will not have modified _revisionRemovalBuffers try { _revisionTree->remove(removeIt->second); } catch (std::exception const& ex) { // this should never fail, anyway log... LOG_TOPIC(""a5ba8"", ERR, Logger::ENGINES) << ""unable to apply revision tree removals for "" << _logicalCollection.vocbase().name() << ""/"" << _logicalCollection.name() << "": "" << ex.what(); // it is pretty bad if this fails in real life, but we would trigger // this assertion during failure testing as well, so we cannot enable // it TRI_ASSERT(false); // if an exception escapes from here, the same remove will be retried // next time. throw; } TRI_IF_FAILURE(""TransactionChaos::randomSleep"") { std::this_thread::sleep_for(std::chrono::milliseconds( RandomGenerator::interval(uint32_t(5)))); } // if the remove succeeded, we remove it from the list of operations, // so it won't be reapplied even if subsequent operations fail. removeIt = _revisionRemovalBuffers.erase(removeIt); } } }); // if memory usage changed, track the adjustment auto newMemoryUsage = _revisionTree->memoryUsage(); if (oldMemoryUsage != newMemoryUsage) { auto& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); if (oldMemoryUsage > newMemoryUsage) { engine.trackRevisionTreeMemoryDecrease(oldMemoryUsage - newMemoryUsage); } else { engine.trackRevisionTreeMemoryIncrease(newMemoryUsage - oldMemoryUsage); } } if (res.fail()) { LOG_TOPIC(""fdfa7"", ERR, Logger::ENGINES) << ""unable to apply revision tree updates for "" << _logicalCollection.vocbase().name() << ""/"" << _logicalCollection.name() << "": "" << res.errorMessage(); THROW_ARANGO_EXCEPTION(res); } TRI_IF_FAILURE(""applyUpdates::forceHibernation2"") { if (_revisionTree != nullptr) { _revisionTree->hibernate(/*force*/ true); } } } Result RocksDBMetaCollection::applyUpdatesForTransaction( containers::RevisionTree& tree, rocksdb::SequenceNumber commitSeq, std::unique_lock& lock) const { TRI_ASSERT(lock.owns_lock()); TRI_ASSERT(_logicalCollection.useSyncByRevision()); return basics::catchVoidToResult([&]() -> void { auto insertIt = _revisionInsertBuffers.begin(); auto removeIt = _revisionRemovalBuffers.begin(); { rocksdb::SequenceNumber ignoreSeq = 0; // truncate will increase this sequence bool foundTruncate = false; // check for a truncate marker auto it = _revisionTruncateBuffer.begin(); // sorted ASC while (it != _revisionTruncateBuffer.end() && *it <= commitSeq) { ignoreSeq = *it; TRI_ASSERT(ignoreSeq != 0); foundTruncate = true; ++it; } if (foundTruncate) { TRI_ASSERT(ignoreSeq <= commitSeq); while (insertIt != _revisionInsertBuffers.end() && insertIt->first <= ignoreSeq) { ++insertIt; } while (removeIt != _revisionRemovalBuffers.end() && removeIt->first <= ignoreSeq) { ++removeIt; } tree.clear(); // clear estimates } } while (true) { std::vector const* inserts = nullptr; std::vector const* removals = nullptr; // find out if we have buffers to apply { bool haveInserts = insertIt != _revisionInsertBuffers.end() && insertIt->first <= commitSeq; bool haveRemovals = removeIt != _revisionRemovalBuffers.end() && removeIt->first <= commitSeq; bool applyInserts = haveInserts && (!haveRemovals || removeIt->first >= insertIt->first); bool applyRemovals = haveRemovals && !applyInserts; // check for inserts if (applyInserts) { inserts = &insertIt->second; ++insertIt; } // check for removals if (applyRemovals) { removals = &removeIt->second; ++removeIt; } } // no inserts or removals left to apply, drop out of loop if (!inserts && !removals) { break; } TRI_ASSERT(inserts == nullptr || removals == nullptr); // apply inserts if (inserts) { tree.insert(*inserts); } // apply removals if (removals) { tree.remove(*removals); } } }); } /// @brief lock a collection, with a timeout ErrorCode RocksDBMetaCollection::doLock(double timeout, AccessMode::Type mode) { uint64_t waitTime = 0; // indicates that time is uninitialized double startTime = 0.0; // user read operations don't require any lock in RocksDB, so we won't get // here. user write operations will acquire the R/W lock in read mode, and // user exclusive operations will acquire the R/W lock in write mode. TRI_ASSERT(mode == AccessMode::Type::READ || mode == AccessMode::Type::WRITE); while (true) { bool gotLock = false; if (mode == AccessMode::Type::WRITE) { gotLock = _exclusiveLock.tryLockWrite(); } else if (mode == AccessMode::Type::READ) { gotLock = _exclusiveLock.tryLockRead(); } else { // we should never get here TRI_ASSERT(false); return TRI_ERROR_INTERNAL; } if (gotLock) { // keep the lock and exit the loop return TRI_ERROR_NO_ERROR; } double now = TRI_microtime(); if (waitTime == 0) { // initialize times // set end time for lock waiting if (timeout <= 0.0) { timeout = defaultLockTimeout; } startTime = now; waitTime = 1; } else { TRI_ASSERT(startTime > 0.0); if (now > startTime + timeout) { LOG_TOPIC(""d1e52"", TRACE, arangodb::Logger::ENGINES) << ""timed out after "" << timeout << "" s waiting for "" << AccessMode::typeString(mode) << "" lock on collection '"" << _logicalCollection.name() << ""'""; return TRI_ERROR_LOCK_TIMEOUT; } } if (now - startTime < 0.001) { std::this_thread::yield(); } else { std::this_thread::sleep_for(std::chrono::microseconds(waitTime)); if (waitTime < 32) { waitTime *= 2; } } } } bool RocksDBMetaCollection::haveBufferedOperations( std::unique_lock const& lock) const { TRI_ASSERT(lock.owns_lock()); TRI_ASSERT(_logicalCollection.useSyncByRevision()); return (!_revisionTruncateBuffer.empty() || !_revisionInsertBuffers.empty() || !_revisionRemovalBuffers.empty()); } std::unique_ptr RocksDBMetaCollection::allocateEmptyRevisionTree(std::size_t depth) const { // determine the minimum revision id for the collection. // for smart edge collection children collections, the _rev values are // determined via the agency's uniqid() function. they can be anything, so we // need to assume 0 as the lower bound. for other collections, it is mostly // safe to assume that there will be no data inserted with non-recent // revisions. So a minRevision id that is relatively recent (HLC value from // January 2021) will mostly work for these cases. There are some exceptions // (e.g. some system collections are never dropped by the replication on the // follower but only truncated, which may lead to collections on the follower // being ""older"" than on the leader, plus because of DC2DC, which may insert // arbitrary data into a collection). For these special cases no current // minRevision value would do, but we would like to avoid using a value very // much in the past. thus we still go with a HLC from January 2021 and in // addition allow the minRevision to decrease in the revision trees. RevisionId minRevision = _logicalCollection.isSmartChild() ? RevisionId::none() : RevisionId::lowerBound(); return std::make_unique(depth, minRevision.id()); } void RocksDBMetaCollection::ensureRevisionTree() { // should have _revisionTreeLock held outside if (_revisionTree == nullptr) { auto& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); auto newTree = allocateEmptyRevisionTree(revisionTreeDepth); TRI_ASSERT(newTree->depth() == revisionTreeDepth); _revisionTree = std::make_unique(std::move(newTree), _logicalCollection); _revisionTreeCreationSeq = engine.db()->GetLatestSequenceNumber(); _revisionTreeSerializedSeq = _revisionTreeCreationSeq; _revisionTreeCanBeSerialized = true; LOG_TOPIC(""7630e"", TRACE, Logger::ENGINES) << ""created revision tree for "" << _logicalCollection.name() << "", sequence number: "" << _revisionTreeCreationSeq; } TRI_ASSERT(_revisionTree != nullptr); TRI_ASSERT(_revisionTree->depth() == revisionTreeDepth); } /// @brief construct from revision tree RocksDBMetaCollection::RevisionTreeAccessor::RevisionTreeAccessor( std::unique_ptr tree, LogicalCollection const& collection) : _tree(std::move(tree)), _logicalCollection(collection), _depth(_tree->depth()), _hibernationRequests(0), _compressible(true) { TRI_ASSERT(_depth == revisionTreeDepth); TRI_ASSERT(_tree != nullptr); auto& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); engine.trackRevisionTreeMemoryIncrease(_tree->memoryUsage()); } RocksDBMetaCollection::RevisionTreeAccessor::~RevisionTreeAccessor() { TRI_ASSERT((_tree == nullptr && !_compressed.empty()) || (_tree != nullptr && _compressed.empty())); auto& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); if (_tree != nullptr) { engine.trackRevisionTreeMemoryDecrease(_tree->memoryUsage()); } else if (!_compressed.empty()) { engine.trackRevisionTreeMemoryDecrease(_compressed.size()); } } void RocksDBMetaCollection::RevisionTreeAccessor::insert( std::vector const& keys) { ensureTree(); _tree->insert(keys); } void RocksDBMetaCollection::RevisionTreeAccessor::remove( std::vector const& keys) { ensureTree(); _tree->remove(keys); } void RocksDBMetaCollection::RevisionTreeAccessor::clear() { ensureTree(); // do not track memory usage here. the caller has to do this _tree->clear(); TRI_ASSERT(_tree->memoryUsage() == 0); _compressed.clear(); _compressible = true; TRI_ASSERT(_tree != nullptr && _compressed.empty()); } std::unique_ptr RocksDBMetaCollection::RevisionTreeAccessor::clone() const { ensureTree(); return _tree->clone(); } std::uint64_t RocksDBMetaCollection::RevisionTreeAccessor::compressedSize() const { if (_tree == nullptr) { TRI_ASSERT(!_compressed.empty()); return _compressed.size(); } std::string output; _tree->serializeBinary( output, arangodb::containers::MerkleTreeBase::BinaryFormat::Optimal); return output.size(); } std::uint64_t RocksDBMetaCollection::RevisionTreeAccessor::count() const { ensureTree(); return _tree->count(); } std::uint64_t RocksDBMetaCollection::RevisionTreeAccessor::rootValue() const { ensureTree(); return _tree->rootValue(); } std::uint64_t RocksDBMetaCollection::RevisionTreeAccessor::depth() const { return _depth; } std::size_t RocksDBMetaCollection::RevisionTreeAccessor::memoryUsage() const { ensureTree(); return _tree->memoryUsage(); } void RocksDBMetaCollection::RevisionTreeAccessor::checkConsistency() const { ensureTree(); return _tree->checkConsistency(); } #ifdef ARANGODB_ENABLE_FAILURE_TESTS void RocksDBMetaCollection::RevisionTreeAccessor::corrupt(uint64_t count, uint64_t hash) { ensureTree(); // track memory usage differences auto oldMemoryUsage = _tree->memoryUsage(); // corrupt will _insert_ intentionally broken data into the tree. it does not // _remove_ data _tree->corrupt(count, hash); RocksDBEngine& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); engine.trackRevisionTreeMemoryIncrease(_tree->memoryUsage() - oldMemoryUsage); } #endif void RocksDBMetaCollection::RevisionTreeAccessor::hibernate(bool force) { TRI_ASSERT((_tree == nullptr && !_compressed.empty()) || (_tree != nullptr && _compressed.empty())); if (_tree == nullptr) { // already compressed, nothing to do TRI_ASSERT(!_compressed.empty()); return; } TRI_ASSERT(_compressed.empty()); std::uint64_t count = _tree->count(); auto oldMemoryUsage = _tree->memoryUsage(); if (!force) { if (count >= 5'000'000) { // we have so many values in the tree that compressibility // will likely be bad return; } if (count >= 1'000'000 && !_compressible) { // for whatever reason this collection is not well compressible return; } if (oldMemoryUsage == 0) { // tree is empty -> we do not want to compress it! return; } if (++_hibernationRequests < 10) { // sit out the first few hibernation requests before we // actually work (10 is just an arbitrary value here to avoid // some pathologic hibernation/resurrection cycles, e.g. by // the statistics collections) return; } } double start = TRI_microtime(); _compressed.clear(); _tree->serializeBinary( _compressed, arangodb::containers::MerkleTreeBase::BinaryFormat::Optimal); TRI_ASSERT(!_compressed.empty()); LOG_TOPIC(""45eae"", DEBUG, Logger::REPLICATION) << ""hibernating revision tree for "" << _logicalCollection.vocbase().name() << ""/"" << _logicalCollection.name() << "" with "" << count << "" entries and size "" << _tree->byteSize() << "", hibernated size: "" << _compressed.size() << "", hibernation took: "" << (TRI_microtime() - start); // we would like to see at least 50% compressibility if (_compressed.size() * 2 < _tree->byteSize()) { // compression ratio ok. // remove tree from memory. now we only have _compressed RocksDBEngine& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); engine.trackRevisionTreeHibernation(); engine.trackRevisionTreeMemoryIncrease(_compressed.size()); engine.trackRevisionTreeMemoryDecrease(oldMemoryUsage); _tree.reset(); _compressible = true; TRI_ASSERT(_tree == nullptr && !_compressed.empty()); } else { // otherwise we'll keep the uncompressed tree, and will // not try compressing again soon _compressed = std::string(); _compressible = false; TRI_ASSERT(_tree != nullptr && _compressed.empty()); } } void RocksDBMetaCollection::RevisionTreeAccessor::serializeBinary( std::string& output) const { if (_tree != nullptr) { // compress tree into output _tree->serializeBinary( output, arangodb::containers::MerkleTreeBase::BinaryFormat::Optimal); } else { // append our already compressed state output.append(_compressed); } } // unfortunately we need to declare this method const although it can // modify internal (mutable) state void RocksDBMetaCollection::RevisionTreeAccessor::ensureTree() const { TRI_ASSERT((_tree == nullptr && !_compressed.empty()) || (_tree != nullptr && _compressed.empty())); if (_tree == nullptr) { // build tree from compressed state TRI_ASSERT(!_compressed.empty()); double start = TRI_microtime(); _tree = containers::RevisionTree::fromBuffer(std::string_view(_compressed)); if (_tree == nullptr) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, ""unable to uncompress tree""); } RocksDBEngine& engine = _logicalCollection.vocbase() .server() .getFeature() .engine(); engine.trackRevisionTreeResurrection(); engine.trackRevisionTreeMemoryIncrease(_tree->memoryUsage()); engine.trackRevisionTreeMemoryDecrease(_compressed.size()); // reset hibernation counter _hibernationRequests = 0; TRI_ASSERT(_tree->depth() == _depth); LOG_TOPIC(""e9c29"", DEBUG, Logger::REPLICATION) << ""resurrected revision tree for "" << _logicalCollection.vocbase().name() << ""/"" << _logicalCollection.name() << "" with "" << _tree->count() << "" entries. resurrection took: "" << (TRI_microtime() - start); // clear the compressed state and free the associated memory _compressed = std::string(); } TRI_ASSERT(_tree != nullptr); TRI_ASSERT(_compressed.empty()); } ",16357,True,3290.167785656267,median "= ProManage - Developer Guide :site-section: DeveloperGuide :toc: :toc-title: :toc-placement: preamble :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: endif::[] :repoURL: https://github.com/CS2113-AY1819S1-T16-2/main By: `T16-2`      Since: `September 2018`      Licence: `NUS` == Setting up === Prerequisites . *JDK `9`* or later + [WARNING] JDK `10` on Windows will fail to run tests in <> due to a https://github.com/javafxports/openjdk-jfx/issues/66[JavaFX bug]. Windows developers are highly recommended to use JDK `9`. . *IntelliJ* IDE + [NOTE] IntelliJ by default has Gradle and JavaFx plugins installed. + Do not disable them. If you have disabled them, go to `File` > `Settings` > `Plugins` to re-enable them. === Setting up the project in your computer . Fork this repo, and clone the fork to your computer . Open IntelliJ (if you are not in the welcome screen, click `File` > `Close Project` to close the existing project dialog first) . Set up the correct JDK version for Gradle .. Click `Configure` > `Project Defaults` > `Project Structure` .. Click `New...` and find the directory of the JDK . Click `Import Project` . Locate the `build.gradle` file and select it. Click `OK` . Click `Open as Project` . Click `OK` to accept the default settings . Open a console and run the command `gradlew processResources` (Mac/Linux: `./gradlew processResources`). It should finish with the `BUILD SUCCESSFUL` message. + This will generate all resources required by the application and tests. === Verifying the setup . Run the `seedu.address.MainApp` and try a few commands . <> to ensure they all pass. === Configurations to do before writing code ==== Configuring the coding style This project follows https://github.com/oss-generic/process/blob/master/docs/CodingStandards.adoc[oss-generic coding standards]. IntelliJ's default style is mostly compliant with ours but it uses a different import order from ours. To rectify, . Go to `File` > `Settings...` (Windows/Linux), or `IntelliJ IDEA` > `Preferences...` (macOS) . Select `Editor` > `Code Style` > `Java` . Click on the `Imports` tab to set the order * For `Class count to use import with '\\*'` and `Names count to use static import with '*'`: Set to `999` to prevent IntelliJ from contracting the import statements * For `Import Layout`: The order is `import static all other imports`, `import java.\\*`, `import javax.*`, `import org.\\*`, `import com.*`, `import all other imports`. Add a `` between each `import` Optionally, you can follow the <> document to configure Intellij to check style-compliance as you write code. ==== Updating documentation to match your fork After forking the repo, the documentation will still have the SE-EDU branding and refer to the `se-edu/addressbook-level4` repo. If you plan to develop this fork as a separate product (i.e. instead of contributing to `se-edu/addressbook-level4`), you should do the following: . Configure the <> in link:{repoURL}/build.gradle[`build.gradle`], such as the `site-name`, to suit your own project. . Replace the URL in the attribute `repoURL` in link:{repoURL}/docs/DeveloperGuide.adoc[`DeveloperGuide.adoc`] and link:{repoURL}/docs/UserGuide.adoc[`UserGuide.adoc`] with the URL of your fork. ==== Setting up CI Set up Travis to perform Continuous Integration (CI) for your fork. See <> to learn how to set it up. After setting up Travis, you can optionally set up coverage reporting for your team fork (see <>). [NOTE] Coverage reporting could be useful for a team repository that hosts the final version but it is not that useful for your personal fork. Optionally, you can set up AppVeyor as a second CI (see <>). [NOTE] Having both Travis and AppVeyor ensures your App works on both Unix-based platforms and Windows-based platforms (Travis is Unix-based and AppVeyor is Windows-based) ==== Getting started with coding When you are ready to start coding, 1. Get some sense of the overall design by reading <>. 2. Take a look at <>. == Design [[Design-Architecture]] === Architecture .Architecture Diagram image::Architecture.png[width=""600""] The *_Architecture Diagram_* given above explains the high-level design of the App. Given below is a quick overview of each component. [TIP] The `.pptx` files used to create diagrams in this document can be found in the link:{repoURL}/docs/diagrams/[diagrams] folder. To update a diagram, modify the diagram in the pptx file, select the objects of the diagram, and choose `Save as picture`. `Main` has only one class called link:{repoURL}/src/main/java/seedu/address/MainApp.java[`MainApp`]. It is responsible for, * At app launch: Initializes the components in the correct sequence, and connects them up with each other. * At shut down: Shuts down the components and invokes cleanup method where necessary. <> represents a collection of classes used by multiple other components. Two of those classes play important roles at the architecture level. * `EventsCenter` : This class (written using https://github.com/google/guava/wiki/EventBusExplained[Google's Event Bus library]) is used by components to communicate with other components using events (i.e. a form of _Event Driven_ design) * `LogsCenter` : Used by many classes to write log messages to the App's log file. The rest of the App consists of four components. * <>: The UI of the App. * <>: The command executor. * <>: Holds the data of the App in-memory. * <>: Reads data from, and writes data to, the hard disk. Each of the four components * Defines its _API_ in an `interface` with the same name as the Component. * Exposes its functionality using a `{Component Name}Manager` class. For example, the `Logic` component (see the class diagram given below) defines it's API in the `Logic.java` interface and exposes its functionality using the `LogicManager.java` class. .Class Diagram of the Logic Component image::LogicClassDiagram.png[width=""800""] [discrete] ==== Events-Driven nature of the design The _Sequence Diagram_ below shows how the components interact for the scenario where the user issues the command `delete 1`. .Component interactions for `delete 1` command (part 1) image::SDforDeletePerson.png[width=""800""] [NOTE] Note how the `Model` simply raises a `AddressBookChangedEvent` when the Address Book data are changed, instead of asking the `Storage` to save the updates to the hard disk. The diagram below shows how the `EventsCenter` reacts to that event, which eventually results in the updates being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time. .Component interactions for `delete 1` command (part 2) image::SDforDeletePersonEventHandling.png[width=""800""] [NOTE] Note how the event is propagated through the `EventsCenter` to the `Storage` and `UI` without `Model` having to be coupled to either of them. This is an example of how this Event Driven approach helps us reduce direct coupling between components. The sections below give more details of each component. [[Design-Ui]] === UI component .Structure of the UI Component image::UiClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/ui/Ui.java[`Ui.java`] The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay`, `PersonListPanel`, `StatusBarFooter`, `BrowserPanel` etc. All these, including the `MainWindow`, inherit from the abstract `UiPart` class. The `UI` component uses JavaFx UI framework. The layout of these UI parts are defined in matching `.fxml` files that are in the `src/main/resources/view` folder. For example, the layout of the link:{repoURL}/src/main/java/seedu/address/ui/MainWindow.java[`MainWindow`] is specified in link:{repoURL}/src/main/resources/view/MainWindow.fxml[`MainWindow.fxml`] The `UI` component, * Executes user commands using the `Logic` component. * Binds itself to some data in the `Model` so that the UI can auto-update when data in the `Model` change. * Responds to events raised from various parts of the App and updates the UI accordingly. [[Design-Logic]] === Logic component [[fig-LogicClassDiagram]] .Structure of the Logic Component image::LogicClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/logic/Logic.java[`Logic.java`] . `Logic` uses the `AddressBookParser` class to parse the user command. . This results in a `Command` object which is executed by the `LogicManager`. . The command execution can affect the `Model` (e.g. adding a person) and/or raise events. . The result of the command execution is encapsulated as a `CommandResult` object which is passed back to the `Ui`. Given below is the Sequence Diagram for interactions within the `Logic` component for the `execute(""delete 1"")` API call. .Interactions Inside the Logic Component for the `delete 1` Command image::DeletePersonSdForLogic.png[width=""800""] [[Design-Model]] === Model component .Structure of the Model Component image::ModelClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/model/Model.java[`Model.java`] The `Model`, * stores a `UserPref` object that represents the user's preferences. * stores the Address Book data. * exposes an unmodifiable `ObservableList` that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change. * does not depend on any of the other three components. [NOTE] As a more OOP model, we can store a `Tag` list in `Address Book`, which `Person` can reference. This would allow `Address Book` to only require one `Tag` object per unique `Tag`, instead of each `Person` needing their own `Tag` object. An example of how such a model may look like is given below. + + image:ModelClassBetterOopDiagram.png[width=""800""] [[Design-Storage]] === Storage component .Structure of the Storage Component image::StorageClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/storage/Storage.java[`Storage.java`] The `Storage` component, * can save `UserPref` objects in json format and read it back. * can save the Address Book data in xml format and read it back. [[Design-Commons]] === Common classes Classes used by multiple components are in the `seedu.addressbook.commons` package. == Implementation This section describes some noteworthy details on how certain features are implemented. // tag::undoredo[] === Undo/Redo feature ==== Current Implementation The undo/redo mechanism is facilitated by `VersionedAddressBook`. It extends `AddressBook` with an undo/redo history, stored internally as an `addressBookStateList` and `currentStatePointer`. Additionally, it implements the following operations: * `VersionedAddressBook#commit()` -- Saves the current address book state in its history. * `VersionedAddressBook#undo()` -- Restores the previous address book state from its history. * `VersionedAddressBook#redo()` -- Restores a previously undone address book state from its history. These operations are exposed in the `Model` interface as `Model#commitAddressBook()`, `Model#undoAddressBook()` and `Model#redoAddressBook()` respectively. Given below is an example usage scenario and how the undo/redo mechanism behaves at each step. Step 1. The user launches the application for the first time. The `VersionedAddressBook` will be initialized with the initial address book state, and the `currentStatePointer` pointing to that single address book state. image::UndoRedoStartingStateListDiagram.png[width=""800""] Step 2. The user executes `delete 5` command to delete the 5th person in the address book. The `delete` command calls `Model#commitAddressBook()`, causing the modified state of the address book after the `delete 5` command executes to be saved in the `addressBookStateList`, and the `currentStatePointer` is shifted to the newly inserted address book state. image::UndoRedoNewCommand1StateListDiagram.png[width=""800""] Step 3. The user executes `add n/David ...` to add a new person. The `add` command also calls `Model#commitAddressBook()`, causing another modified address book state to be saved into the `addressBookStateList`. image::UndoRedoNewCommand2StateListDiagram.png[width=""800""] [NOTE] If a command fails its execution, it will not call `Model#commitAddressBook()`, so the address book state will not be saved into the `addressBookStateList`. Step 4. The user now decides that adding the person was a mistake, and decides to undo that action by executing the `undo` command. The `undo` command will call `Model#undoAddressBook()`, which will shift the `currentStatePointer` once to the left, pointing it to the previous address book state, and restores the address book to that state. image::UndoRedoExecuteUndoStateListDiagram.png[width=""800""] [NOTE] If the `currentStatePointer` is at index 0, pointing to the initial address book state, then there are no previous address book states to restore. The `undo` command uses `Model#canUndoAddressBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the undo. The following sequence diagram shows how the undo operation works: image::UndoRedoSequenceDiagram.png[width=""800""] The `redo` command does the opposite -- it calls `Model#redoAddressBook()`, which shifts the `currentStatePointer` once to the right, pointing to the previously undone state, and restores the address book to that state. [NOTE] If the `currentStatePointer` is at index `addressBookStateList.size() - 1`, pointing to the latest address book state, then there are no undone address book states to restore. The `redo` command uses `Model#canRedoAddressBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the redo. Step 5. The user then decides to execute the command `list`. Commands that do not modify the address book, such as `list`, will usually not call `Model#commitAddressBook()`, `Model#undoAddressBook()` or `Model#redoAddressBook()`. Thus, the `addressBookStateList` remains unchanged. image::UndoRedoNewCommand3StateListDiagram.png[width=""800""] Step 6. The user executes `clear`, which calls `Model#commitAddressBook()`. Since the `currentStatePointer` is not pointing at the end of the `addressBookStateList`, all address book states after the `currentStatePointer` will be purged. We designed it this way because it no longer makes sense to redo the `add n/David ...` command. This is the behavior that most modern desktop applications follow. image::UndoRedoNewCommand4StateListDiagram.png[width=""800""] The following activity diagram summarizes what happens when a user executes a new command: image::UndoRedoActivityDiagram.png[width=""650""] ==== Design Considerations ===== Aspect: How undo & redo executes * **Alternative 1 (current choice):** Saves the entire address book. ** Pros: Easy to implement. ** Cons: May have performance issues in terms of memory usage. * **Alternative 2:** Individual command knows how to undo/redo by itself. ** Pros: Will use less memory (e.g. for `delete`, just save the person being deleted). ** Cons: We must ensure that the implementation of each individual command are correct. ===== Aspect: Data structure to support the undo/redo commands * **Alternative 1 (current choice):** Use a list to store the history of address book states. ** Pros: Easy for new Computer Science student undergraduates to understand, who are likely to be the new incoming developers of our project. ** Cons: Logic is duplicated twice. For example, when a new command is executed, we must remember to update both `HistoryManager` and `VersionedAddressBook`. * **Alternative 2:** Use `HistoryManager` for undo/redo ** Pros: We do not need to maintain a separate list, and just reuse what is already in the codebase. ** Cons: Requires dealing with commands that have already been undone: We must remember to skip these commands. Violates Single Responsibility Principle and Separation of Concerns as `HistoryManager` now needs to do two different things. // end::undoredo[] // tag::dataencryption[] === [Proposed] Data Encryption _{Explain here how the data encryption feature will be implemented}_ // end::dataencryption[] === Logging We are using `java.util.logging` package for logging. The `LogsCenter` class is used to manage the logging levels and logging destinations. * The logging level can be controlled using the `logLevel` setting in the configuration file (See <>) * The `Logger` for a class can be obtained using `LogsCenter.getLogger(Class)` which will log messages according to the specified logging level * Currently log messages are output through: `Console` and to a `.log` file. *Logging Levels* * `SEVERE` : Critical problem detected which may possibly cause the termination of the application * `WARNING` : Can continue, but with caution * `INFO` : Information showing the noteworthy actions by the App * `FINE` : Details that is not usually noteworthy but may be useful in debugging e.g. print the actual list instead of just its size [[Implementation-Configuration]] === Configuration Certain properties of the application can be controlled (e.g App name, logging level) through the configuration file (default: `config.json`). == Documentation We use asciidoc for writing documentation. [NOTE] We chose asciidoc over Markdown because asciidoc, although a bit more complex than Markdown, provides more flexibility in formatting. === Editing Documentation See <> to learn how to render `.adoc` files locally to preview the end result of your edits. Alternatively, you can download the AsciiDoc plugin for IntelliJ, which allows you to preview the changes you have made to your `.adoc` files in real-time. === Publishing Documentation See <> to learn how to deploy GitHub Pages using Travis. === Converting Documentation to PDF format We use https://www.google.com/chrome/browser/desktop/[Google Chrome] for converting documentation to PDF format, as Chrome's PDF engine preserves hyperlinks used in webpages. Here are the steps to convert the project documentation files to PDF format. . Follow the instructions in <> to convert the AsciiDoc files in the `docs/` directory to HTML format. . Go to your generated HTML files in the `build/docs` folder, right click on them and select `Open with` -> `Google Chrome`. . Within Chrome, click on the `Print` option in Chrome's menu. . Set the destination to `Save as PDF`, then click `Save` to save a copy of the file in PDF format. For best results, use the settings indicated in the screenshot below. .Saving documentation as PDF files in Chrome image::chrome_save_as_pdf.png[width=""300""] [[Docs-SiteWideDocSettings]] === Site-wide Documentation Settings The link:{repoURL}/build.gradle[`build.gradle`] file specifies some project-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how all documentation files within this project are rendered. [TIP] Attributes left unset in the `build.gradle` file will use their *default value*, if any. [cols=""1,2a,1"", options=""header""] .List of site-wide attributes |=== |Attribute name |Description |Default value |`site-name` |The name of the website. If set, the name will be displayed near the top of the page. |_not set_ |`site-githuburl` |URL to the site's repository on https://github.com[GitHub]. Setting this will add a ""View on GitHub"" link in the navigation bar. |_not set_ |`site-seedu` |Define this attribute if the project is an official SE-EDU project. This will render the SE-EDU navigation bar at the top of the page, and add some SE-EDU-specific navigation items. |_not set_ |=== [[Docs-PerFileDocSettings]] === Per-file Documentation Settings Each `.adoc` file may also specify some file-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how the file is rendered. Asciidoctor's https://asciidoctor.org/docs/user-manual/#builtin-attributes[built-in attributes] may be specified and used as well. [TIP] Attributes left unset in `.adoc` files will use their *default value*, if any. [cols=""1,2a,1"", options=""header""] .List of per-file attributes, excluding Asciidoctor's built-in attributes |=== |Attribute name |Description |Default value |`site-section` |Site section that the document belongs to. This will cause the associated item in the navigation bar to be highlighted. One of: `UserGuide`, `DeveloperGuide`, ``LearningOutcomes``{asterisk}, `AboutUs`, `ContactUs` _{asterisk} Official SE-EDU projects only_ |_not set_ |`no-site-header` |Set this attribute to remove the site navigation bar. |_not set_ |=== === Site Template The files in link:{repoURL}/docs/stylesheets[`docs/stylesheets`] are the https://developer.mozilla.org/en-US/docs/Web/CSS[CSS stylesheets] of the site. You can modify them to change some properties of the site's design. The files in link:{repoURL}/docs/templates[`docs/templates`] controls the rendering of `.adoc` files into HTML5. These template files are written in a mixture of https://www.ruby-lang.org[Ruby] and http://slim-lang.com[Slim]. [WARNING] ==== Modifying the template files in link:{repoURL}/docs/templates[`docs/templates`] requires some knowledge and experience with Ruby and Asciidoctor's API. You should only modify them if you need greater control over the site's layout than what stylesheets can provide. The SE-EDU team does not provide support for modified template files. ==== [[Testing]] == Testing === Running Tests There are three ways to run tests. [TIP] The most reliable way to run tests is the 3rd one. The first two methods might fail some GUI tests due to platform/resolution-specific idiosyncrasies. *Method 1: Using IntelliJ JUnit test runner* * To run all tests, right-click on the `src/test/java` folder and choose `Run 'All Tests'` * To run a subset of tests, you can right-click on a test package, test class, or a test and choose `Run 'ABC'` *Method 2: Using Gradle* * Open a console and run the command `gradlew clean allTests` (Mac/Linux: `./gradlew clean allTests`) [NOTE] See <> for more info on how to run tests using Gradle. *Method 3: Using Gradle (headless)* Thanks to the https://github.com/TestFX/TestFX[TestFX] library we use, our GUI tests can be run in the _headless_ mode. In the headless mode, GUI tests do not show up on the screen. That means the developer can do other things on the Computer while the tests are running. To run tests in headless mode, open a console and run the command `gradlew clean headless allTests` (Mac/Linux: `./gradlew clean headless allTests`) === Types of tests We have two types of tests: . *GUI Tests* - These are tests involving the GUI. They include, .. _System Tests_ that test the entire App by simulating user actions on the GUI. These are in the `systemtests` package. .. _Unit tests_ that test the individual components. These are in `seedu.address.ui` package. . *Non-GUI Tests* - These are tests not involving the GUI. They include, .. _Unit tests_ targeting the lowest level methods/classes. + e.g. `seedu.address.commons.StringUtilTest` .. _Integration tests_ that are checking the integration of multiple code units (those code units are assumed to be working). + e.g. `seedu.address.storage.StorageManagerTest` .. Hybrids of unit and integration tests. These test are checking multiple code units as well as how the are connected together. + e.g. `seedu.address.logic.LogicManagerTest` === Troubleshooting Testing **Problem: `HelpWindowTest` fails with a `NullPointerException`.** * Reason: One of its dependencies, `HelpWindow.html` in `src/main/resources/docs` is missing. * Solution: Execute Gradle task `processResources`. == Dev Ops === Build Automation See <> to learn how to use Gradle for build automation. === Continuous Integration We use https://travis-ci.org/[Travis CI] and https://www.appveyor.com/[AppVeyor] to perform _Continuous Integration_ on our projects. See <> and <> for more details. === Coverage Reporting We use https://coveralls.io/[Coveralls] to track the code coverage of our projects. See <> for more details. === Documentation Previews When a pull request has changes to asciidoc files, you can use https://www.netlify.com/[Netlify] to see a preview of how the HTML version of those asciidoc files will look like when the pull request is merged. See <> for more details. === Making a Release Here are the steps to create a new release. . Update the version number in link:{repoURL}/src/main/java/seedu/address/MainApp.java[`MainApp.java`]. . Generate a JAR file <>. . Tag the repo with the version number. e.g. `v0.1` . https://help.github.com/articles/creating-releases/[Create a new release using GitHub] and upload the JAR file you created. === Managing Dependencies A project often depends on third-party libraries. For example, Address Book depends on the http://wiki.fasterxml.com/JacksonHome[Jackson library] for XML parsing. Managing these _dependencies_ can be automated using Gradle. For example, Gradle can download the dependencies automatically, which is better than these alternatives. + a. Include those libraries in the repo (this bloats the repo size) + b. Require developers to download those libraries manually (this creates extra work for developers) [[GetStartedProgramming]] [appendix] == Suggested Programming Tasks to Get Started Suggested path for new programmers: 1. First, add small local-impact (i.e. the impact of the change does not go beyond the component) enhancements to one component at a time. Some suggestions are given in <>. 2. Next, add a feature that touches multiple components to learn how to implement an end-to-end feature across all components. <> explains how to go about adding such a feature. [[GetStartedProgramming-EachComponent]] === Improving each component Each individual exercise in this section is component-based (i.e. you would not need to modify the other components to get it to work). [discrete] ==== `Logic` component *Scenario:* You are in charge of `logic`. During dog-fooding, your team realize that it is troublesome for the user to type the whole command in order to execute a command. Your team devise some strategies to help cut down the amount of typing necessary, and one of the suggestions was to implement aliases for the command words. Your job is to implement such aliases. [TIP] Do take a look at <> before attempting to modify the `Logic` component. . Add a shorthand equivalent alias for each of the individual commands. For example, besides typing `clear`, the user can also type `c` to remove all persons in the list. + **** * Hints ** Just like we store each individual command word constant `COMMAND_WORD` inside `*Command.java` (e.g. link:{repoURL}/src/main/java/seedu/address/logic/commands/FindCommand.java[`FindCommand#COMMAND_WORD`], link:{repoURL}/src/main/java/seedu/address/logic/commands/DeleteCommand.java[`DeleteCommand#COMMAND_WORD`]), you need a new constant for aliases as well (e.g. `FindCommand#COMMAND_ALIAS`). ** link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] is responsible for analyzing command words. * Solution ** Modify the switch statement in link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser#parseCommand(String)`] such that both the proper command word and alias can be used to execute the same intended command. ** Add new tests for each of the aliases that you have added. ** Update the user guide to document the new aliases. ** See this https://github.com/se-edu/addressbook-level4/pull/785[PR] for the full solution. **** [discrete] ==== `Model` component *Scenario:* You are in charge of `model`. One day, the `logic`-in-charge approaches you for help. He wants to implement a command such that the user is able to remove a particular tag from everyone in the address book, but the model API does not support such a functionality at the moment. Your job is to implement an API method, so that your teammate can use your API to implement his command. [TIP] Do take a look at <> before attempting to modify the `Model` component. . Add a `removeTag(Tag)` method. The specified tag will be removed from everyone in the address book. + **** * Hints ** The link:{repoURL}/src/main/java/seedu/address/model/Model.java[`Model`] and the link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] API need to be updated. ** Think about how you can use SLAP to design the method. Where should we place the main logic of deleting tags? ** Find out which of the existing API methods in link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] and link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] classes can be used to implement the tag removal logic. link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] allows you to update a person, and link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] allows you to update the tags. * Solution ** Implement a `removeTag(Tag)` method in link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`]. Loop through each person, and remove the `tag` from each person. ** Add a new API method `deleteTag(Tag)` in link:{repoURL}/src/main/java/seedu/address/model/ModelManager.java[`ModelManager`]. Your link:{repoURL}/src/main/java/seedu/address/model/ModelManager.java[`ModelManager`] should call `AddressBook#removeTag(Tag)`. ** Add new tests for each of the new public methods that you have added. ** See this https://github.com/se-edu/addressbook-level4/pull/790[PR] for the full solution. **** [discrete] ==== `Ui` component *Scenario:* You are in charge of `ui`. During a beta testing session, your team is observing how the users use your address book application. You realize that one of the users occasionally tries to delete non-existent tags from a contact, because the tags all look the same visually, and the user got confused. Another user made a typing mistake in his command, but did not realize he had done so because the error message wasn't prominent enough. A third user keeps scrolling down the list, because he keeps forgetting the index of the last person in the list. Your job is to implement improvements to the UI to solve all these problems. [TIP] Do take a look at <> before attempting to modify the `UI` component. . Use different colors for different tags inside person cards. For example, `friends` tags can be all in brown, and `colleagues` tags can be all in yellow. + **Before** + image::getting-started-ui-tag-before.png[width=""300""] + **After** + image::getting-started-ui-tag-after.png[width=""300""] + **** * Hints ** The tag labels are created inside link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[the `PersonCard` constructor] (`new Label(tag.tagName)`). https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Label.html[JavaFX's `Label` class] allows you to modify the style of each Label, such as changing its color. ** Use the .css attribute `-fx-background-color` to add a color. ** You may wish to modify link:{repoURL}/src/main/resources/view/DarkTheme.css[`DarkTheme.css`] to include some pre-defined colors using css, especially if you have experience with web-based css. * Solution ** You can modify the existing test methods for `PersonCard` 's to include testing the tag's color as well. ** See this https://github.com/se-edu/addressbook-level4/pull/798[PR] for the full solution. *** The PR uses the hash code of the tag names to generate a color. This is deliberately designed to ensure consistent colors each time the application runs. You may wish to expand on this design to include additional features, such as allowing users to set their own tag colors, and directly saving the colors to storage, so that tags retain their colors even if the hash code algorithm changes. **** . Modify link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] such that link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay`] can show a different style on error (currently it shows the same regardless of errors). + **Before** + image::getting-started-ui-result-before.png[width=""200""] + **After** + image::getting-started-ui-result-after.png[width=""200""] + **** * Hints ** link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] is raised by link:{repoURL}/src/main/java/seedu/address/ui/CommandBox.java[`CommandBox`] which also knows whether the result is a success or failure, and is caught by link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay`] which is where we want to change the style to. ** Refer to link:{repoURL}/src/main/java/seedu/address/ui/CommandBox.java[`CommandBox`] for an example on how to display an error. * Solution ** Modify link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] 's constructor so that users of the event can indicate whether an error has occurred. ** Modify link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay#handleNewResultAvailableEvent(NewResultAvailableEvent)`] to react to this event appropriately. ** You can write two different kinds of tests to ensure that the functionality works: *** The unit tests for `ResultDisplay` can be modified to include verification of the color. *** The system tests link:{repoURL}/src/test/java/systemtests/AddressBookSystemTest.java[`AddressBookSystemTest#assertCommandBoxShowsDefaultStyle() and AddressBookSystemTest#assertCommandBoxShowsErrorStyle()`] to include verification for `ResultDisplay` as well. ** See this https://github.com/se-edu/addressbook-level4/pull/799[PR] for the full solution. *** Do read the commits one at a time if you feel overwhelmed. **** . Modify the link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] to show the total number of people in the address book. + **Before** + image::getting-started-ui-status-before.png[width=""500""] + **After** + image::getting-started-ui-status-after.png[width=""500""] + **** * Hints ** link:{repoURL}/src/main/resources/view/StatusBarFooter.fxml[`StatusBarFooter.fxml`] will need a new `StatusBar`. Be sure to set the `GridPane.columnIndex` properly for each `StatusBar` to avoid misalignment! ** link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] needs to initialize the status bar on application start, and to update it accordingly whenever the address book is updated. * Solution ** Modify the constructor of link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] to take in the number of persons when the application just started. ** Use link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter#handleAddressBookChangedEvent(AddressBookChangedEvent)`] to update the number of persons whenever there are new changes to the addressbook. ** For tests, modify link:{repoURL}/src/test/java/guitests/guihandles/StatusBarFooterHandle.java[`StatusBarFooterHandle`] by adding a state-saving functionality for the total number of people status, just like what we did for save location and sync status. ** For system tests, modify link:{repoURL}/src/test/java/systemtests/AddressBookSystemTest.java[`AddressBookSystemTest`] to also verify the new total number of persons status bar. ** See this https://github.com/se-edu/addressbook-level4/pull/803[PR] for the full solution. **** [discrete] ==== `Storage` component *Scenario:* You are in charge of `storage`. For your next project milestone, your team plans to implement a new feature of saving the address book to the cloud. However, the current implementation of the application constantly saves the address book after the execution of each command, which is not ideal if the user is working on limited internet connection. Your team decided that the application should instead save the changes to a temporary local backup file first, and only upload to the cloud after the user closes the application. Your job is to implement a backup API for the address book storage. [TIP] Do take a look at <> before attempting to modify the `Storage` component. . Add a new method `backupAddressBook(ReadOnlyAddressBook)`, so that the address book can be saved in a fixed temporary location. + **** * Hint ** Add the API method in link:{repoURL}/src/main/java/seedu/address/storage/AddressBookStorage.java[`AddressBookStorage`] interface. ** Implement the logic in link:{repoURL}/src/main/java/seedu/address/storage/StorageManager.java[`StorageManager`] and link:{repoURL}/src/main/java/seedu/address/storage/XmlAddressBookStorage.java[`XmlAddressBookStorage`] class. * Solution ** See this https://github.com/se-edu/addressbook-level4/pull/594[PR] for the full solution. **** [[GetStartedProgramming-RemarkCommand]] === Creating a new command: `remark` By creating this command, you will get a chance to learn how to implement a feature end-to-end, touching all major components of the app. *Scenario:* You are a software maintainer for `addressbook`, as the former developer team has moved on to new projects. The current users of your application have a list of new feature requests that they hope the software will eventually have. The most popular request is to allow adding additional comments/notes about a particular contact, by providing a flexible `remark` field for each contact, rather than relying on tags alone. After designing the specification for the `remark` command, you are convinced that this feature is worth implementing. Your job is to implement the `remark` command. ==== Description Edits the remark for a person specified in the `INDEX`. + Format: `remark INDEX r/[REMARK]` Examples: * `remark 1 r/Likes to drink coffee.` + Edits the remark for the first person to `Likes to drink coffee.` * `remark 1 r/` + Removes the remark for the first person. ==== Step-by-step Instructions ===== [Step 1] Logic: Teach the app to accept 'remark' which does nothing Let's start by teaching the application how to parse a `remark` command. We will add the logic of `remark` later. **Main:** . Add a `RemarkCommand` that extends link:{repoURL}/src/main/java/seedu/address/logic/commands/Command.java[`Command`]. Upon execution, it should just throw an `Exception`. . Modify link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] to accept a `RemarkCommand`. **Tests:** . Add `RemarkCommandTest` that tests that `execute()` throws an Exception. . Add new test method to link:{repoURL}/src/test/java/seedu/address/logic/parser/AddressBookParserTest.java[`AddressBookParserTest`], which tests that typing ""remark"" returns an instance of `RemarkCommand`. ===== [Step 2] Logic: Teach the app to accept 'remark' arguments Let's teach the application to parse arguments that our `remark` command will accept. E.g. `1 r/Likes to drink coffee.` **Main:** . Modify `RemarkCommand` to take in an `Index` and `String` and print those two parameters as the error message. . Add `RemarkCommandParser` that knows how to parse two arguments, one index and one with prefix 'r/'. . Modify link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] to use the newly implemented `RemarkCommandParser`. **Tests:** . Modify `RemarkCommandTest` to test the `RemarkCommand#equals()` method. . Add `RemarkCommandParserTest` that tests different boundary values for `RemarkCommandParser`. . Modify link:{repoURL}/src/test/java/seedu/address/logic/parser/AddressBookParserTest.java[`AddressBookParserTest`] to test that the correct command is generated according to the user input. ===== [Step 3] Ui: Add a placeholder for remark in `PersonCard` Let's add a placeholder on all our link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] s to display a remark for each person later. **Main:** . Add a `Label` with any random text inside link:{repoURL}/src/main/resources/view/PersonListCard.fxml[`PersonListCard.fxml`]. . Add FXML annotation in link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] to tie the variable to the actual label. **Tests:** . Modify link:{repoURL}/src/test/java/guitests/guihandles/PersonCardHandle.java[`PersonCardHandle`] so that future tests can read the contents of the remark label. ===== [Step 4] Model: Add `Remark` class We have to properly encapsulate the remark in our link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] class. Instead of just using a `String`, let's follow the conventional class structure that the codebase already uses by adding a `Remark` class. **Main:** . Add `Remark` to model component (you can copy from link:{repoURL}/src/main/java/seedu/address/model/person/Address.java[`Address`], remove the regex and change the names accordingly). . Modify `RemarkCommand` to now take in a `Remark` instead of a `String`. **Tests:** . Add test for `Remark`, to test the `Remark#equals()` method. ===== [Step 5] Model: Modify `Person` to support a `Remark` field Now we have the `Remark` class, we need to actually use it inside link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`]. **Main:** . Add `getRemark()` in link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`]. . You may assume that the user will not be able to use the `add` and `edit` commands to modify the remarks field (i.e. the person will be created without a remark). . Modify link:{repoURL}/src/main/java/seedu/address/model/util/SampleDataUtil.java/[`SampleDataUtil`] to add remarks for the sample data (delete your `addressBook.xml` so that the application will load the sample data when you launch it.) ===== [Step 6] Storage: Add `Remark` field to `XmlAdaptedPerson` class We now have `Remark` s for `Person` s, but they will be gone when we exit the application. Let's modify link:{repoURL}/src/main/java/seedu/address/storage/XmlAdaptedPerson.java[`XmlAdaptedPerson`] to include a `Remark` field so that it will be saved. **Main:** . Add a new Xml field for `Remark`. **Tests:** . Fix `invalidAndValidPersonAddressBook.xml`, `typicalPersonsAddressBook.xml`, `validAddressBook.xml` etc., such that the XML tests will not fail due to a missing `` element. ===== [Step 6b] Test: Add withRemark() for `PersonBuilder` Since `Person` can now have a `Remark`, we should add a helper method to link:{repoURL}/src/test/java/seedu/address/testutil/PersonBuilder.java[`PersonBuilder`], so that users are able to create remarks when building a link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`]. **Tests:** . Add a new method `withRemark()` for link:{repoURL}/src/test/java/seedu/address/testutil/PersonBuilder.java[`PersonBuilder`]. This method will create a new `Remark` for the person that it is currently building. . Try and use the method on any sample `Person` in link:{repoURL}/src/test/java/seedu/address/testutil/TypicalPersons.java[`TypicalPersons`]. ===== [Step 7] Ui: Connect `Remark` field to `PersonCard` Our remark label in link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] is still a placeholder. Let's bring it to life by binding it with the actual `remark` field. **Main:** . Modify link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`]'s constructor to bind the `Remark` field to the `Person` 's remark. **Tests:** . Modify link:{repoURL}/src/test/java/seedu/address/ui/testutil/GuiTestAssert.java[`GuiTestAssert#assertCardDisplaysPerson(...)`] so that it will compare the now-functioning remark label. ===== [Step 8] Logic: Implement `RemarkCommand#execute()` logic We now have everything set up... but we still can't modify the remarks. Let's finish it up by adding in actual logic for our `remark` command. **Main:** . Replace the logic in `RemarkCommand#execute()` (that currently just throws an `Exception`), with the actual logic to modify the remarks of a person. **Tests:** . Update `RemarkCommandTest` to test that the `execute()` logic works. ==== Full Solution See this https://github.com/se-edu/addressbook-level4/pull/599[PR] for the step-by-step solution. [appendix] == Product Scope *Target user profile*: * Companies have project management teams. Delegation of tasks and events can become complicated. * Project teams comprises of project managers, and the various sub branches : Admin, Logistics, Programmes, Publicity, Marketing and Safety. * This application aims to provide an all in one platform to ease the mode of task and event allocation. * prefer desktop apps over other types * can type fast * prefers typing over mouse input * is reasonably comfortable using CLI apps **Project Manager:** * In charge of overall project. * He/She has the autonomy to add/edit/view/delete all of the events and tasks of his/her employees. **Department Head:** * In charge of his/her department . * He/she has the autonomy to communicate with other department heads within the system. * He/she has the autonomy to add/edit/view/delete all of the events of his/her employees within the department. **Employees:** * He/she is only entitled to add/edit/view/delete all of the events of himself/herself within the department. *Value proposition*: * Facilitates workflow faster than a typical mouse/GUI driven app. * Saves consumers' efficiency, money and time tremendously. [appendix] == User Stories Priorities: High (must have) - `* * \\*`, Medium (nice to have) - `* \\*`, Low (unlikely to have) - `*` [width=""59%"",cols=""22%,<23%,<25%,<30%"",options=""header"",] |======================================================================= |Priority |As a ... |I want to ... |So that I can... |`* * *` |new user |see usage instructions |refer to instructions when I forget how to use the App |`* * *` |user |add a new person | |`* * *` |user |delete a person |remove entries that I no longer need |`* * *` |user |find a person by name |locate details of persons without having to go through the entire list |`* *` |user |hide <> by default |minimize chance of someone else seeing them by accident |`*` |user with many persons in the address book |sort persons by name |locate a person easily |======================================================================= _{More to be added}_ [appendix] == Use Cases (For all use cases below, the *System* is the `AddressBook` and the *Actor* is the `user`, unless specified otherwise) [discrete] === Use case: Delete person *MSS* 1. User requests to list persons 2. AddressBook shows a list of persons 3. User requests to delete a specific person in the list 4. AddressBook deletes the person + Use case ends. *Extensions* [none] * 2a. The list is empty. + Use case ends. * 3a. The given index is invalid. + [none] ** 3a1. AddressBook shows an error message. + Use case resumes at step 2. _{More to be added}_ [appendix] == Non Functional Requirements . Should work on any <> as long as it has Java `9` or higher installed. . Should be able to hold up to 1000 persons without a noticeable sluggishness in performance for typical usage. . A user with above average typing speed for regular English text (i.e. not code, not system admin commands) should be able to accomplish most of the tasks faster using commands than using the mouse. _{More to be added}_ [appendix] == Glossary [[mainstream-os]] Mainstream OS:: Windows, Linux, Unix, OS-X [[private-contact-detail]] Private contact detail:: A contact detail that is not meant to be shared with others [appendix] == Product Survey *Product Name* Author: ... Pros: * ... * ... Cons: * ... * ... [appendix] == Instructions for Manual Testing Given below are instructions to test the app manually. [NOTE] These instructions only provide a starting point for testers to work on; testers are expected to do more _exploratory_ testing. === Launch and Shutdown . Initial launch .. Download the jar file and copy into an empty folder .. Double-click the jar file + Expected: Shows the GUI with a set of sample contacts. The window size may not be optimum. . Saving window preferences .. Resize the window to an optimum size. Move the window to a different location. Close the window. .. Re-launch the app by double-clicking the jar file. + Expected: The most recent window size and location is retained. _{ more test cases ... }_ === Deleting a person . Deleting a person while all persons are listed .. Prerequisites: List all persons using the `list` command. Multiple persons in the list. .. Test case: `delete 1` + Expected: First contact is deleted from the list. Details of the deleted contact shown in the status message. Timestamp in the status bar is updated. .. Test case: `delete 0` + Expected: No person is deleted. Error details shown in the status message. Status bar remains the same. .. Other incorrect delete commands to try: `delete`, `delete x` (where x is larger than the list size) _{give more}_ + Expected: Similar to previous. _{ more test cases ... }_ === Saving data . Dealing with missing/corrupted data files .. _{explain how to simulate a missing/corrupted file and the expected behavior}_ _{ more test cases ... }_ ",12107,False,2053.895826281927,median "/********************************************************************** * * Name: mitab_miffile.cpp * Project: MapInfo TAB Read/Write library * Language: C++ * Purpose: Implementation of the MIDFile class. * To be used by external programs to handle reading/writing of * features from/to MID/MIF datasets. * Author: Stephane Villeneuve, stephane.v@videotron.ca * ********************************************************************** * Copyright (c) 1999-2003, Stephane Villeneuve * Copyright (c) 2011-2013, Even Rouault * Copyright (c) 2014, Even Rouault * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the ""Software""), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include ""cpl_port.h"" #include ""mitab.h"" #include #include #include #include #include #include ""cpl_conv.h"" #include ""cpl_error.h"" #include ""cpl_string.h"" #include ""mitab_priv.h"" #include ""mitab_utils.h"" #include ""ogr_core.h"" #include ""ogr_feature.h"" #include ""ogr_spatialref.h"" #include ""ogrsf_frmts.h"" CPL_CVSID(""$Id: mitab_miffile.cpp df398e80769422a4bbd5d4a295f4ede443c9fec6 2021-04-04 00:17:15 +0200 Even Rouault $"") /*===================================================================== * class MIFFile *====================================================================*/ /********************************************************************** * MIFFile::MIFFile() * * Constructor. **********************************************************************/ MIFFile::MIFFile() : m_pszFname(nullptr), m_eAccessMode(TABRead), m_nVersion(300), // Tab is default delimiter in MIF spec if not explicitly specified. Use // that by default for read mode. In write mode, we will use "","" as // delimiter since it is more common than tab (we do this in Open()) m_pszDelimiter(CPLStrdup(""\\t"")), m_pszUnique(nullptr), m_pszIndex(nullptr), m_pszCoordSys(nullptr), m_paeFieldType(nullptr), m_pabFieldIndexed(nullptr), m_pabFieldUnique(nullptr), m_dfXMultiplier(1.0), m_dfYMultiplier(1.0), m_dfXDisplacement(0.0), m_dfYDisplacement(0.0), m_dXMin(0), m_dYMin(0), m_dXMax(0), m_dYMax(0), m_bExtentsSet(FALSE), m_nPoints(0), m_nLines(0), m_nRegions(0), m_nTexts(0), m_nPreloadedId(0), m_poMIDFile(nullptr), m_poMIFFile(nullptr), m_poDefn(nullptr), m_poSpatialRef(nullptr), m_nFeatureCount(0), m_nWriteFeatureId(-1), m_nAttribute(0), m_bPreParsed(FALSE), m_bHeaderWrote(FALSE) { m_nCurFeatureId = 0; m_poCurFeature = nullptr; } /********************************************************************** * MIFFile::~MIFFile() * * Destructor. **********************************************************************/ MIFFile::~MIFFile() { MIFFile::Close(); } /********************************************************************** * MIFFile::Open() * * Returns 0 on success, -1 on error. **********************************************************************/ int MIFFile::Open(const char *pszFname, TABAccess eAccess, GBool bTestOpenNoError /*=FALSE*/, const char* pszCharset /* = NULL */ ) { char *pszTmpFname = nullptr; int nFnameLen = 0; CPLErrorReset(); if (m_poMIFFile) { CPLError(CE_Failure, CPLE_FileIO, ""Open() failed: object already contains an open file""); return -1; } /*----------------------------------------------------------------- * Validate access mode *----------------------------------------------------------------*/ const char* pszAccess = nullptr; if (eAccess == TABRead) { m_eAccessMode = TABRead; pszAccess = ""rt""; } else if (eAccess == TABWrite) { m_eAccessMode = TABWrite; pszAccess = ""wt""; // In write mode, use "","" as delimiter since it is more common than tab CPLFree(m_pszDelimiter); m_pszDelimiter = CPLStrdup("",""); } else { if (!bTestOpenNoError) CPLError(CE_Failure, CPLE_FileIO, ""Open() failed: access mode \\""%d\\"" not supported"", eAccess); else CPLErrorReset(); return -1; } /*----------------------------------------------------------------- * Make sure filename has a .MIF or .MID extension... *----------------------------------------------------------------*/ m_pszFname = CPLStrdup(pszFname); nFnameLen = static_cast(strlen(m_pszFname)); if (nFnameLen > 4 && (strcmp(m_pszFname+nFnameLen-4, "".MID"")==0 || strcmp(m_pszFname+nFnameLen-4, "".MIF"")==0 ) ) strcpy(m_pszFname+nFnameLen-4, "".MIF""); else if (nFnameLen > 4 && (EQUAL(m_pszFname+nFnameLen-4, "".mid"") || EQUAL(m_pszFname+nFnameLen-4, "".mif"") ) ) strcpy(m_pszFname+nFnameLen-4, "".mif""); else { if (!bTestOpenNoError) CPLError(CE_Failure, CPLE_FileIO, ""Open() failed for %s: invalid filename extension"", m_pszFname); else CPLErrorReset(); return -1; } pszTmpFname = CPLStrdup(m_pszFname); /*----------------------------------------------------------------- * Open .MIF file *----------------------------------------------------------------*/ #ifndef _WIN32 /*----------------------------------------------------------------- * On Unix, make sure extension uses the right cases * We do it even for write access because if a file with the same * extension already exists we want to overwrite it. *----------------------------------------------------------------*/ TABAdjustFilenameExtension(pszTmpFname); #endif m_poMIFFile = new MIDDATAFile(CharsetToEncoding(pszCharset)); if (m_poMIFFile->Open(pszTmpFname, pszAccess) != 0) { if (!bTestOpenNoError) CPLError(CE_Failure, CPLE_NotSupported, ""Unable to open %s."", pszTmpFname); else CPLErrorReset(); CPLFree(pszTmpFname); Close(); return -1; } /*----------------------------------------------------------------- * Read MIF File Header *----------------------------------------------------------------*/ int bIsEmpty = FALSE; if (m_eAccessMode == TABRead && ParseMIFHeader(&bIsEmpty) != 0) { Close(); if (!bTestOpenNoError) CPLError(CE_Failure, CPLE_NotSupported, ""Failed parsing header in %s."", m_pszFname); else CPLErrorReset(); CPLFree(pszTmpFname); return -1; } if ( m_nAttribute > 0 || m_eAccessMode == TABWrite ) { /*----------------------------------------------------------------- * Open .MID file *----------------------------------------------------------------*/ if (nFnameLen > 4 && strcmp(pszTmpFname+nFnameLen-4, "".MIF"")==0) strcpy(pszTmpFname+nFnameLen-4, "".MID""); else strcpy(pszTmpFname+nFnameLen-4, "".mid""); #ifndef _WIN32 TABAdjustFilenameExtension(pszTmpFname); #endif m_poMIDFile = new MIDDATAFile(""""); if(eAccess == TABRead || eAccess == TABReadWrite) { m_poMIDFile->SetEncoding( CharsetToEncoding(GetCharset()) ); } else if(eAccess == TABWrite) { m_poMIDFile->SetEncoding( CharsetToEncoding(pszCharset) ); } if (m_poMIDFile->Open(pszTmpFname, pszAccess) !=0) { if (m_eAccessMode == TABWrite) { if (!bTestOpenNoError) CPLError(CE_Failure, CPLE_NotSupported, ""Unable to open %s."", pszTmpFname); else CPLErrorReset(); CPLFree(pszTmpFname); Close(); return -1; } else { CPLDebug(""MITAB"", ""%s is not found, although %d attributes are declared"", pszTmpFname, m_nAttribute); delete m_poMIDFile; m_poMIDFile = nullptr; } } } CPLFree(pszTmpFname); pszTmpFname = nullptr; /*----------------------------------------------------------------- * In write access, set some defaults *----------------------------------------------------------------*/ if (m_eAccessMode == TABWrite) { m_nVersion = 300; if( pszCharset != nullptr ) SetCharset(pszCharset); else SetCharset(""Neutral""); } /* Put the MID file at the correct location, on the first feature */ if (m_eAccessMode == TABRead && (m_poMIDFile != nullptr && !bIsEmpty && m_poMIDFile->GetLine() == nullptr)) { Close(); if (bTestOpenNoError) CPLErrorReset(); return -1; } m_poMIFFile->SetTranslation(m_dfXMultiplier,m_dfYMultiplier, m_dfXDisplacement, m_dfYDisplacement); if( m_poMIDFile != nullptr ) m_poMIDFile->SetTranslation(m_dfXMultiplier,m_dfYMultiplier, m_dfXDisplacement, m_dfYDisplacement); m_poMIFFile->SetDelimiter(m_pszDelimiter); if( m_poMIDFile != nullptr ) m_poMIDFile->SetDelimiter(m_pszDelimiter); /*------------------------------------------------------------- * Set geometry type if the geometry objects are uniform. *------------------------------------------------------------*/ int numPoints=0, numRegions=0, numTexts=0, numLines=0; if( GetFeatureCountByType( numPoints, numLines, numRegions, numTexts, FALSE ) == 0 ) { numPoints += numTexts; if( numPoints > 0 && numLines == 0 && numRegions == 0 ) m_poDefn->SetGeomType( wkbPoint ); else if( numPoints == 0 && numLines > 0 && numRegions == 0 ) m_poDefn->SetGeomType( wkbLineString ); else { /* we leave it unknown indicating a mixture */ } } /* A newly created layer should have OGRFeatureDefn */ if (m_poDefn == nullptr) { char *pszFeatureClassName = TABGetBasename(m_pszFname); m_poDefn = new OGRFeatureDefn(pszFeatureClassName); CPLFree(pszFeatureClassName); // Ref count defaults to 0... set it to 1 m_poDefn->Reference(); } return 0; } /********************************************************************** * MIFFile::ParseMIFHeader() * * Scan the header of a MIF file, and store any useful information into * class members. The main piece of information being the fields * definition that we use to build the OGRFeatureDefn for this file. * * This private method should be used only during the Open() call. * * Returns 0 on success, -1 on error. **********************************************************************/ int MIFFile::ParseMIFHeader(int* pbIsEmpty) { *pbIsEmpty = FALSE; char *pszFeatureClassName = TABGetBasename(m_pszFname); m_poDefn = new OGRFeatureDefn(pszFeatureClassName); CPLFree(pszFeatureClassName); // Ref count defaults to 0... set it to 1 m_poDefn->Reference(); if (m_eAccessMode != TABRead) { CPLError(CE_Failure, CPLE_NotSupported, ""ParseMIDFile() can be used only with Read access.""); return -1; } /*----------------------------------------------------------------- * Parse header until we find the ""Data"" line *----------------------------------------------------------------*/ char **papszToken = nullptr; GBool bColumns = FALSE; GBool bAllColumnsRead = FALSE; int nColumns = 0; GBool bCoordSys = FALSE; CPLString osCoordSys; int nLineCount = 0; const char *pszLine = nullptr; while (((pszLine = m_poMIFFile->GetLine()) != nullptr) && ((bAllColumnsRead == FALSE) || !STARTS_WITH_CI(pszLine, ""Data""))) { nLineCount ++; if( nLineCount == 100000 ) { // Arbitrary threshold. The number of lines must be at least as big // as the number of fields we want to support. CPLError(CE_Failure, CPLE_NotSupported, ""Too many lines in MIF header""); return -1; } if (bColumns == TRUE && nColumns >0) { if (AddFields(pszLine) == 0) { nColumns--; if (nColumns == 0) { bAllColumnsRead = TRUE; bColumns = FALSE; } } else { bColumns = FALSE; } } else if (STARTS_WITH_CI(pszLine, ""VERSION"")) { papszToken = CSLTokenizeStringComplex(pszLine,"" ()\\t"",TRUE,FALSE); bColumns = FALSE; bCoordSys = FALSE; if (CSLCount(papszToken) == 2) m_nVersion = atoi(papszToken[1]); CSLDestroy(papszToken); } else if (STARTS_WITH_CI(pszLine, ""CHARSET"")) { papszToken = CSLTokenizeStringComplex(pszLine,"" ()\\t"",TRUE,FALSE); bColumns = FALSE; bCoordSys = FALSE; if (CSLCount(papszToken) == 2) { SetCharset(papszToken[1]); } CSLDestroy(papszToken); } else if (STARTS_WITH_CI(pszLine, ""DELIMITER"")) { papszToken = CSLTokenizeStringComplex(pszLine,"" ()\\t"",TRUE,FALSE); bColumns = FALSE; bCoordSys = FALSE; if (CSLCount(papszToken) == 2) { CPLFree(m_pszDelimiter); m_pszDelimiter = CPLStrdup(papszToken[1]); } CSLDestroy(papszToken); } else if (m_pszUnique == nullptr && STARTS_WITH_CI(pszLine, ""UNIQUE"")) { bColumns = FALSE; bCoordSys = FALSE; m_pszUnique = CPLStrdup(pszLine + 6); } else if (m_pszIndex == nullptr && STARTS_WITH_CI(pszLine, ""INDEX"")) { bColumns = FALSE; bCoordSys = FALSE; m_pszIndex = CPLStrdup(pszLine + 5); } else if (osCoordSys.empty() && STARTS_WITH_CI(pszLine, ""COORDSYS"") && CPLStrnlen(pszLine, 9) >= 9) { bCoordSys = TRUE; osCoordSys = pszLine + 9; } else if (STARTS_WITH_CI(pszLine, ""TRANSFORM"")) { papszToken = CSLTokenizeStringComplex(pszLine,"" ,\\t"",TRUE,FALSE); bColumns = FALSE; bCoordSys = FALSE; if (CSLCount(papszToken) == 5) { m_dfXMultiplier = CPLAtof(papszToken[1]); m_dfYMultiplier = CPLAtof(papszToken[2]); m_dfXDisplacement = CPLAtof(papszToken[3]); m_dfYDisplacement = CPLAtof(papszToken[4]); if (m_dfXMultiplier == 0.0) m_dfXMultiplier = 1.0; if (m_dfYMultiplier == 0.0) m_dfYMultiplier = 1.0; } CSLDestroy(papszToken); } else if (STARTS_WITH_CI(pszLine, ""COLUMNS"")) { papszToken = CSLTokenizeStringComplex(pszLine,"" ()\\t"",TRUE,FALSE); bCoordSys = FALSE; bColumns = TRUE; if (CSLCount(papszToken) == 2) { nColumns = atoi(papszToken[1]); m_nAttribute = nColumns; if (nColumns == 0) { // Permit to 0 columns bAllColumnsRead = TRUE; bColumns = FALSE; } } else { bColumns = FALSE; m_nAttribute = 0; } CSLDestroy(papszToken); } else if (bCoordSys == TRUE) { if( osCoordSys.size() > 10000 ) // Arbitrary threshold { CPLError(CE_Failure, CPLE_NotSupported, ""COORDSYS value too long""); return -1; } osCoordSys += ' '; osCoordSys += pszLine; } } if( !osCoordSys.empty() ) { m_pszCoordSys = CPLStrdup(osCoordSys); // Extract bounds if present char **papszFields = CSLTokenizeStringComplex(osCoordSys, "" ,()\\t"", TRUE, FALSE ); int iBounds = CSLFindString( papszFields, ""Bounds"" ); if (iBounds >= 0 && iBounds + 4 < CSLCount(papszFields)) { m_dXMin = CPLAtof(papszFields[++iBounds]); m_dYMin = CPLAtof(papszFields[++iBounds]); m_dXMax = CPLAtof(papszFields[++iBounds]); m_dYMax = CPLAtof(papszFields[++iBounds]); m_bBoundsSet = TRUE; } CSLDestroy( papszFields ); } if (!bAllColumnsRead) { CPLError(CE_Failure, CPLE_NotSupported, ""COLUMNS keyword not found or invalid number of columns read in %s. File may be corrupt."", m_pszFname); return -1; } if (m_poMIFFile->GetLastLine() == nullptr || STARTS_WITH_CI(m_poMIFFile->GetLastLine(), ""DATA"") == FALSE) { CPLError(CE_Failure, CPLE_NotSupported, ""DATA keyword not found in %s. File may be corrupt."", m_pszFname); return -1; } /*----------------------------------------------------------------- * Move pointer to first line of first object *----------------------------------------------------------------*/ while (((pszLine = m_poMIFFile->GetLine()) != nullptr) && m_poMIFFile->IsValidFeature(pszLine) == FALSE) ; *pbIsEmpty = (pszLine == nullptr); /*----------------------------------------------------------------- * Check for Unique and Indexed flags *----------------------------------------------------------------*/ if (m_pszIndex) { papszToken = CSLTokenizeStringComplex(m_pszIndex,"" ,\\t"",TRUE,FALSE); for(int i=0; papszToken && papszToken[i]; i++) { int nVal = atoi(papszToken[i]); if (nVal > 0 && nVal <= m_poDefn->GetFieldCount()) m_pabFieldIndexed[nVal-1] = TRUE; } CSLDestroy(papszToken); } if (m_pszUnique) { papszToken = CSLTokenizeStringComplex(m_pszUnique,"" ,\\t"",TRUE,FALSE); for(int i=0; papszToken && papszToken[i]; i++) { int nVal = atoi(papszToken[i]); if (nVal > 0 && nVal <= m_poDefn->GetFieldCount()) m_pabFieldUnique[nVal-1] = TRUE; } CSLDestroy(papszToken); } return 0; } /************************************************************************/ /* AddFields() */ /************************************************************************/ int MIFFile::AddFields(const char *pszLine) { int nStatus = 0; CPLAssert(m_bHeaderWrote == FALSE); char **papszToken = CSLTokenizeStringComplex(pszLine, "" (,)\\t"", TRUE, FALSE); int numTok = CSLCount(papszToken); CPLString osFieldName; if( numTok > 0 ) { osFieldName = papszToken[0]; if( strlen( GetEncoding() ) > 0 ) { osFieldName.Recode( GetEncoding(), CPL_ENC_UTF8 ); } } if (numTok >= 3 && EQUAL(papszToken[1], ""char"")) { /*------------------------------------------------- * CHAR type *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFChar, atoi(papszToken[2])); } else if (numTok >= 2 && EQUAL(papszToken[1], ""integer"")) { if (numTok == 2) { /*------------------------------------------------- * INTEGER type without a specified width *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFInteger); } else /* if (numTok > 2) */ { /*------------------------------------------------- * INTEGER type with a specified width *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFInteger, atoi(papszToken[2])); } } else if (numTok >= 2 && EQUAL(papszToken[1], ""smallint"")) { if (numTok == 2) { /*------------------------------------------------- * SMALLINT type without a specified width *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFSmallInt); } else /* if (numTok > 2) */ { /*------------------------------------------------- * SMALLINT type with a specified width *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFSmallInt, atoi(papszToken[2])); } } else if (numTok >= 4 && EQUAL(papszToken[1], ""decimal"")) { /*------------------------------------------------- * DECIMAL type *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFDecimal, atoi(papszToken[2]), atoi(papszToken[3])); } else if (numTok >= 2 && EQUAL(papszToken[1], ""float"")) { /*------------------------------------------------- * FLOAT type *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFFloat); } else if (numTok >= 2 && EQUAL(papszToken[1], ""date"")) { /*------------------------------------------------- * DATE type (returned as a string: ""DD/MM/YYYY"" or ""YYYYMMDD"") *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFDate); } else if (numTok >= 2 && EQUAL(papszToken[1], ""time"")) { /*------------------------------------------------- * TIME type (v900, returned as a string: ""HH:MM:SS"" or ""HHMMSSmmm"") *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFTime); } else if (numTok >= 2 && EQUAL(papszToken[1], ""datetime"")) { /*------------------------------------------------- * DATETIME type (v900, returned as a string: ""DD/MM/YYYY HH:MM:SS"", * ""YYYY/MM/DD HH:MM:SS"" or ""YYYYMMDDHHMMSSmmm"") *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFDateTime); } else if (numTok >= 2 && EQUAL(papszToken[1], ""logical"")) { /*------------------------------------------------- * LOGICAL type (value ""T"" or ""F"") *------------------------------------------------*/ nStatus = AddFieldNative(osFieldName, TABFLogical); } else nStatus = -1; // Unrecognized field type or line corrupt CSLDestroy(papszToken); papszToken = nullptr; if (nStatus != 0) { CPLError(CE_Failure, CPLE_FileIO, ""Failed to parse field definition in file %s"", m_pszFname); return -1; } return 0; } /************************************************************************/ /* GetFeatureCount() */ /************************************************************************/ GIntBig MIFFile::GetFeatureCount (int bForce) { if( m_poFilterGeom != nullptr || m_poAttrQuery != nullptr ) return OGRLayer::GetFeatureCount( bForce ); else { if (bForce == TRUE) PreParseFile(); if (m_bPreParsed) return m_nFeatureCount; else return -1; } } /************************************************************************/ /* ResetReading() */ /************************************************************************/ void MIFFile::ResetReading() { m_poMIFFile->Rewind(); const char *pszLine = nullptr; while ((pszLine = m_poMIFFile->GetLine()) != nullptr) if (STARTS_WITH_CI(pszLine, ""DATA"")) break; while ((pszLine = m_poMIFFile->GetLine()) != nullptr) { if (m_poMIFFile->IsValidFeature(pszLine)) break; } if( m_poMIDFile != nullptr ) { m_poMIDFile->Rewind(); m_poMIDFile->GetLine(); } // We're positioned on first feature. Feature Ids start at 1. if (m_poCurFeature) { delete m_poCurFeature; m_poCurFeature = nullptr; } m_nCurFeatureId = 0; m_nPreloadedId = 1; } /************************************************************************/ /* PreParseFile() */ /************************************************************************/ void MIFFile::PreParseFile() { char **papszToken = nullptr; GBool bPLine = FALSE; GBool bText = FALSE; if (m_bPreParsed == TRUE) return; m_poMIFFile->Rewind(); const char *pszLine = nullptr; while ((pszLine = m_poMIFFile->GetLine()) != nullptr) if (STARTS_WITH_CI(pszLine, ""DATA"")) break; m_nPoints = m_nLines = m_nRegions = m_nTexts = 0; while ((pszLine = m_poMIFFile->GetLine()) != nullptr) { if (m_poMIFFile->IsValidFeature(pszLine)) { bPLine = FALSE; bText = FALSE; m_nFeatureCount++; } CSLDestroy(papszToken); papszToken = CSLTokenizeString2(pszLine, "" \\t"", CSLT_HONOURSTRINGS); if (STARTS_WITH_CI(pszLine, ""POINT"")) { m_nPoints++; if (CSLCount(papszToken) == 3) { UpdateExtents(m_poMIFFile->GetXTrans(CPLAtof(papszToken[1])), m_poMIFFile->GetYTrans(CPLAtof(papszToken[2]))); } } else if (STARTS_WITH_CI(pszLine, ""LINE"") || STARTS_WITH_CI(pszLine, ""RECT"") || STARTS_WITH_CI(pszLine, ""ROUNDRECT"") || STARTS_WITH_CI(pszLine, ""ARC"") || STARTS_WITH_CI(pszLine, ""ELLIPSE"")) { if (CSLCount(papszToken) == 5) { m_nLines++; UpdateExtents(m_poMIFFile->GetXTrans(CPLAtof(papszToken[1])), m_poMIFFile->GetYTrans(CPLAtof(papszToken[2]))); UpdateExtents(m_poMIFFile->GetXTrans(CPLAtof(papszToken[3])), m_poMIFFile->GetYTrans(CPLAtof(papszToken[4]))); } } else if (STARTS_WITH_CI(pszLine, ""REGION"") ) { m_nRegions++; bPLine = TRUE; } else if( STARTS_WITH_CI(pszLine, ""PLINE"")) { m_nLines++; bPLine = TRUE; } else if (STARTS_WITH_CI(pszLine, ""TEXT"")) { m_nTexts++; bText = TRUE; } else if (bPLine == TRUE) { if (CSLCount(papszToken) == 2 && strchr(""-.0123456789"", papszToken[0][0]) != nullptr) { UpdateExtents( m_poMIFFile->GetXTrans(CPLAtof(papszToken[0])), m_poMIFFile->GetYTrans(CPLAtof(papszToken[1]))); } } else if (bText == TRUE) { if (CSLCount(papszToken) == 4 && strchr(""-.0123456789"", papszToken[0][0]) != nullptr) { UpdateExtents(m_poMIFFile->GetXTrans(CPLAtof(papszToken[0])), m_poMIFFile->GetYTrans(CPLAtof(papszToken[1]))); UpdateExtents(m_poMIFFile->GetXTrans(CPLAtof(papszToken[2])), m_poMIFFile->GetYTrans(CPLAtof(papszToken[3]))); } } } CSLDestroy(papszToken); m_poMIFFile->Rewind(); while ((pszLine = m_poMIFFile->GetLine()) != nullptr) if (STARTS_WITH_CI(pszLine, ""DATA"")) break; while ((pszLine = m_poMIFFile->GetLine()) != nullptr) { if (m_poMIFFile->IsValidFeature(pszLine)) break; } if( m_poMIDFile != nullptr ) { m_poMIDFile->Rewind(); m_poMIDFile->GetLine(); } m_bPreParsed = TRUE; } /********************************************************************** * MIFFile::WriteMIFHeader() * * Generate the .MIF header. * * Returns 0 on success, -1 on error. **********************************************************************/ int MIFFile::WriteMIFHeader() { GBool bFound; if (m_eAccessMode != TABWrite) { CPLError(CE_Failure, CPLE_NotSupported, ""WriteMIFHeader() can be used only with Write access.""); return -1; } if (m_poDefn==nullptr || m_poDefn->GetFieldCount() == 0) { CPLError(CE_Failure, CPLE_NotSupported, ""File %s must contain at least 1 attribute field."", m_pszFname); return -1; } /*----------------------------------------------------------------- * Start writing header. *----------------------------------------------------------------*/ m_bHeaderWrote = TRUE; m_poMIFFile->WriteLine(""Version %d\\n"", m_nVersion); m_poMIFFile->WriteLine(""Charset \\""%s\\""\\n"", m_pszCharset); // Delimiter is not required if you use \\t as delimiter if ( !EQUAL(m_pszDelimiter, ""\\t"") ) m_poMIFFile->WriteLine(""Delimiter \\""%s\\""\\n"", m_pszDelimiter); bFound = FALSE; for( int iField = 0; iFieldGetFieldCount(); iField++ ) { if (m_pabFieldUnique[iField]) { if (!bFound) m_poMIFFile->WriteLine(""Unique %d"", iField+1); else m_poMIFFile->WriteLine("",%d"", iField+1); bFound = TRUE; } } if (bFound) m_poMIFFile->WriteLine(""\\n""); bFound = FALSE; for( int iField = 0; iField < m_poDefn->GetFieldCount(); iField++ ) { if (m_pabFieldIndexed[iField]) { if (!bFound) m_poMIFFile->WriteLine(""Index %d"", iField+1); else m_poMIFFile->WriteLine("",%d"", iField+1); bFound = TRUE; } } if (bFound) m_poMIFFile->WriteLine(""\\n""); if (m_pszCoordSys && m_bBoundsSet) { m_poMIFFile->WriteLine(""CoordSys %s "" ""Bounds (%.15g, %.15g) (%.15g, %.15g)\\n"", m_pszCoordSys, m_dXMin, m_dYMin, m_dXMax, m_dYMax); } else if (m_pszCoordSys) { m_poMIFFile->WriteLine(""CoordSys %s\\n"",m_pszCoordSys); } /*----------------------------------------------------------------- * Column definitions *----------------------------------------------------------------*/ CPLAssert(m_paeFieldType); m_poMIFFile->WriteLine(""Columns %d\\n"", m_poDefn->GetFieldCount()); for( int iField = 0; iField < m_poDefn->GetFieldCount(); iField++ ) { OGRFieldDefn *poFieldDefn = m_poDefn->GetFieldDefn(iField); CPLString osFieldName( poFieldDefn->GetNameRef() ); if( strlen( GetEncoding() ) > 0 ) osFieldName.Recode( CPL_ENC_UTF8, GetEncoding() ); char* pszCleanName = TABCleanFieldName( osFieldName ); osFieldName = pszCleanName; CPLFree( pszCleanName ); switch(m_paeFieldType[iField]) { case TABFInteger: m_poMIFFile->WriteLine("" %s Integer\\n"", osFieldName.c_str() ); break; case TABFSmallInt: m_poMIFFile->WriteLine("" %s SmallInt\\n"", osFieldName.c_str() ); break; case TABFFloat: m_poMIFFile->WriteLine("" %s Float\\n"", osFieldName.c_str() ); break; case TABFDecimal: m_poMIFFile->WriteLine("" %s Decimal(%d,%d)\\n"", osFieldName.c_str(), poFieldDefn->GetWidth(), poFieldDefn->GetPrecision()); break; case TABFLogical: m_poMIFFile->WriteLine("" %s Logical\\n"", osFieldName.c_str() ); break; case TABFDate: m_poMIFFile->WriteLine("" %s Date\\n"", osFieldName.c_str() ); break; case TABFTime: m_poMIFFile->WriteLine("" %s Time\\n"", osFieldName.c_str() ); break; case TABFDateTime: m_poMIFFile->WriteLine("" %s DateTime\\n"", osFieldName.c_str() ); break; case TABFChar: default: m_poMIFFile->WriteLine("" %s Char(%d)\\n"", osFieldName.c_str(), poFieldDefn->GetWidth()); } } /*----------------------------------------------------------------- * Ready to write objects *----------------------------------------------------------------*/ m_poMIFFile->WriteLine(""Data\\n\\n""); return 0; } /********************************************************************** * MIFFile::Close() * * Close current file, and release all memory used. * * Returns 0 on success, -1 on error. **********************************************************************/ int MIFFile::Close() { /* flush .mif header if not already written */ if ( m_poDefn != nullptr && m_bHeaderWrote == FALSE && m_eAccessMode != TABRead ) { WriteMIFHeader(); } if (m_poMIDFile) { m_poMIDFile->Close(); delete m_poMIDFile; m_poMIDFile = nullptr; } if (m_poMIFFile) { m_poMIFFile->Close(); delete m_poMIFFile; m_poMIFFile = nullptr; } if (m_poCurFeature) { delete m_poCurFeature; m_poCurFeature = nullptr; } /*----------------------------------------------------------------- * Note: we have to check the reference count before deleting * m_poSpatialRef and m_poDefn *----------------------------------------------------------------*/ if (m_poDefn && m_poDefn->Dereference() == 0) delete m_poDefn; m_poDefn = nullptr; if (m_poSpatialRef && m_poSpatialRef->Dereference() == 0) delete m_poSpatialRef; m_poSpatialRef = nullptr; CPLFree(m_pszCoordSys); m_pszCoordSys = nullptr; CPLFree(m_pszDelimiter); m_pszDelimiter = nullptr; CPLFree(m_pszUnique); m_pszUnique = nullptr; CPLFree(m_pszFname); m_pszFname = nullptr; m_nVersion = 0; CPLFree(m_pszCharset); m_pszCharset = nullptr; CPLFree(m_pabFieldIndexed); m_pabFieldIndexed = nullptr; CPLFree(m_pabFieldUnique); m_pabFieldUnique = nullptr; CPLFree( m_pszIndex ); m_pszIndex = nullptr; CPLFree(m_paeFieldType); m_paeFieldType = nullptr; m_nCurFeatureId = 0; m_nPreloadedId = 0; m_nFeatureCount =0; m_bBoundsSet = FALSE; return 0; } /********************************************************************** * MIFFile::GetNextFeatureId() * * Returns feature id that follows nPrevId, or -1 if it is the * last feature id. Pass nPrevId=-1 to fetch the first valid feature id. **********************************************************************/ GIntBig MIFFile::GetNextFeatureId(GIntBig nPrevId) { if (m_eAccessMode != TABRead) { CPLError(CE_Failure, CPLE_NotSupported, ""GetNextFeatureId() can be used only with Read access.""); return -1; } if (nPrevId <= 0 && m_poMIFFile->GetLastLine() != nullptr) return 1; // Feature Ids start at 1 else if (nPrevId > 0 && m_poMIFFile->GetLastLine() != nullptr) return nPrevId + 1; else return -1; } /********************************************************************** * MIFFile::GotoFeature() * * Private method to move MIF and MID pointers ready to read specified * feature. Note that Feature Ids start at 1. * * Returns 0 on success, -1 on error (likely request for invalid feature id) **********************************************************************/ int MIFFile::GotoFeature(int nFeatureId) { if (nFeatureId < 1) return -1; if (nFeatureId == m_nPreloadedId) // CorrectPosition { return 0; } else { if (nFeatureId < m_nPreloadedId || m_nCurFeatureId == 0) ResetReading(); while(m_nPreloadedId < nFeatureId) { if (NextFeature() == FALSE) return -1; } CPLAssert(m_nPreloadedId == nFeatureId); return 0; } } /********************************************************************** * MIFFile::NextFeature() **********************************************************************/ GBool MIFFile::NextFeature() { const char *pszLine = nullptr; while ((pszLine = m_poMIFFile->GetLine()) != nullptr) { if (m_poMIFFile->IsValidFeature(pszLine)) { if( m_poMIDFile != nullptr ) m_poMIDFile->GetLine(); m_nPreloadedId++; return TRUE; } } return FALSE; } /********************************************************************** * MIFFile::GetFeatureRef() * * Fill and return a TABFeature object for the specified feature id. * * The returned pointer is a reference to an object owned and maintained * by this MIFFile object. It should not be altered or freed by the * caller and its contents is guaranteed to be valid only until the next * call to GetFeatureRef() or Close(). * * Returns NULL if the specified feature id does not exist of if an * error happened. In any case, CPLError() will have been called to * report the reason of the failure. **********************************************************************/ TABFeature *MIFFile::GetFeatureRef(GIntBig nFeatureId) { if (m_eAccessMode != TABRead) { CPLError(CE_Failure, CPLE_NotSupported, ""GetFeatureRef() can be used only with Read access.""); return nullptr; } /*----------------------------------------------------------------- * Make sure file is opened and Validate feature id by positioning * the read pointers for the .MAP and .DAT files to this feature id. *----------------------------------------------------------------*/ if (m_poMIFFile == nullptr) { CPLError(CE_Failure, CPLE_IllegalArg, ""GetFeatureRef() failed: file is not opened!""); return nullptr; } if ( !CPL_INT64_FITS_ON_INT32(nFeatureId) || GotoFeature(static_cast(nFeatureId))!= 0 ) { CPLError(CE_Failure, CPLE_IllegalArg, ""GetFeatureRef() failed: invalid feature id "" CPL_FRMT_GIB, nFeatureId); return nullptr; } /*----------------------------------------------------------------- * Create new feature object of the right type *----------------------------------------------------------------*/ const char *pszLine = nullptr; if ((pszLine = m_poMIFFile->GetLastLine()) != nullptr) { // Delete previous feature... we'll start we a clean one. if (m_poCurFeature) delete m_poCurFeature; m_poCurFeature = nullptr; m_nCurFeatureId = m_nPreloadedId; if (STARTS_WITH_CI(pszLine, ""NONE"")) { m_poCurFeature = new TABFeature(m_poDefn); } else if (STARTS_WITH_CI(pszLine, ""POINT"")) { // Special case, we need to know two lines to decide the type char **papszToken = CSLTokenizeString2(pszLine, "" \\t"", CSLT_HONOURSTRINGS); if (CSLCount(papszToken) !=3) { CSLDestroy(papszToken); CPLError(CE_Failure, CPLE_NotSupported, ""GetFeatureRef() failed: invalid point line: '%s'"", pszLine); return nullptr; } m_poMIFFile->SaveLine(pszLine); if ((pszLine = m_poMIFFile->GetLine()) != nullptr) { CSLDestroy(papszToken); papszToken = CSLTokenizeStringComplex(pszLine,"" ,()\\t"", TRUE,FALSE); if (CSLCount(papszToken)> 0 &&STARTS_WITH_CI(papszToken[0], ""SYMBOL"")) { switch (CSLCount(papszToken)) { case 4: m_poCurFeature = new TABPoint(m_poDefn); break; case 7: m_poCurFeature = new TABFontPoint(m_poDefn); break; case 5: m_poCurFeature = new TABCustomPoint(m_poDefn); break; default: CSLDestroy(papszToken); CPLError(CE_Failure, CPLE_NotSupported, ""GetFeatureRef() failed: invalid symbol "" ""line: '%s'"", pszLine); return nullptr; break; } } } CSLDestroy(papszToken); if (m_poCurFeature == nullptr) { // No symbol clause... default to TABPoint m_poCurFeature = new TABPoint(m_poDefn); } } else if (STARTS_WITH_CI(pszLine, ""LINE"") || STARTS_WITH_CI(pszLine, ""PLINE"")) { m_poCurFeature = new TABPolyline(m_poDefn); } else if (STARTS_WITH_CI(pszLine, ""REGION"")) { m_poCurFeature = new TABRegion(m_poDefn); } else if (STARTS_WITH_CI(pszLine, ""ARC"")) { m_poCurFeature = new TABArc(m_poDefn); } else if (STARTS_WITH_CI(pszLine, ""TEXT"")) { m_poCurFeature = new TABText(m_poDefn); } else if (STARTS_WITH_CI(pszLine, ""RECT"") || STARTS_WITH_CI(pszLine, ""ROUNDRECT"")) { m_poCurFeature = new TABRectangle(m_poDefn); } else if (STARTS_WITH_CI(pszLine, ""ELLIPSE"")) { m_poCurFeature = new TABEllipse(m_poDefn); } else if (STARTS_WITH_CI(pszLine, ""MULTIPOINT"")) { m_poCurFeature = new TABMultiPoint(m_poDefn); } else if (STARTS_WITH_CI(pszLine, ""COLLECTION"")) { m_poCurFeature = new TABCollection(m_poDefn); } else { if (!EQUAL(pszLine,"""")) CPLError(CE_Failure, CPLE_NotSupported, ""Error during reading, unknown type %s."", pszLine); //m_poCurFeature = new TABDebugFeature(m_poDefn); return nullptr; } } CPLAssert(m_poCurFeature); if (m_poCurFeature == nullptr) return nullptr; /*----------------------------------------------------------------- * Read fields from the .DAT file * GetRecordBlock() has already been called above... *----------------------------------------------------------------*/ if (m_poMIDFile != nullptr && m_poCurFeature->ReadRecordFromMIDFile(m_poMIDFile) != 0) { CPLError(CE_Failure, CPLE_NotSupported, ""Error during reading Record.""); delete m_poCurFeature; m_poCurFeature = nullptr; return nullptr; } /*----------------------------------------------------------------- * Read geometry from the .MAP file * MoveToObjId() has already been called above... *----------------------------------------------------------------*/ if (m_poCurFeature->ReadGeometryFromMIFFile(m_poMIFFile) != 0) { CPLError(CE_Failure, CPLE_NotSupported, ""Error during reading Geometry.""); delete m_poCurFeature; m_poCurFeature = nullptr; return nullptr; } /* If the feature geometry is Text, and the value is empty(""""), transform it to a geometry none */ if (m_poCurFeature->GetFeatureClass() == TABFCText) { TABText *poTextFeature = cpl::down_cast(m_poCurFeature); if (strlen(poTextFeature->GetTextString()) == 0) { TABFeature *poTmpFeature = new TABFeature(m_poDefn); for( int i = 0; i < m_poDefn->GetFieldCount(); i++ ) { poTmpFeature->SetField( i, m_poCurFeature->GetRawFieldRef( i ) ); } delete m_poCurFeature; m_poCurFeature = poTmpFeature; } } /*--------------------------------------------------------------------- * The act of reading the geometry causes the first line of the * next object to be preloaded. Set the preloaded id appropriately. *--------------------------------------------------------------------- */ if( m_poMIFFile->GetLastLine() != nullptr ) m_nPreloadedId++; else m_nPreloadedId = 0; /* Update the Current Feature ID */ m_poCurFeature->SetFID(m_nCurFeatureId); return m_poCurFeature; } /********************************************************************** * MIFFile::CreateFeature() * * Write a new feature to this dataset. The passed in feature is updated * with the new feature id. * * Returns OGRERR_NONE on success, or an appropriate OGRERR_ code if an * error happened in which case, CPLError() will have been called to * report the reason of the failure. **********************************************************************/ OGRErr MIFFile::CreateFeature(TABFeature *poFeature) { int nFeatureId = -1; if (m_eAccessMode != TABWrite) { CPLError(CE_Failure, CPLE_NotSupported, ""CreateFeature() can be used only with Write access.""); return OGRERR_UNSUPPORTED_OPERATION; } /*----------------------------------------------------------------- * Make sure file is opened and establish new feature id. *----------------------------------------------------------------*/ if (m_poMIDFile == nullptr) { CPLError(CE_Failure, CPLE_IllegalArg, ""CreateFeature() failed: file is not opened!""); return OGRERR_FAILURE; } if (m_bHeaderWrote == FALSE) { /*------------------------------------------------------------- * OK, this is the first feature in the dataset... make sure the * .MID schema has been initialized. *------------------------------------------------------------*/ if (m_poDefn == nullptr) SetFeatureDefn(poFeature->GetDefnRef(), nullptr); WriteMIFHeader(); nFeatureId = 1; } else { nFeatureId = ++ m_nWriteFeatureId; } /*----------------------------------------------------------------- * Write geometry to the .Mif file *----------------------------------------------------------------*/ if (m_poMIFFile == nullptr || poFeature->WriteGeometryToMIFFile(m_poMIFFile) != 0) { CPLError(CE_Failure, CPLE_FileIO, ""Failed writing geometry for feature id %d in %s"", nFeatureId, m_pszFname); return OGRERR_FAILURE; } if (m_poMIDFile == nullptr || poFeature->WriteRecordToMIDFile(m_poMIDFile) != 0 ) { CPLError(CE_Failure, CPLE_FileIO, ""Failed writing attributes for feature id %d in %s"", nFeatureId, m_pszFname); return OGRERR_FAILURE; } poFeature->SetFID(nFeatureId); return OGRERR_NONE; } /********************************************************************** * MIFFile::GetLayerDefn() * * Returns a reference to the OGRFeatureDefn that will be used to create * features in this dataset. * * Returns a reference to an object that is maintained by this MIFFile * object (and thus should not be modified or freed by the caller) or * NULL if the OGRFeatureDefn has not been initialized yet (i.e. no file * opened yet) **********************************************************************/ OGRFeatureDefn *MIFFile::GetLayerDefn() { return m_poDefn; } /********************************************************************** * MIFFile::SetFeatureDefn() * * Pass a reference to the OGRFeatureDefn that will be used to create * features in this dataset. This function should be called after * creating a new dataset, but before writing the first feature. * All features that will be written to this dataset must share this same * OGRFeatureDefn. * * This function will use poFeatureDefn to create a local copy that * will be used to build the .MID file, etc. * * Returns 0 on success, -1 on error. **********************************************************************/ int MIFFile::SetFeatureDefn(OGRFeatureDefn *poFeatureDefn, TABFieldType *paeMapInfoNativeFieldTypes /* =NULL */) { /*----------------------------------------------------------------- * Check that call happens at the right time in dataset's life. *----------------------------------------------------------------*/ if ( m_eAccessMode == TABWrite && m_bHeaderWrote ) { CPLError(CE_Failure, CPLE_AssertionFailed, ""SetFeatureDefn() must be called after opening a new "" ""dataset, but before writing the first feature to it.""); return -1; } /*----------------------------------------------------------------- * Delete current feature defn if there is already one. * AddFieldNative() will take care of creating a new one for us. *----------------------------------------------------------------*/ if (m_poDefn && m_poDefn->Dereference() == 0) delete m_poDefn; m_poDefn = nullptr; /*----------------------------------------------------------------- * Copy field information *----------------------------------------------------------------*/ const int numFields = poFeatureDefn->GetFieldCount(); int nStatus = 0; for( int iField = 0; iFieldGetFieldDefn(iField); if (paeMapInfoNativeFieldTypes) { eMapInfoType = paeMapInfoNativeFieldTypes[iField]; } else { /*--------------------------------------------------------- * Map OGRFieldTypes to MapInfo native types *--------------------------------------------------------*/ switch(poFieldDefn->GetType()) { case OFTInteger: eMapInfoType = TABFInteger; break; case OFTReal: eMapInfoType = TABFFloat; break; case OFTDateTime: eMapInfoType = TABFDateTime; break; case OFTDate: eMapInfoType = TABFDate; break; case OFTTime: eMapInfoType = TABFTime; break; case OFTString: default: eMapInfoType = TABFChar; } } nStatus = AddFieldNative(poFieldDefn->GetNameRef(), eMapInfoType, poFieldDefn->GetWidth(), poFieldDefn->GetPrecision(), FALSE, FALSE); } return nStatus; } /********************************************************************** * MIFFile::AddFieldNative() * * Create a new field using a native mapinfo data type... this is an * alternative to defining fields through the OGR interface. * This function should be called after creating a new dataset, but before * writing the first feature. * * This function will build/update the OGRFeatureDefn that will have to be * used when writing features to this dataset. * * A reference to the OGRFeatureDefn can be obtained using GetLayerDefn(). * * Returns 0 on success, -1 on error. **********************************************************************/ int MIFFile::AddFieldNative(const char *pszName, TABFieldType eMapInfoType, int nWidth /*=0*/, int nPrecision /*=0*/, GBool bIndexed /*=FALSE*/, GBool bUnique/*=FALSE*/, int /*bApproxOK*/ ) { /*----------------------------------------------------------------- * Check that call happens at the right time in dataset's life. *----------------------------------------------------------------*/ if ( m_eAccessMode == TABWrite && m_bHeaderWrote ) { CPLError(CE_Failure, CPLE_AssertionFailed, ""AddFieldNative() must be called after opening a new "" ""dataset, but before writing the first feature to it.""); return -1; } /*----------------------------------------------------------------- * Validate field width... must be <= 254 *----------------------------------------------------------------*/ if (nWidth > 254) { CPLError(CE_Warning, CPLE_IllegalArg, ""Invalid size (%d) for field '%s'. "" ""Size must be 254 or less."", nWidth, pszName); nWidth = 254; } /*----------------------------------------------------------------- * Map fields with width=0 (variable length in OGR) to a valid default *----------------------------------------------------------------*/ if (eMapInfoType == TABFDecimal && nWidth == 0) nWidth=20; else if (eMapInfoType == TABFChar && nWidth == 0) nWidth=254; /* char fields */ /*----------------------------------------------------------------- * Create new OGRFeatureDefn if not done yet... *----------------------------------------------------------------*/ if (m_poDefn == nullptr) { char *pszFeatureClassName = TABGetBasename(m_pszFname); m_poDefn = new OGRFeatureDefn(pszFeatureClassName); CPLFree(pszFeatureClassName); // Ref count defaults to 0... set it to 1 m_poDefn->Reference(); } CPLString osName(NormalizeFieldName(pszName)); /*----------------------------------------------------------------- * Map MapInfo native types to OGR types *----------------------------------------------------------------*/ OGRFieldDefn *poFieldDefn = nullptr; switch(eMapInfoType) { case TABFChar: /*------------------------------------------------- * CHAR type *------------------------------------------------*/ poFieldDefn = new OGRFieldDefn(osName.c_str(), OFTString); poFieldDefn->SetWidth(nWidth); break; case TABFInteger: /*------------------------------------------------- * INTEGER type *------------------------------------------------*/ poFieldDefn = new OGRFieldDefn(osName.c_str(), OFTInteger); poFieldDefn->SetWidth(nWidth); break; case TABFSmallInt: /*------------------------------------------------- * SMALLINT type *------------------------------------------------*/ poFieldDefn = new OGRFieldDefn(osName.c_str(), OFTInteger); poFieldDefn->SetWidth(nWidth); break; case TABFDecimal: /*------------------------------------------------- * DECIMAL type *------------------------------------------------*/ poFieldDefn = new OGRFieldDefn(osName.c_str(), OFTReal); poFieldDefn->SetWidth(nWidth); poFieldDefn->SetPrecision(nPrecision); break; case TABFFloat: /*------------------------------------------------- * FLOAT type *------------------------------------------------*/ poFieldDefn = new OGRFieldDefn(osName.c_str(), OFTReal); break; case TABFDate: /*------------------------------------------------- * DATE type (V450, returned as a string: ""DD/MM/YYYY"" or ""YYYYMMDD"") *------------------------------------------------*/ poFieldDefn = new OGRFieldDefn(osName.c_str(), #ifdef MITAB_USE_OFTDATETIME OFTDate); #else OFTString); #endif poFieldDefn->SetWidth(10); m_nVersion = std::max(m_nVersion, 450); break; case TABFTime: /*------------------------------------------------- * TIME type (v900, returned as a string: ""HH:MM:SS"" or ""HHMMSSmmm"") *------------------------------------------------*/ poFieldDefn = new OGRFieldDefn(osName.c_str(), #ifdef MITAB_USE_OFTDATETIME OFTTime); #else OFTString); #endif poFieldDefn->SetWidth(9); m_nVersion = std::max(m_nVersion, 900); break; case TABFDateTime: /*------------------------------------------------- * DATETIME type (v900, returned as a string: ""DD/MM/YYYY HH:MM:SS"", * ""YYYY/MM/DD HH:MM:SS"" or ""YYYYMMDDHHMMSSmmm"") *------------------------------------------------*/ poFieldDefn = new OGRFieldDefn(osName.c_str(), #ifdef MITAB_USE_OFTDATETIME OFTDateTime); #else OFTString); #endif poFieldDefn->SetWidth(19); m_nVersion = std::max(m_nVersion, 900); break; case TABFLogical: /*------------------------------------------------- * LOGICAL type (value ""T"" or ""F"") *------------------------------------------------*/ poFieldDefn = new OGRFieldDefn(osName.c_str(), OFTString); poFieldDefn->SetWidth(1); break; default: CPLError(CE_Failure, CPLE_NotSupported, ""Unsupported type for field %s"", pszName); return -1; } /*----------------------------------------------------- * Add the FieldDefn to the FeatureDefn *----------------------------------------------------*/ m_poDefn->AddFieldDefn(poFieldDefn); m_oSetFields.insert(CPLString(poFieldDefn->GetNameRef()).toupper()); delete poFieldDefn; /*----------------------------------------------------------------- * Keep track of native field type *----------------------------------------------------------------*/ m_paeFieldType = static_cast(CPLRealloc(m_paeFieldType, m_poDefn->GetFieldCount()* sizeof(TABFieldType))); m_paeFieldType[m_poDefn->GetFieldCount()-1] = eMapInfoType; /*----------------------------------------------------------------- * Extend array of Indexed/Unique flags *----------------------------------------------------------------*/ m_pabFieldIndexed = static_cast(CPLRealloc(m_pabFieldIndexed, m_poDefn->GetFieldCount()* sizeof(GBool))); m_pabFieldUnique = static_cast(CPLRealloc(m_pabFieldUnique, m_poDefn->GetFieldCount()* sizeof(GBool))); m_pabFieldIndexed[m_poDefn->GetFieldCount()-1] = bIndexed; m_pabFieldUnique[m_poDefn->GetFieldCount()-1] = bUnique; return 0; } /********************************************************************** * MIFFile::GetNativeFieldType() * * Returns the native MapInfo field type for the specified field. * * Returns TABFUnknown if file is not opened, or if specified field index is * invalid. **********************************************************************/ TABFieldType MIFFile::GetNativeFieldType(int nFieldId) { if ( m_poDefn==nullptr || m_paeFieldType==nullptr || nFieldId < 0 || nFieldId >= m_poDefn->GetFieldCount()) return TABFUnknown; return m_paeFieldType[nFieldId]; } /************************************************************************ * MIFFile::SetFieldIndexed() ************************************************************************/ int MIFFile::SetFieldIndexed( int nFieldId ) { if ( m_poDefn==nullptr || m_pabFieldIndexed==nullptr || nFieldId < 0 || nFieldId >= m_poDefn->GetFieldCount()) return -1; m_pabFieldIndexed[nFieldId] = TRUE; return 0; } /************************************************************************ * MIFFile::IsFieldIndexed() ************************************************************************/ GBool MIFFile::IsFieldIndexed( int nFieldId ) { if ( m_poDefn==nullptr || m_pabFieldIndexed==nullptr || nFieldId < 0 || nFieldId >= m_poDefn->GetFieldCount()) return FALSE; return m_pabFieldIndexed[nFieldId]; } /************************************************************************ * MIFFile::IsFieldUnique() ************************************************************************/ GBool MIFFile::IsFieldUnique( int nFieldId ) { if ( m_poDefn==nullptr || m_pabFieldUnique==nullptr || nFieldId < 0 || nFieldId >= m_poDefn->GetFieldCount()) return FALSE; return m_pabFieldUnique[nFieldId]; } /************************************************************************/ /* MIFFile::SetSpatialRef() */ /************************************************************************/ int MIFFile::SetSpatialRef( OGRSpatialReference * poSpatialRef ) { CPLFree( m_pszCoordSys ); m_pszCoordSys = nullptr; char* pszCoordSys = MITABSpatialRef2CoordSys( poSpatialRef ); if( pszCoordSys ) { SetMIFCoordSys(pszCoordSys); CPLFree(pszCoordSys); } return m_pszCoordSys != nullptr; } /************************************************************************/ /* MIFFile::SetMIFCoordSys() */ /************************************************************************/ int MIFFile::SetMIFCoordSys(const char * pszMIFCoordSys) { char *pszCoordSys = nullptr; // Extract the word 'COORDSYS' if present if (STARTS_WITH_CI(pszMIFCoordSys, ""COORDSYS"") ) { pszCoordSys = CPLStrdup(pszMIFCoordSys + 9); } else { pszCoordSys = CPLStrdup(pszMIFCoordSys); } // Extract bounds if present char **papszFields = CSLTokenizeStringComplex(pszCoordSys, "" ,()\\t"", TRUE, FALSE ); int iBounds = CSLFindString( papszFields, ""Bounds"" ); if (iBounds >= 0 && iBounds + 4 < CSLCount(papszFields)) { m_dXMin = CPLAtof(papszFields[++iBounds]); m_dYMin = CPLAtof(papszFields[++iBounds]); m_dXMax = CPLAtof(papszFields[++iBounds]); m_dYMax = CPLAtof(papszFields[++iBounds]); m_bBoundsSet = TRUE; char* pszBounds = strstr(pszCoordSys, "" Bounds""); if( pszBounds == nullptr ) pszBounds = strstr(pszCoordSys, ""Bounds""); pszCoordSys[pszBounds - pszCoordSys] = '\\0'; } CSLDestroy( papszFields ); // Assign the CoordSys CPLFree( m_pszCoordSys ); m_pszCoordSys = CPLStrdup(pszCoordSys); CPLFree(pszCoordSys); return m_pszCoordSys != nullptr; } int MIFFile::SetCharset(const char* pszCharset) { if(0 != IMapInfoFile::SetCharset(pszCharset)) { return -1; } if(m_poMIDFile != nullptr) { m_poMIDFile->SetEncoding( CharsetToEncoding( pszCharset ) ); } if(m_poMIFFile != nullptr) { m_poMIFFile->SetEncoding( CharsetToEncoding( pszCharset ) ); } return 0; } /************************************************************************/ /* MIFFile::GetSpatialRef() */ /************************************************************************/ OGRSpatialReference *MIFFile::GetSpatialRef() { if( m_poSpatialRef == nullptr ) m_poSpatialRef = MITABCoordSys2SpatialRef( m_pszCoordSys ); return m_poSpatialRef; } /********************************************************************** * MIFFile::UpdateExtents() * * Private method used to update the dataset extents. **********************************************************************/ void MIFFile::UpdateExtents(double dfX, double dfY) { if (m_bExtentsSet == FALSE) { m_bExtentsSet = TRUE; m_sExtents.MinX = m_sExtents.MaxX = dfX; m_sExtents.MinY = m_sExtents.MaxY = dfY; } else { if (dfX < m_sExtents.MinX) m_sExtents.MinX = dfX; if (dfX > m_sExtents.MaxX) m_sExtents.MaxX = dfX; if (dfY < m_sExtents.MinY) m_sExtents.MinY = dfY; if (dfY > m_sExtents.MaxY) m_sExtents.MaxY = dfY; } } /********************************************************************** * MIFFile::SetBounds() * * Set projection coordinates bounds of the newly created dataset. * * This function must be called after creating a new dataset and before any * feature can be written to it. * * Returns 0 on success, -1 on error. **********************************************************************/ int MIFFile::SetBounds( double dXMin, double dYMin, double dXMax, double dYMax ) { if (m_eAccessMode != TABWrite) { CPLError(CE_Failure, CPLE_NotSupported, ""SetBounds() can be used only with Write access.""); return -1; } m_dXMin = dXMin; m_dXMax = dXMax; m_dYMin = dYMin; m_dYMax = dYMax; m_bBoundsSet = TRUE; return 0; } /********************************************************************** * MIFFile::GetFeatureCountByType() * * Return number of features of each type. * * NOTE: The current implementation always returns -1 for MIF files * since this would require scanning the whole file. * * When properly implemented, the bForce flag will force scanning the * whole file by default. * * Returns 0 on success, or silently returns -1 (with no error) if this * information is not available. **********************************************************************/ int MIFFile::GetFeatureCountByType(int &numPoints, int &numLines, int &numRegions, int &numTexts, GBool bForce ) { if( m_bPreParsed || bForce ) { PreParseFile(); numPoints = m_nPoints; numLines = m_nLines; numRegions = m_nRegions; numTexts = m_nTexts; return 0; } else { numPoints = numLines = numRegions = numTexts = 0; return -1; } } /********************************************************************** * MIFFile::GetBounds() * * Fetch projection coordinates bounds of a dataset. * * Pass bForce=FALSE to avoid a scan of the whole file if the bounds * are not already available. * * Returns 0 on success, -1 on error or if bounds are not available and * bForce=FALSE. **********************************************************************/ int MIFFile::GetBounds(double &dXMin, double &dYMin, double &dXMax, double &dYMax, GBool bForce /*= TRUE*/ ) { if (m_bBoundsSet == FALSE && bForce == FALSE) { return -1; } else if (m_bBoundsSet == FALSE) { PreParseFile(); } if (m_bBoundsSet == FALSE) { return -1; } dXMin = m_dXMin; dXMax = m_dXMax; dYMin = m_dYMin; dYMax = m_dYMax; return 0; } /********************************************************************** * MIFFile::GetExtent() * * Fetch extent of the data currently stored in the dataset. We collect * this information while preparsing the file ... often already done for * other reasons, and if not it is still faster than fully reading all * the features just to count them. * * Returns OGRERR_NONE/OGRRERR_FAILURE. **********************************************************************/ OGRErr MIFFile::GetExtent (OGREnvelope *psExtent, int bForce) { if (bForce == TRUE) PreParseFile(); if (m_bPreParsed && m_bExtentsSet) { *psExtent = m_sExtents; return OGRERR_NONE; } else return OGRERR_FAILURE; } /************************************************************************/ /* TestCapability() */ /************************************************************************/ int MIFFile::TestCapability( const char * pszCap ) { if( EQUAL(pszCap,OLCRandomRead) ) return TRUE; else if( EQUAL(pszCap,OLCSequentialWrite) ) return TRUE; else if( EQUAL(pszCap,OLCFastFeatureCount) ) return m_bPreParsed; else if( EQUAL(pszCap,OLCFastSpatialFilter) ) return FALSE; else if( EQUAL(pszCap,OLCFastGetExtent) ) return m_bPreParsed; else if( EQUAL(pszCap,OLCCreateField) ) return TRUE; else if( EQUAL(pszCap,OLCStringsAsUTF8) ) return TestUtf8Capability(); else return FALSE; } ",16293,True,3114.437227575206,median "ifdef::env-github[] NOTE: Release notes are best read in our documentation at https://www.elastic.co/guide/en/apm/agent/java/current/release-notes.html[elastic.co] endif::[] //// [[release-notes-x.x.x]] ==== x.x.x - YYYY/MM/DD [float] ===== Breaking changes [float] ===== Features * Cool new feature: {pull}2526[#2526] [float] ===== Bug fixes //// === Unreleased [[release-notes-1.18.0]] ==== 1.18.0 - YYYY/MM/DD [float] ===== Breaking changes [float] ===== Features * The agent now collects cgroup memory metrics (see <>) * Experimental support for runtime attachment now also for OSGi containers, JBoss, and WildFly * New mitigation of OSGi bootdelegation errors (`NoClassDefFoundError`). You can remove any `org.osgi.framework.bootdelegation` related configuration. This release also removes the configuration option `boot_delegation_packages`. * Overhaul of the `ExecutorService` instrumentation that avoids `ClassCastException` issues - {pull}1206[#1206] * Support for `ForkJoinPool` and `ScheduledExecutorService` (see <>) * Support for `ExecutorService#invokeAny` and `ExecutorService#invokeAll` * Added support for `java.util.TimerTask` - {pull}1235[#1235] * Add capturing of request body in Elasticsearch queries: `_msearch`, `_count`, `_msearch/template`, `_search/template`, `_rollup_search` - {pull}1222[#1222] * Add <> flag * Add experimental support for Scala Futures * The agent now collects heap memory pools metrics - {pull}1228[#1228] * Deprecating `ignore_urls` config in favour of <> to align with other agents, while still allowing the old config name for backward compatibility - {pull}1315[#1315] * Enabling instrumentation of classes compiled with Java 1.4. This is reverting the restriction of instrumenting only bytecode of Java 1.5 or higher ({pull}320[#320]), which was added due to potential `VerifyError`. Such errors should be avoided now by the usage of `TypeConstantAdjustment` - {pull}1317[#1317] * Enabling agent to work without attempting any communication with APM server, by allowing setting `server_urls` with an empty string - {pull}1295[#1295] * Add <> - {pull}1303[#1303] * Add `profiling_inferred_spans_lib_directory` option to override the default temp directory used for exporting the async-profiler library. This is useful for server-hardened environments where `/tmp` is often configured with `noexec`, leading to `java.lang.UnsatisfiedLinkError` errors - {pull}1350[#1350] [float] ===== Bug fixes * Fixes error capturing for log4j2 loggers. Version 1.17.0 introduced a regression. * Fixes `NullPointerException` related to JAX-RS and Quartz instrumentation - {pull}1249[#1249] * Expanding k8s pod ID discovery to some formerly non-supported environments * When `recording` is set to `false`, the agent will not send captured errors anymore. * Fixes NPE in Dubbo instrumentation that occurs when the application is acting both as a provider and as a consumer - {pull}1260[#1260] * Adding a delay by default what attaching the agent to Tomcat using the premain route to work around the JUL deadlock issue - {pull}1262[#1262] * Fixes missing `jboss.as:*` MBeans on JBoss - {pull}1257[#1257] * Fixes a `NoClassDefFoundError` in the JMS instrumentation of `MessageListener` - {pull}1287[#1287] * Fix `/ by zero` error message when setting `server_urls` with an empty string - {pull}1295[#1295] * Fix `ClassNotFoundException` or `ClassCastException` in some cases where special log4j configurations are used - {pull}1322[#1322] * Fix `NumberFormatException` when using early access Java version - {pull}1325[#1325] * Fix `service_name` config being ignored when set to the same auto-discovered default value - {pull}1324[#1324] * Fix service name error when updating a web app on a Servlet container - {pull}1326[#1326] [[release-notes-1.x]] === Java Agent version 1.x [[release-notes-1.18.0.rc1]] ==== 1.18.0.RC1 - 2020/07/22 This release candidate adds some highly anticipated features: It’s now possible to attach the agent at runtime in more cases than before. Most notably, it enables runtime attachment on JBoss, WildFly, Glassfish/Payara, and other OSGi runtimes such as Atlassian Jira and Confluence. To make this and other significant features, such as https://github.com/elastic/apm-agent-java/issues/937[external plugins], possible, we have implemented major changes to the architecture of the agent. The agent now relies on the `invokedynamic` bytecode instruction to make plugin development easier, safer, and more efficient. As early versions of Java 7 and Java 8 have unreliable support for invokedynamic, we now require a minimum update level of 60 for Java 7 (7u60+) in addition to the existing minimum update level of 40 for Java 8 (8u40+). We’re looking for users who would like to try this out to give feedback. If we see that the `invokedynamic`-based approach (https://github.com/elastic/apm-agent-java/pull/1230[indy plugins]) works well, we can continue and migrate the rest of the plugins. After the migration has completed, we can move forward with external plugins and remove the experimental label from runtime attachment. If all works like in our testing, you would not see `NoClassDefFoundError` s anymore when, for example, trying to attach the agent at runtime to an OSGi container or a JBoss server. Also, non-standard OSGi containers, such as Atlassian Jira and other technologies with restrictive class loading policies, such as MuleSoft ESB, will benefit from this change. In the worst case, there might be JVM crashes due to `invokedynamic`-related JVM bugs. However, we already disable the agent when attached to JVM versions that are known to be problematic. Another potentially problematic area is that we now dynamically raise the bytecode version of instrumented classes to be at least bytecode version 51 (Java 7). This is needed in order to be able to use the `invokedynamic` instruction. This requires re-computation of stack map frames which makes instrumentation a bit slower. We don't anticipate notable slowdowns unless you extensively (over-)use <>. [float] ===== Breaking changes * Early Java 7 versions, prior to update 60, are not supported anymore. When trying to attach to a non-supported version, the agent will disable itself and not apply any instrumentations. [float] ===== Features * Experimental support for runtime attachment now also for OSGi containers, JBoss, and WildFly * New mitigation of OSGi bootdelegation errors (`NoClassDefFoundError`). You can remove any `org.osgi.framework.bootdelegation` related configuration. This release also removes the configuration option `boot_delegation_packages`. * Overhaul of the `ExecutorService` instrumentation that avoids `ClassCastException` issues - {pull}1206[#1206] * Support for `ForkJoinPool` and `ScheduledExecutorService` (see <>) * Support for `ExecutorService#invokeAny` and `ExecutorService#invokeAll` * Added support for `java.util.TimerTask` - {pull}1235[#1235] * Add capturing of request body in Elasticsearch queries: `_msearch`, `_count`, `_msearch/template`, `_search/template`, `_rollup_search` - {pull}1222[#1222] * Add <> flag * Add experimental support for Scala Futures * The agent now collects heap memory pools metrics - {pull}1228[#1228] [float] ===== Bug fixes * Fixes error capturing for log4j2 loggers. Version 1.17.0 introduced a regression. * Fixes `NullPointerException` related to JAX-RS and Quartz instrumentation - {pull}1249[#1249] * Expanding k8s pod ID discovery to some formerly non-supported environments * When `recording` is set to `false`, the agent will not send captured errors anymore. * Fixes NPE in Dubbo instrumentation that occurs when the application is acting both as a provider and as a consumer - {pull}1260[#1260] * Adding a delay by default what attaching the agent to Tomcat using the premain route to work around the JUL deadlock issue - {pull}1262[#1262] * Fixes missing `jboss.as:*` MBeans on JBoss - {pull}1257[#1257] [[release-notes-1.17.0]] ==== 1.17.0 - 2020/06/17 [float] ===== Features * Log files are now rotated after they reach <>. There will always be one history file `${log_file}.1`. * Add <> and <> with the options `PLAIN_TEXT` and `JSON`. The latter uses https://github.com/elastic/ecs-logging-java[ecs-logging-java] to format the logs. * Exposing <> config - {pull}1187[#1187] * Add support for naming transactions based on Grails controllers. Supports Grails 3+ - {pull}1171[#1171] * Add support for the Apache/Alibaba Dubbo RPC framework * Async Profiler version upgraded to 1.7.1, with a new debugging flag for the stack frame recovery mechanism - {pull}1173[#1173] [float] ===== Bug fixes * Fixes `IndexOutOfBoundsException` that can occur when profiler-inferred spans are enabled. This also makes the profiler more resilient by just removing the call tree related to the exception (which might be in an invalid state) as opposed to stopping the profiler when an exception occurs. * Fix `NumberFormatException` when parsing Ingres/Actian JDBC connection strings - {pull}1198[#1198] * Prevent agent from overriding JVM configured truststore when not using HTTPS for communication with APM server - {pull}1203[#1203] * Fix `java.lang.IllegalStateException` with `jps` JVM when using continuous runtime attach - {pull}1205[1205] * Fix agent trying to load log4j2 plugins from application - {pull}1214[1214] * Fix memory leak in gRPC instrumentation plugin - {pull}1196[1196] * Fix HTTPS connection failures when agent is configured to use HTTPS to communicate with APM server {pull}1209[1209] [[release-notes-1.16.0]] ==== 1.16.0 - 2020/05/13 [float] ===== Features * The log correlation feature now adds `error.id` to the MDC. See <> for details. - {pull}1050[#1050] * Deprecating the `incubating` tag in favour of the `experimental` tag. This is not a breaking change, so former <> configuration containing the `incubating` tag will still be respected - {pull}1123[#1123] * Add a `--without-emulated-attach` option for runtime attachment to allow disabling this feature as a workaround. * Add workaround for JDK bug JDK-8236039 with TLS 1.3 {pull}1149[#1149] * Add log level `OFF` to silence agent logging * Adds <> option to exclude fast executing spans. When set together with one of the more specific thresholds - `trace_methods_duration_threshold` or `profiling_inferred_spans_min_duration`, the higher threshold will determine which spans will be discarded. * Automatically instrument quartz jobs from the quartz-jobs artifact {pull}1170[#1170] * Perform re-parenting of regular spans to be a child of profiler-inferred spans. Requires APM Server and Kibana 7.8.0. {pull}1117[#1117] * Upgrade Async Profiler version to 1.7.0 [float] ===== Bug fixes * When Servlet-related Exceptions are handled through exception handlers that return a 200 status code, agent shouldn't override with 500 - {pull}1103[#1103] * Exclude Quartz 1 from instrumentation to avoid `IncompatibleClassChangeError: Found class org.quartz.JobExecutionContext, but interface was expected` - {pull}1108[#1108] * Fix breakdown metrics span sub-types {pull}1113[#1113] * Fix flaky gRPC server instrumentation {pull}1122[#1122] * Fix side effect of calling `Statement.getUpdateCount` more than once {pull}1139[#1139] * Stop capturing JDBC affected rows count using `Statement.getUpdateCount` to prevent unreliable side-effects {pull}1147[#1147] * Fix OpenTracing error tag handling (set transaction error result when tag value is `true`) {pull}1159[#1159] * Due to a bug in the build we didn't include the gRPC plugin in the build so far * `java.lang.ClassNotFoundException: Unable to load class 'jdk.internal...'` is thrown when tracing specific versions of Atlassian systems {pull}1168[#1168] * Make sure spans are kept active during `AsyncHandler` methods in the `AsyncHttpClient` * CPU and memory metrics are sometimes not reported properly when using IBM J9 {pull}1148[#1148] * `NullPointerException` thrown by the agent on WebLogic {pull}1142[#1142] [[release-notes-1.15.0]] ==== 1.15.0 - 2020/03/27 [float] ===== Breaking changes * Ordering of configuration sources has slightly changed, please review <>: ** `elasticapm.properties` file now has higher priority over java system properties and environment variables, + This change allows to change dynamic options values at runtime by editing file, previously values set in java properties or environment variables could not be overridden, even if they were dynamic. * Renamed some configuration options related to the experimental profiler-inferred spans feature ({pull}1084[#1084]): ** `profiling_spans_enabled` -> `profiling_inferred_spans_enabled` ** `profiling_sampling_interval` -> `profiling_inferred_spans_sampling_interval` ** `profiling_spans_min_duration` -> `profiling_inferred_spans_min_duration` ** `profiling_included_classes` -> `profiling_inferred_spans_included_classes` ** `profiling_excluded_classes` -> `profiling_inferred_spans_excluded_classes` ** Removed `profiling_interval` and `profiling_duration` (both are fixed to 5s now) [float] ===== Features * Gracefully abort agent init when running on a known Java 8 buggy JVM {pull}1075[#1075]. * Add support for <> * Makes <>, <>, and <> dynamic. Note that changing these values at runtime can slow down the application temporarily. * Do not instrument Servlet API before 3.0 {pull}1077[#1077] * Add support for API keys for apm backend authentication {pull}1083[#1083] * Add support for <> client & server instrumentation {pull}1019[#1019] * Deprecating `active` configuration option in favor of `recording`. Setting `active` still works as it's now an alias for `recording`. [float] ===== Bug fixes * When JAX-RS-annotated method delegates to another JAX-RS-annotated method, transaction name should include method A - {pull}1062[#1062] * Fixed bug that prevented an APM Error from being created when calling `org.slf4j.Logger#error` - {pull}1049[#1049] * Wrong address in JDBC spans for Oracle, MySQL and MariaDB when multiple hosts are configured - {pull}1082[#1082] * Document and re-order configuration priorities {pull}1087[#1087] * Improve heuristic for `service_name` when not set through config {pull}1097[#1097] [[release-notes-1.14.0]] ==== 1.14.0 - 2020/03/04 [float] ===== Features * Support for the official https://www.w3.org/TR/trace-context[W3C] `traceparent` and `tracestate` headers. + The agent now accepts both the `elastic-apm-traceparent` and the official `traceparent` header. By default, it sends both headers on outgoing requests, unless <> is set to false. * Creating spans for slow methods with the help of the sampling profiler https://github.com/jvm-profiling-tools/async-profiler[async-profiler]. This is a low-overhead way of seeing which methods make your transactions slow and a replacement for the `trace_methods` configuration option. See <> for more details * Adding a Circuit Breaker to pause the agent when stress is detected on the system and resume when the stress is relieved. See <> and {pull}1040[#1040] for more info. * `Span#captureException` and `Transaction#captureException` in public API return reported error id - {pull}1015[#1015] [float] ===== Bug fixes * java.lang.IllegalStateException: Cannot resolve type description for - {pull}1037[#1037] * properly handle `java.sql.SQLException` for unsupported JDBC features {pull}[#1035] https://github.com/elastic/apm-agent-java/issues/1025[#1025] [[release-notes-1.13.0]] ==== 1.13.0 - 2020/02/11 [float] ===== Features * Add support for <> * Add `context.message.age.ms` field for JMS message receiving spans and transactions - {pull}970[#970] * Instrument log4j2 Logger#error(String, Throwable) ({pull}919[#919]) Automatically captures exceptions when calling `logger.error(""message"", exception)` * Add instrumentation for external process execution through `java.lang.Process` and Apache `commons-exec` - {pull}903[#903] * Add `destination` fields to exit span contexts - {pull}976[#976] * Removed `context.message.topic.name` field - {pull}993[#993] * Add support for Kafka clients - {pull}981[#981] * Add support for binary `traceparent` header format (see the https://github.com/elastic/apm/blob/master/docs/agent-development.md#Binary-Fields[spec] for more details) - {pull}1009[#1009] * Add support for log correlation for log4j and log4j2, even when not used in combination with slf4j. See <> for details. [float] ===== Bug Fixes * Fix parsing value of `trace_methods` configuration property {pull}930[#930] * Workaround for `java.util.logging` deadlock {pull}965[#965] * JMS should propagate traceparent header when transactions are not sampled {pull}999[#999] * Spans are not closed if JDBC implementation does not support `getUpdateCount` {pull}1008[#1008] [[release-notes-1.12.0]] ==== 1.12.0 - 2019/11/21 [float] ===== Features * JMS Enhancements {pull}911[#911]: ** Add special handling for temporary queues/topics ** Capture message bodies of text Messages *** Rely on the existing `ELASTIC_APM_CAPTURE_BODY` agent config option (off by default). *** Send as `context.message.body` *** Limit size to 10000 characters. If longer than this size, trim to 9999 and append with ellipsis ** Introduce the `ignore_message_queues` configuration to disable instrumentation (message tagging) for specific queues/topics as suggested in {pull}710[#710] ** Capture predefined message headers and all properties *** Rely on the existing `ELASTIC_APM_CAPTURE_HEADERS` agent config option. *** Send as `context.message.headers` *** Sanitize sensitive headers/properties based on the `sanitize_field_names` config option * Added support for the MongoDB sync driver. See https://www.elastic.co/guide/en/apm/agent/java/master/supported-technologies-details.html#supported-databases[supported data stores]. [float] ===== Bug Fixes * JDBC regression- `PreparedStatement#executeUpdate()` and `PreparedStatement#executeLargeUpdate()` are not traced {pull}918[#918] * When systemd cgroup driver is used, the discovered Kubernetes pod UID contains ""_"" instead of ""-"" {pull}920[#920] * DB2 jcc4 driver is not traced properly {pull}926[#926] [[release-notes-1.11.0]] ==== 1.11.0 - 2019/10/31 [float] ===== Features * Add the ability to configure a unique name for a JVM within a service through the https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-node-name[`service_node_name`] config option] * Add ability to ignore some exceptions to be reported as errors https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-ignore-exceptions[ignore_exceptions] * Applying new logic for JMS `javax.jms.MessageConsumer#receive` so that, instead of the transaction created for the polling method itself (ie from `receive` start to end), the agent will create a transaction attempting to capture the code executed during actual message handling. This logic is suitable for environments where polling APIs are invoked within dedicated polling threads. This polling transaction creation strategy can be reversed through a configuration option (`message_polling_transaction_strategy`) that is not exposed in the properties file by default. * Send IP obtained through `javax.servlet.ServletRequest#getRemoteAddr()` in `context.request.socket.remote_address` instead of parsing from headers {pull}889[#889] * Added `ElasticApmAttacher.attach(String propertiesLocation)` to specify a custom properties location * Logs message when `transaction_max_spans` has been exceeded {pull}849[#849] * Report the number of affected rows by a SQL statement (UPDATE,DELETE,INSERT) in 'affected_rows' span attribute {pull}707[#707] * Add https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-traced[`@Traced`] annotation which either creates a span or a transaction, depending on the context * Report JMS destination as a span/transaction context field {pull}906[#906] * Added https://www.elastic.co/guide/en/apm/agent/java/master/config-jmx.html#config-capture-jmx-metrics[`capture_jmx_metrics`] configuration option [float] ===== Bug Fixes * JMS creates polling transactions even when the API invocations return without a message * Support registering MBeans which are added after agent startup [[release-notes-1.10.0]] ==== 1.10.0 - 2019/09/30 [float] ===== Features * Add ability to manually specify reported https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-hostname[hostname] * Add support for https://www.elastic.co/guide/en/apm/agent/java/master/supported-technologies-details.html#supported-databases[Redis Jedis client] * Add support for identifying target JVM to attach apm agent to using JVM property. See also the documentation of the https://www.elastic.co/guide/en/apm/agent/java/master/setup-attach-cli.html#setup-attach-cli-usage-list[`--include` and `--exclude` flags] * Added https://www.elastic.co/guide/en/apm/agent/java/master/config-jmx.html#config-capture-jmx-metrics[`capture_jmx_metrics`] configuration option * Improve servlet error capture {pull}812[#812] Among others, now also takes Spring MVC `@ExceptionHandler`s into account * Instrument Logger#error(String, Throwable) {pull}821[#821] Automatically captures exceptions when calling `logger.error(""message"", exception)` * Easier log correlation with https://github.com/elastic/java-ecs-logging. See https://www.elastic.co/guide/en/apm/agent/java/master/log-correlation.html[docs]. * Avoid creating a temp agent file for each attachment {pull}859[#859] * Instrument `View#render` instead of `DispatcherServlet#render` {pull}829[#829] This makes the transaction breakdown graph more useful. Instead of `dispatcher-servlet`, the graph now shows a type which is based on the view name, for example, `FreeMarker` or `Thymeleaf`. [float] ===== Bug Fixes * Error in log when setting https://www.elastic.co/guide/en/apm/agent/java/current/config-reporter.html#config-server-urls[server_urls] to an empty string - `co.elastic.apm.agent.configuration.ApmServerConfigurationSource - Expected previousException not to be null` * Avoid terminating the TCP connection to APM Server when polling for configuration updates {pull}823[#823] [[release-notes-1.9.0]] ==== 1.9.0 - 2019/08/22 [float] ===== Features * Upgrading supported OpenTracing version from 0.31 to 0.33 * Added annotation and meta-annotation matching support for `trace_methods`, for example: ** `public @java.inject.* org.example.*` (for annotation) ** `public @@javax.enterprise.context.NormalScope org.example.*` (for meta-annotation) * The runtime attachment now also works when the `tools.jar` or the `jdk.attach` module is not available. This means you don't need a full JDK installation - the JRE is sufficient. This makes the runtime attachment work in more environments such as minimal Docker containers. Note that the runtime attachment currently does not work for OSGi containers like those used in many application servers such as JBoss and WildFly. See the https://www.elastic.co/guide/en/apm/agent/java/master/setup-attach-cli.html[documentation] for more information. * Support for Hibernate Search [float] ===== Bug Fixes * A warning in logs saying APM server is not available when using 1.8 with APM server 6.x. Due to that, agent 1.8.0 will silently ignore non-string labels, even if used with APM server of versions 6.7.x or 6.8.x that support such. If APM server version is <6.7 or 7.0+, this should have no effect. Otherwise, upgrade the Java agent to 1.9.0+. * `ApacheHttpAsyncClientInstrumentation` matching increases startup time considerably * Log correlation feature is active when `active==false` * Tomcat's memory leak prevention mechanism is causing a... memory leak. JDBC statement map is leaking in Tomcat if the application that first used it is undeployed/redeployed. See https://discuss.elastic.co/t/elastic-apm-agent-jdbchelper-seems-to-use-a-lot-of-memory/195295[this related discussion]. [float] ==== Breaking Changes * The `apm-agent-attach.jar` is not executable anymore. Use `apm-agent-attach-standalone.jar` instead. [[release-notes-1.8.0]] ==== 1.8.0 - 2019/07/30 [float] ===== Features * Added support for tracking https://www.elastic.co/guide/en/kibana/7.3/transactions.html[time spent by span type]. Can be disabled by setting https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-breakdown-metrics[`breakdown_metrics`] to `false`. * Added support for https://www.elastic.co/guide/en/kibana/7.3/agent-configuration.html[central configuration]. Can be disabled by setting https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-central-config[`central_config`] to `false`. * Added support for Spring's JMS flavor - instrumenting `org.springframework.jms.listener.SessionAwareMessageListener` * Added support to legacy ApacheHttpClient APIs (which adds support to Axis2 configured to use ApacheHttpClient) * Added support for setting https://www.elastic.co/guide/en/apm/agent/java/1.x/config-reporter.html#config-server-urls[`server_urls`] dynamically via properties file {pull}723[#723] * Added https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-config-file[`config_file`] option * Added option to use `@javax.ws.rs.Path` value as transaction name https://www.elastic.co/guide/en/apm/agent/java/current/config-jax-rs.html#config-use-jaxrs-path-as-transaction-name[`use_jaxrs_path_as_transaction_name`] * Instrument quartz jobs https://www.elastic.co/guide/en/apm/agent/java/current/supported-technologies-details.html#supported-scheduling-frameworks[docs] * SQL parsing improvements {pull}696[#696] * Introduce priorities for transaction name {pull}748[#748]. Now uses the path as transaction name if https://www.elastic.co/guide/en/apm/agent/java/current/config-http.html#config-use-path-as-transaction-name[`use_path_as_transaction_name`] is set to `true` rather than `ServletClass#doGet`. But if a name can be determined from a high level framework, like Spring MVC, that takes precedence. User-supplied names from the API always take precedence over any others. * Use JSP path name as transaction name as opposed to the generated servlet class name {pull}751[#751] [float] ===== Bug Fixes * Some JMS Consumers and Producers are filtered due to class name filtering in instrumentation matching * Jetty: When no display name is set and context path is ""/"" transaction service names will now correctly fall back to configured values * JDBC's `executeBatch` is not traced * Drops non-String labels when connected to APM Server < 6.7 to avoid validation errors {pull}687[#687] * Parsing container ID in cloud foundry garden {pull}695[#695] * Automatic instrumentation should not override manual results {pull}752[#752] [float] ===== Breaking changes * The log correlation feature does not add `span.id` to the MDC anymore but only `trace.id` and `transaction.id` {pull}742[#742]. [[release-notes-1.7.0]] ==== 1.7.0 - 2019/06/13 [float] ===== Features * Added the `trace_methods_duration_threshold` config option. When using the `trace_methods` config option with wild cards, this enables considerable reduction of overhead by limiting the number of spans captured and reported (see more details in config documentation). NOTE: Using wildcards is still not the recommended approach for the `trace_methods` feature. * Add `Transaction#addCustomContext(String key, String|Number|boolean value)` to public API * Added support for AsyncHttpClient 2.x * Added https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-global-labels[`global_labels`] configuration option. This requires APM Server 7.2+. * Added basic support for JMS- distributed tracing for basic scenarios of `send`, `receive`, `receiveNoWait` and `onMessage`. Both Queues and Topics are supported. Async `send` APIs are not supported in this version. NOTE: This feature is currently marked as ""experimental"" and is disabled by default. In order to enable, it is required to set the https://www.elastic.co/guide/en/apm/agent/java/1.x/config-core.html#config-disable-instrumentations[`disable_instrumentations`] configuration property to an empty string. * Improved OSGi support: added a configuration option for `bootdelegation` packages {pull}641[#641] * Better span names for SQL spans. For example, `SELECT FROM user` instead of just `SELECT` {pull}633[#633] [float] ===== Bug Fixes * ClassCastException related to async instrumentation of Pilotfish Executor causing thread hang (applied workaround) * NullPointerException when computing Servlet transaction name with null HTTP method name * FileNotFoundException when trying to find implementation version of jar with encoded URL * NullPointerException when closing Apache AsyncHttpClient request producer * Fixes loading of `elasticapm.properties` for Spring Boot applications * Fix startup error on WebLogic 12.2.1.2.0 {pull}649[#649] * Disable metrics reporting and APM Server health check when active=false {pull}653[#653] [[release-notes-1.6.1]] ==== 1.6.1 - 2019/04/26 [float] ===== Bug Fixes * Fixes transaction name for non-sampled transactions https://github.com/elastic/apm-agent-java/issues/581[#581] * Makes log_file option work again https://github.com/elastic/apm-agent-java/issues/594[#594] * Async context propagation fixes ** Fixing some async mechanisms lifecycle issues https://github.com/elastic/apm-agent-java/issues/605[#605] ** Fixes exceptions when using WildFly managed executor services https://github.com/elastic/apm-agent-java/issues/589[#589] ** Exclude glassfish Executor which does not permit wrapped runnables https://github.com/elastic/apm-agent-java/issues/596[#596] ** Exclude DumbExecutor https://github.com/elastic/apm-agent-java/issues/598[#598] * Fixes Manifest version reading error to support `jar:file` protocol https://github.com/elastic/apm-agent-java/issues/601[#601] * Fixes transaction name for non-sampled transactions https://github.com/elastic/apm-agent-java/issues/597[#597] * Fixes potential classloader deadlock by preloading `FileSystems.getDefault()` https://github.com/elastic/apm-agent-java/issues/603[#603] [[release-notes-1.6.0]] ==== 1.6.0 - 2019/04/16 [float] ===== Related Announcements * Java APM Agent became part of the Cloud Foundry Java Buildpack as of https://github.com/cloudfoundry/java-buildpack/releases/tag/v4.19[Release v4.19] [float] ===== Features * Support Apache HttpAsyncClient - span creation and cross-service trace context propagation * Added the `jvm.thread.count` metric, indicating the number of live threads in the JVM (daemon and non-daemon) * Added support for WebLogic * Added support for Spring `@Scheduled` and EJB `@Schedule` annotations - https://github.com/elastic/apm-agent-java/pull/569[#569] [float] ===== Bug Fixes * Avoid that the agent blocks server shutdown in case the APM Server is not available - https://github.com/elastic/apm-agent-java/pull/554[#554] * Public API annotations improper retention prevents it from being used with Groovy - https://github.com/elastic/apm-agent-java/pull/567[#567] * Eliminate side effects of class loading related to Instrumentation matching mechanism [[release-notes-1.5.0]] ==== 1.5.0 - 2019/03/26 [float] ===== Potentially breaking changes * If you didn't explicitly set the https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-name[`service_name`] previously and you are dealing with a servlet-based application (including Spring Boot), your `service_name` will change. See the documentation for https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-name[`service_name`] and the corresponding section in _Features_ for more information. Note: this requires APM Server 7.0+. If using previous versions, nothing will change. [float] ===== Features * Added property `""allow_path_on_hierarchy""` to JAX-RS plugin, to lookup inherited usage of `@path` * Support for number and boolean labels in the public API {pull}497[497]. This change also renames `tag` to `label` on the API level to be compliant with the https://github.com/elastic/ecs#-base-fields[Elastic Common Schema (ECS)]. The `addTag(String, String)` method is still supported but deprecated in favor of `addLabel(String, String)`. As of version 7.x of the stack, labels will be stored under `labels` in Elasticsearch. Previously, they were stored under `context.tags`. * Support async queries made by Elasticsearch REST client * Added `setStartTimestamp(long epochMicros)` and `end(long epochMicros)` API methods to `Span` and `Transaction`, allowing to set custom start and end timestamps. * Auto-detection of the `service_name` based on the `` element of the `web.xml` with a fallback to the servlet context path. If you are using a spring-based application, the agent will use the setting for `spring.application.name` for its `service_name`. See the documentation for https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-name[`service_name`] for more information. Note: this requires APM Server 7.0+. If using previous versions, nothing will change. * Previously, enabling https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-capture-body[`capture_body`] could only capture form parameters. Now it supports all UTF-8 encoded plain-text content types. The option https://www.elastic.co/guide/en/apm/agent/java/master/config-http.html#config-capture-body-content-types[`capture_body_content_types`] controls which `Content-Type`s should be captured. * Support async calls made by OkHttp client (`Call#enqueue`) * Added support for providing config options on agent attach. ** CLI example: `--config server_urls=http://localhost:8200,http://localhost:8201` ** API example: `ElasticApmAttacher.attach(Map.of(""server_urls"", ""http://localhost:8200,http://localhost:8201""));` [float] ===== Bug Fixes * Logging integration through MDC is not working properly - https://github.com/elastic/apm-agent-java/issues/499[#499] * ClassCastException with adoptopenjdk/openjdk11-openj9 - https://github.com/elastic/apm-agent-java/issues/505[#505] * Span count limitation is not working properly - reported https://discuss.elastic.co/t/kibana-apm-not-showing-spans-which-are-visible-in-discover-too-many-spans/171690[in our forum] * Java agent causes Exceptions in Alfresco cluster environment due to failure in the instrumentation of Hazelcast `Executor`s - reported https://discuss.elastic.co/t/cant-run-apm-java-agent-in-alfresco-cluster-environment/172962[in our forum] [[release-notes-1.4.0]] ==== 1.4.0 - 2019/02/14 [float] ===== Features * Added support for sync calls of OkHttp client * Added support for context propagation for `java.util.concurrent.ExecutorService`s * The `trace_methods` configuration now allows to omit the method matcher. Example: `com.example.*` traces all classes and methods within the `com.example` package and sub-packages. * Added support for JSF. Tested on WildFly, WebSphere Liberty and Payara with embedded JSF implementation and on Tomcat and Jetty with MyFaces 2.2 and 2.3 * Introduces a new configuration option `disable_metrics` which disables the collection of metrics via a wildcard expression. * Support for HttpUrlConnection * Adds `subtype` and `action` to spans. This replaces former typing mechanism where type, subtype and action were all set through the type in an hierarchical dotted-syntax. In order to support existing API usages, dotted types are parsed into subtype and action, however `Span.createSpan` and `Span.setType` are deprecated starting this version. Instead, type-less spans can be created using the new `Span.startSpan` API and typed spans can be created using the new `Span.startSpan(String type, String subtype, String action)` API * Support for JBoss EAP 6.4, 7.0, 7.1 and 7.2 * Improved startup times * Support for SOAP (JAX-WS). SOAP client create spans and propagate context. Transactions are created for `@WebService` classes and `@WebMethod` methods. [float] ===== Bug Fixes * Fixes a failure in BitBucket when agent deployed https://github.com/elastic/apm-agent-java/issues/349[#349] * Fixes increased CPU consumption https://github.com/elastic/apm-agent-java/issues/453[#453] and https://github.com/elastic/apm-agent-java/issues/443[#443] * Fixed some OpenTracing bridge functionalities that were not working when auto-instrumentation is disabled * Fixed an error occurring when ending an OpenTracing span before deactivating * Sending proper `null` for metrics that have a NaN value * Fixes JVM crash with Java 7 https://github.com/elastic/apm-agent-java/issues/458[#458] * Fixes an application deployment failure when using EclipseLink and `trace_methods` configuration https://github.com/elastic/apm-agent-java/issues/474[#474] [[release-notes-1.3.0]] ==== 1.3.0 - 2019/01/10 [float] ===== Features * The agent now collects system and JVM metrics https://github.com/elastic/apm-agent-java/pull/360[#360] * Add API methods `ElasticApm#startTransactionWithRemoteParent` and `Span#injectTraceHeaders` to allow for manual context propagation https://github.com/elastic/apm-agent-java/pull/396[#396]. * Added `trace_methods` configuration option which lets you define which methods in your project or 3rd party libraries should be traced. To create spans for all `public` methods of classes whose name ends in `Service` which are in a sub-package of `org.example.services` use this matcher: `public org.example.services.*.*Service#*` https://github.com/elastic/apm-agent-java/pull/398[#398] * Added span for `DispatcherServlet#render` https://github.com/elastic/apm-agent-java/pull/409[#409]. * Flush reporter on shutdown to make sure all recorded Spans are sent to the server before the program exits https://github.com/elastic/apm-agent-java/pull/397[#397] * Adds Kubernetes https://github.com/elastic/apm-agent-java/issues/383[#383] and Docker metadata to, enabling correlation with the Kibana Infra UI. * Improved error handling of the Servlet Async API https://github.com/elastic/apm-agent-java/issues/399[#399] * Support async API’s used with AsyncContext.start https://github.com/elastic/apm-agent-java/issues/388[#388] [float] ===== Bug Fixes * Fixing a potential memory leak when there is no connection with APM server * Fixes NoSuchMethodError CharBuffer.flip() which occurs when using the Elasticsearch RestClient and Java 7 or 8 https://github.com/elastic/apm-agent-java/pull/401[#401] [[release-notes-1.2.0]] ==== 1.2.0 - 2018/12/19 [float] ===== Features * Added `capture_headers` configuration option. Set to `false` to disable capturing request and response headers. This will reduce the allocation rate of the agent and can save you network bandwidth and disk space. * Makes the API methods `addTag`, `setName`, `setType`, `setUser` and `setResult` fluent, so that calls can be chained. [float] ===== Bug Fixes * Catch all errors thrown within agent injected code * Enable public APIs and OpenTracing bridge to work properly in OSGi systems, fixes https://github.com/elastic/apm-agent-java/issues/362[this WildFly issue] * Remove module-info.java to enable agent working on early Tomcat 8.5 versions * Fix https://github.com/elastic/apm-agent-java/issues/371[async Servlet API issue] [[release-notes-1.1.0]] ==== 1.1.0 - 2018/11/28 [float] ===== Features * Some memory allocation improvements * Enabling bootdelegation for agent classes in Atlassian OSGI systems [float] ===== Bug Fixes * Update dsl-json which fixes a memory leak. See https://github.com/ngs-doo/dsl-json/pull/102[ngs-doo/dsl-json#102] for details. * Avoid `VerifyError`s by non instrumenting classes compiled for Java 4 or earlier * Enable APM Server URL configuration with path (fixes #339) * Reverse `system.hostname` and `system.platform` order sent to APM server [[release-notes-1.0.1]] ==== 1.0.1 - 2018/11/15 [float] ===== Bug Fixes * Fixes NoSuchMethodError CharBuffer.flip() which occurs when using the Elasticsearch RestClient and Java 7 or 8 {pull}313[#313] [[release-notes-1.0.0]] ==== 1.0.0 - 2018/11/14 [float] ===== Breaking changes * Remove intake v1 support. This version requires APM Server 6.5.0+ which supports the intake api v2. Until the time the APM Server 6.5.0 is officially released, you can test with docker by pulling the APM Server image via `docker pull docker.elastic.co/apm/apm-server:6.5.0-SNAPSHOT`. [float] ===== Features * Adds `@CaptureTransaction` and `@CaptureSpan` annotations which let you declaratively add custom transactions and spans. Note that it is required to configure the `application_packages` for this to work. See the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-annotation[documentation] for more information. * The public API now supports to activate a span on the current thread. This makes the span available via `ElasticApm#currentSpan()` Refer to the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-span-activate[documentation] for more details. * Capturing of Elasticsearch RestClient 5.0.2+ calls. Currently, the `*Async` methods are not supported, only their synchronous counterparts. * Added API methods to enable correlating the spans created from the JavaScrip Real User Monitoring agent with the Java agent transaction. More information can be found in the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-ensure-parent-id[documentation]. * Added `Transaction.isSampled()` and `Span.isSampled()` methods to the public API * Added `Transaction#setResult` to the public API {pull}293[#293] [float] ===== Bug Fixes * Fix for situations where status code is reported as `200`, even though it actually was `500` {pull}225[#225] * Capturing the username now properly works when using Spring security {pull}183[#183] [[release-notes-1.0.0.rc1]] ==== 1.0.0.RC1 - 2018/11/06 [float] ===== Breaking changes * Remove intake v1 support. This version requires APM Server 6.5.0+ which supports the intake api v2. Until the time the APM Server 6.5.0 is officially released, you can test with docker by pulling the APM Server image via `docker pull docker.elastic.co/apm/apm-server:6.5.0-SNAPSHOT`. * Wildcard patterns are case insensitive by default. Prepend `(?-i)` to make the matching case sensitive. [float] ===== Features * Support for Distributed Tracing * Adds `@CaptureTransaction` and `@CaptureSpan` annotations which let you declaratively add custom transactions and spans. Note that it is required to configure the `application_packages` for this to work. See the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-annotation[documentation] for more information. * The public API now supports to activate a span on the current thread. This makes the span available via `ElasticApm#currentSpan()` Refer to the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-span-activate[documentation] for more details. * Capturing of Elasticsearch RestClient 5.0.2+ calls. Currently, the `*Async` methods are not supported, only their synchronous counterparts. * Added API methods to enable correlating the spans created from the JavaScrip Real User Monitoring agent with the Java agent transaction. More information can be found in the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-ensure-parent-id[documentation]. * Microsecond accurate timestamps {pull}261[#261] * Support for JAX-RS annotations. Transactions are named based on your resources (`ResourceClass#resourceMethod`). [float] ===== Bug Fixes * Fix for situations where status code is reported as `200`, even though it actually was `500` {pull}225[#225] [[release-notes-0.8.x]] === Java Agent version 0.8.x [[release-notes-0.8.0]] ==== 0.8.0 [float] ===== Breaking changes * Wildcard patterns are case insensitive by default. Prepend `(?-i)` to make the matching case sensitive. [float] ===== Features * Wildcard patterns are now not limited to only one wildcard in the middle and can be arbitrarily complex now. Example: `*foo*bar*baz`. * Support for JAX-RS annotations. Transactions are named based on your resources (`ResourceClass#resourceMethod`). [[release-notes-0.7.x]] === Java Agent version 0.7.x [[release-notes-0.7.1]] ==== 0.7.1 - 2018/10/24 [float] ===== Bug Fixes * Avoid recycling transactions twice {pull}178[#178] [[release-notes-0.7.0]] ==== 0.7.0 - 2018/09/12 [float] ===== Breaking changes * Removed `ElasticApm.startSpan`. Spans can now only be created from their transactions via `Transaction#createSpan`. * `ElasticApm.startTransaction` and `Transaction#createSpan` don't activate the transaction and spans and are thus not available via `ElasticApm.activeTransaction` and `ElasticApm.activeSpan`. [float] ===== Features * Public API ** Add `Span#captureException` and `Transaction#captureException` to public API. `ElasticApm.captureException` is deprecated now. Use `ElasticApm.currentSpan().captureException(exception)` instead. ** Added `Transaction.getId` and `Span.getId` methods * Added support for async servlet requests * Added support for Payara/Glassfish * Incubating support for Apache HttpClient * Support for Spring RestTemplate * Added configuration options `use_path_as_transaction_name` and `url_groups`, which allow to use the URL path as the transaction name. As that could contain path parameters, like `/user/$userId` however, You can set the `url_groups` option to define a wildcard pattern, like `/user/*`, to group those paths together. This is especially helpful when using an unsupported Servlet API-based framework. * Support duration suffixes (`ms`, `s` and `m`) for duration configuration options. Not using the duration suffix logs out a deprecation warning and will not be supported in future versions. * Add ability to add multiple APM server URLs, which enables client-side load balancing. The configuration option `server_url` has been renamed to `server_urls` to reflect this change. However, `server_url` still works for backwards compatibility. * The configuration option `service_name` is now optional. It defaults to the main class name, the name of the executed jar file (removing the version number), or the application server name (for example `tomcat-application`). In a lot of cases, you will still want to set the `service_name` explicitly. But it helps getting started and seeing data easier, as there are no required configuration options anymore. In the future we will most likely determine more useful application names for Servlet API-based applications. ",12301,True,2565.743342953105,median "[[box-component]] = Box Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-box/camel-box-component/src/main/docs/box-component.adoc :docTitle: Box :artifactId: camel-box :description: Upload, download and manage files, folders, groups, collaborations, etc. on box.com. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/box.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Box component provides access to all of the Box.com APIs accessible using https://github.com/box/box-java-sdk/[https://github.com/box/box-java-sdk]. It allows producing messages to upload and download files, create, edit, and manage folders, etc. It also supports APIs that allow polling for updates to user accounts and even changes to enterprise accounts, etc. Box.com requires the use of OAuth2.0 for all client application authentication. In order to use camel-box with your account, you'll need to create a new application within Box.com at https://developer.box.com/[https://developer.box.com]. The Box application's client id and secret will allow access to Box APIs which require a current user. A user access token is generated and managed by the API for an end user. Maven users will need to add the following dependency to their pom.xml for this component: [source,xml] ---- org.apache.camel camel-box ${camel-version} ---- == Connection Authentication Types The Box component supports three different types of authenticated connections. === Standard Authentication *Standard Authentication* uses the *OAuth 2.0 three-legged authentication process* to authenticate its connections with Box.com. This type of authentication enables Box *managed users* and *external users* to access, edit, and save their Box content through the Box component. === App Enterprise Authentication *App Enterprise Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as a *Service Account* for a *Box Application*. This type of authentication enables a service account to access, edit, and save the Box content of its *Box Application* through the Box component. === App User Authentication *App User Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as an *App User* for a *Box Application*. This type of authentication enables app users to access, edit, and save their Box content in its *Box Application* through the Box component. == Box Options // component options: START The Box component supports 19 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *configuration* (common) | To use the shared configuration | | BoxConfiguration | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *userId* (common) | The user ID to use for an App User. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *basicPropertyBinding* (advanced) | *Deprecated* Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== // component options: END // endpoint options: START The Box endpoint is configured using URI syntax: ---- box:apiName/methodName ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *apiName* | *Required* What kind of operation to perform. There are 10 enums and the value can be one of: COLLABORATIONS, COMMENTS, EVENT_LOGS, FILES, FOLDERS, GROUPS, EVENTS, SEARCH, TASKS, USERS | | BoxApiName | *methodName* | *Required* What sub operation to use for the selected operation | | String |=== === Query Parameters (21 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *inBody* (common) | Sets the name of a parameter to be passed in the exchange In Body | | String | *userId* (common) | The user ID to use for an App User. | | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== === API Parameters (10 APIs): The Box endpoint is an API based component and has additional parameters based on which API name and API method is used. The API name and API method is located in the endpoint URI as the apiName/methodName path parameters: ---- box:apiName/methodName ---- There are 10 API names as listed in the table below: [width=""100%"",cols=""2,2,6"",options=""header""] |=== | API Name | Type | Description | *collaborations* | Producer | Provides operations to manage Box collaborations | *comments* | Producer | Provides operations to manage Box comments | *event-logs* | Producer | Provides operations to read Box enterprise (admin) event logs | *events* | Consumer | Provides operations to manage Box events | *files* | Producer | Provides operations to manage Box files | *folders* | Producer | Provides operations to manage Box folders | *groups* | Producer | Provides operations to manage Box groups | *search* | Producer | Provides operations to manage Box searches | *tasks* | Producer | Provides operations to manage Box tasks | *users* | Producer | Provides operations to manage Box users |=== Each API is documented in the following sections to come. ==== API: collaborations *Only producer is supported* The collaborations API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxCollaboration addFolderCollaboration(String folderId, com.box.sdk.BoxCollaborator collaborator, com.box.sdk.BoxCollaboration.Role role); com.box.sdk.BoxCollaboration addFolderCollaborationByEmail(String folderId, String email, com.box.sdk.BoxCollaboration.Role role); void deleteCollaboration(String collaborationId); com.box.sdk.BoxCollaboration.Info getCollaborationInfo(String collaborationId); java.util.Collection getFolderCollaborations(String folderId); com.box.sdk.BoxCollaboration updateCollaborationInfo(String collaborationId, com.box.sdk.BoxCollaboration.Info info); ---- The collaborations API is defined in the syntax as follows: ---- box:collaborations/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFolderCollaboration* | add | Add a collaboration to this folder | *addFolderCollaborationByEmail* | addByEmail | Add a collaboration to this folder | *deleteCollaboration* | delete | Delete collaboration | *getCollaborationInfo* | info | Get collaboration information | *getFolderCollaborations* | collaborations | Get information about all of the collaborations for folder | *updateCollaborationInfo* | updateInfo | Update collaboration information |=== The collaborations API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFolderCollaboration | *collaborator* | The collaborator to add | BoxCollaborator | addFolderCollaboration | *folderId* | The id of folder to add collaboration to | String | addFolderCollaboration | *role* | The role of the collaborator | Role | addFolderCollaborationByEmail | *email* | The email address of the collaborator to add | String | addFolderCollaborationByEmail | *folderId* | The id of folder to add collaboration to | String | addFolderCollaborationByEmail | *role* | The role of the collaborator | Role | deleteCollaboration | *collaborationId* | The id of comment to change | String | getCollaborationInfo | *collaborationId* | The id of collaboration | String | getFolderCollaborations | *folderId* | The id of folder to get collaborations information on | String | updateCollaborationInfo | *collaborationId* | The id of collaboration | String | updateCollaborationInfo | *info* | Collaboration information to update | Info |=== In addition to the parameters above, the collaborations API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: comments *Only producer is supported* The comments API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFile addFileComment(String fileId, String message); com.box.sdk.BoxComment changeCommentMessage(String commentId, String message); void deleteComment(String commentId); com.box.sdk.BoxComment.Info getCommentInfo(String commentId); java.util.List getFileComments(String fileId); com.box.sdk.BoxComment replyToComment(String commentId, String message); ---- The comments API is defined in the syntax as follows: ---- box:comments/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFileComment* | add | Add comment to file | *changeCommentMessage* | updateMessage | Change comment message | *deleteComment* | delete | Delete comment | *getCommentInfo* | info | Get comment information | *getFileComments* | comments | Get a list of any comments on this file | *replyToComment* | reply | Reply to a comment |=== The comments API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFileComment | *fileId* | The id of file | String | addFileComment | *message* | The comment's message | String | changeCommentMessage | *commentId* | The id of comment to change | String | changeCommentMessage | *message* | The new message for the comment | String | deleteComment | *commentId* | The id of comment to delete | String | getCommentInfo | *commentId* | The id of comment | String | getFileComments | *fileId* | The id of file | String | replyToComment | *commentId* | The id of comment to reply to | String | replyToComment | *message* | The message for the reply | String |=== In addition to the parameters above, the comments API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: event-logs *Only producer is supported* The event-logs API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.List getEnterpriseEvents(String position, java.util.Date after, java.util.Date before, com.box.sdk.BoxEvent.Type[] types); ---- The event-logs API is defined in the syntax as follows: ---- box:event-logs/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *getEnterpriseEvents* | events | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The event-logs API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | getEnterpriseEvents | *after* | The lower bound on the timestamp of the events returned | Date | getEnterpriseEvents | *before* | The upper bound on the timestamp of the events returned | Date | getEnterpriseEvents | *position* | *Optional* The starting position of the event stream. May be null in which case all events within bounds returned. | String | getEnterpriseEvents | *types* | *Optional* An optional list of event types to filter by | Type[] |=== In addition to the parameters above, the event-logs API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: events *Only consumer is supported* The events API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void listen(com.box.sdk.EventListener listener, Long startingPosition); ---- The events API is defined in the syntax as follows: ---- box:events/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *listen* | | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The events API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | listen | *startingPosition* | *Optional* The starting position of the event stream | Long |=== In addition to the parameters above, the events API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: files *Only producer is supported* The files API has 22 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void checkUpload(String fileName, String parentFolderId, Long size); com.box.sdk.BoxFile copyFile(String fileId, String destinationFolderId, String newName); com.box.sdk.Metadata createFileMetadata(String fileId, com.box.sdk.Metadata metadata, String typeName); com.box.sdk.BoxSharedLink createFileSharedLink(String fileId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFile(String fileId); void deleteFileMetadata(String fileId); void deleteFileVersion(String fileId, Integer version); java.io.OutputStream downloadFile(String fileId, java.io.OutputStream output, Long rangeStart, Long rangeEnd, com.box.sdk.ProgressListener listener); java.io.OutputStream downloadPreviousFileVersion(String fileId, Integer version, java.io.OutputStream output, com.box.sdk.ProgressListener listener); java.net.URL getDownloadURL(String fileId); com.box.sdk.BoxFile.Info getFileInfo(String fileId, String[] fields); com.box.sdk.Metadata getFileMetadata(String fileId, String typeName); java.net.URL getFilePreviewLink(String fileId); byte[] getFileThumbnail(String fileId, com.box.sdk.BoxFile.ThumbnailFileType fileType, Integer minWidth, Integer minHeight, Integer maxWidth, Integer maxHeight); java.util.Collection getFileVersions(String fileId); com.box.sdk.BoxFile moveFile(String fileId, String destinationFolderId, String newName); com.box.sdk.BoxFileVersion promoteFileVersion(String fileId, Integer version); com.box.sdk.BoxFile renameFile(String fileId, String newFileName); com.box.sdk.BoxFile updateFileInfo(String fileId, com.box.sdk.BoxFile.Info info); com.box.sdk.Metadata updateFileMetadata(String fileId, com.box.sdk.Metadata metadata); com.box.sdk.BoxFile uploadFile(String parentFolderId, java.io.InputStream content, String fileName, java.util.Date created, java.util.Date modified, Long size, Boolean check, com.box.sdk.ProgressListener listener); com.box.sdk.BoxFile uploadNewFileVersion(String fileId, java.io.InputStream fileContent, java.util.Date modified, Long fileSize, com.box.sdk.ProgressListener listener); ---- The files API is defined in the syntax as follows: ---- box:files/methodName?[parameters] ---- The 22 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *checkUpload* | canUpload | Does a pre-verification before upload, to check if the filename already exists or if there is permission to upload | *copyFile* | copy | Copy file to destination folder while optionally giving it a new name | *createFileMetadata* | createMetadata | Create metadata for file in either the global properties template or the specified template type | *createFileSharedLink* | link | Create a shared link to file | *deleteFile* | delete | Delete the file | *deleteFileMetadata* | deleteMetadata | Delete the file properties metadata | *deleteFileVersion* | deleteVersion | Delete a file version | *downloadFile* | download | Download a file | *downloadPreviousFileVersion* | downloadVersion | Download a previous version of file | *getDownloadURL* | url | Get an expiring URL for downloading a file directly from Box | *getFileInfo* | info | Get file information | *getFileMetadata* | metadata | Gets the file properties metadata | *getFilePreviewLink* | | Get an expiring URL for creating an embedded preview session | *getFileThumbnail* | thumbnail | Retrieves a thumbnail, or smaller image representation, of this file | *getFileVersions* | versions | Get any previous versions of file | *moveFile* | move | Move file to destination folder while optionally giving it a new name | *promoteFileVersion* | promoteVersion | Promote a previous version of file | *renameFile* | rename | Rename file giving it the name newName | *updateFileInfo* | updateInfo | Update file information | *updateFileMetadata* | updateMetadata | Update the file properties metadata | *uploadFile* | upload | Upload a new file to parent folder | *uploadNewFileVersion* | uploadVersion | Upload a new version of file |=== The files API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | checkUpload | *fileName* | The name to give the uploaded file | String | checkUpload | *parentFolderId* | The id of parent folder | String | checkUpload | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | copyFile | *destinationFolderId* | The id of the destination folder | String | copyFile | *fileId* | The id of file to copy | String | copyFile | *newName* | *Optional* The new name for copied file; if newName is null, the copied file has same name as the original. | String | createFileMetadata | *fileId* | The id of the file to create metadata for | String | createFileMetadata | *metadata* | The new metadata values | Metadata | createFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | createFileSharedLink | *access* | The access level of the shared link | Access | createFileSharedLink | *fileId* | The id of the file to create shared link on | String | createFileSharedLink | *permissions* | *Optional* The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFileSharedLink | *unshareDate* | *Optional* The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFile | *fileId* | The id of file to delete | String | deleteFileMetadata | *fileId* | The id of file to delete | String | deleteFileVersion | *fileId* | The id of file with version to delete | String | deleteFileVersion | *version* | The version of file to delete; initial version of file has value of 0, second version of file is 1 and so on. | Integer | downloadFile | *fileId* | The id of file | String | downloadFile | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadFile | *output* | The stream to which the file contents will be written | OutputStream | downloadFile | *rangeEnd* | *Optional* The byte offset in file at which to stop the download; if null the entire contents of file will be downloaded. | Long | downloadFile | *rangeStart* | *Optional* The byte offset in file at which to start the download; if null the entire contents of file will be downloaded. | Long | downloadPreviousFileVersion | *fileId* | The id of file | String | downloadPreviousFileVersion | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadPreviousFileVersion | *output* | The stream to which the version contents will be written | OutputStream | downloadPreviousFileVersion | *version* | The version of file to download; initial version of file has value of 0, second version of file is 1 and so on. | Integer | getDownloadURL | *fileId* | The id of file | String | getFileInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFileInfo | *fileId* | The id of file | String | getFileMetadata | *fileId* | The id of the file to retrieve metadata for | String | getFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | getFilePreviewLink | *fileId* | The id of the file to get preview link on | String | getFileThumbnail | *fileId* | The id of the file to get thumbnail | String | getFileThumbnail | *fileType* | Either PNG of JPG | ThumbnailFileType | getFileThumbnail | *maxHeight* | Maximum height | Integer | getFileThumbnail | *maxWidth* | Maximum width | Integer | getFileThumbnail | *minHeight* | Minimum height | Integer | getFileThumbnail | *minWidth* | Minimum width | Integer | getFileVersions | *fileId* | The id of file | String | moveFile | *destinationFolderId* | The id of the destination folder | String | moveFile | *fileId* | The id of file to move | String | moveFile | *newName* | *Optional* The new name of moved file; if newName is null, the moved file has same name as the original. | String | promoteFileVersion | *fileId* | The id of file | String | promoteFileVersion | *version* | The version of file to promote; initial version of file has value of 0, second version of file is 1 and so on. | Integer | renameFile | *fileId* | The id of file to rename | String | renameFile | *newFileName* | The new name of file | String | updateFileInfo | *fileId* | The id of file to update | String | updateFileInfo | *info* | The updated information | Info | updateFileMetadata | *fileId* | The id of file to delete | String | updateFileMetadata | *metadata* | The new metadata values | Metadata | uploadFile | *check* | *Optional* If the file name is already used, call the uploadNewVersion instead. | Boolean | uploadFile | *content* | A stream containing contents of the file to upload | InputStream | uploadFile | *created* | *Optional* The content created date that will be given to the uploaded file | Date | uploadFile | *fileName* | The name to give the uploaded file | String | uploadFile | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadFile | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date | uploadFile | *parentFolderId* | The id of parent folder | String | uploadFile | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *fileContent* | A stream containing contents of the file to upload | InputStream | uploadNewFileVersion | *fileId* | The id of file | String | uploadNewFileVersion | *fileSize* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadNewFileVersion | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date |=== In addition to the parameters above, the files API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: folders *Only producer is supported* The folders API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFolder copyFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String folderName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String[] path); com.box.sdk.BoxSharedLink createFolderSharedLink(String folderId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFolder(String folderId); com.box.sdk.BoxFolder getFolder(String[] path); com.box.sdk.BoxFolder.Info getFolderInfo(String folderId, String[] fields); java.util.Collection getFolderItems(String folderId, Long offset, Long limit, String[] fields); com.box.sdk.BoxFolder moveFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder renameFolder(String folderId, String newFolderName); com.box.sdk.BoxFolder updateFolderInfo(String folderId, com.box.sdk.BoxFolder.Info info); ---- The folders API is defined in the syntax as follows: ---- box:folders/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *copyFolder* | copy | Copy folder to destination folder while optionally giving it a new name | *createFolder* | create | Create a folder specified by path from parent folder with given parentFolderId, creating intermediate directories as required | *createFolderSharedLink* | link | Create a shared link to folder | *deleteFolder* | delete | Delete folder | *getFolder* | folder | Return the Box folder referenced by path | *getFolderInfo* | info | Get folder information | *getFolderItems* | items | Returns a specific range of child items in folder and specifies which fields of each item to retrieve | *moveFolder* | move | Move folder to destination folder while optionally giving it a new name | *renameFolder* | rename | Rename folder giving it the name newName | *updateFolderInfo* | updateInfo | Update folder information |=== The folders API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | copyFolder | *destinationFolderId* | The id of the destination folder | String | copyFolder | *folderId* | The id of folder to copy | String | copyFolder | *newName* | *Optional* The new name for copied folder; if newName is null, the copied folder has same name as the original. | String | createFolder | *folderName* | The name of created folder | String | createFolder | *parentFolderId* | The id of parent folder | String | createFolder | *path* | Sequence of Box folder names from parent folder to returned folder | String[] | createFolderSharedLink | *access* | The access level of the shared link | Access | createFolderSharedLink | *folderId* | The id of folder to create shared link on | String | createFolderSharedLink | *permissions* | The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFolderSharedLink | *unshareDate* | The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFolder | *folderId* | The id of folder to delete | String | getFolder | *path* | Sequence of Box folder names from root folder to returned folder | String[] | getFolderInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFolderInfo | *folderId* | The id of folder | String | getFolderItems | *fields* | *Optional* The item fields to retrieve for each child item; if null all item fields are retrieved. | String[] | getFolderItems | *folderId* | The id of folder | String | getFolderItems | *limit* | *Optional* The maximum number of children to retrieve after the offset; if null all child items are retrieved. | Long | getFolderItems | *offset* | *Optional* The index of first child item to retrieve; if null all child items are retrieved. | Long | moveFolder | *destinationFolderId* | The id of the destination folder | String | moveFolder | *folderId* | The id of folder to move | String | moveFolder | *newName* | *Optional* The new name of moved folder; if newName is null, the moved folder has same name as the original. | String | renameFolder | *folderId* | The id of folder to rename | String | renameFolder | *newFolderName* | The new name of folder | String | updateFolderInfo | *folderId* | The id of folder to update | String | updateFolderInfo | *info* | The updated information | Info |=== In addition to the parameters above, the folders API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: groups *Only producer is supported* The groups API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxGroupMembership addGroupMembership(String groupId, String userId, com.box.sdk.BoxGroupMembership.Role role); com.box.sdk.BoxGroup createGroup(String name, String provenance, String externalSyncIdentifier, String description, String invitabilityLevel, String memberViewabilityLevel); void deleteGroup(String groupId); void deleteGroupMembership(String groupMembershipId); com.box.sdk.BoxGroup.Info getGroupInfo(String groupId); com.box.sdk.BoxGroupMembership.Info getGroupMembershipInfo(String groupMembershipId); java.util.Collection getGroupMemberships(String groupId); com.box.sdk.BoxGroup updateGroupInfo(String groupId, com.box.sdk.BoxGroup.Info groupInfo); com.box.sdk.BoxGroupMembership updateGroupMembershipInfo(String groupMembershipId, com.box.sdk.BoxGroupMembership.Info info); ---- The groups API is defined in the syntax as follows: ---- box:groups/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addGroupMembership* | addMembership | Add a member to group with the specified role | *createGroup* | create | Create a new group with a specified name and optional additional parameters | *deleteGroup* | delete | Delete group | *deleteGroupMembership* | deleteMembership | Delete group membership | *getGroupInfo* | info | Get group information | *getGroupMembershipInfo* | membershipInfo | Get group membership information | *getGroupMemberships* | memberships | Get information about all of the group memberships for this group | *updateGroupInfo* | | Update group information | *updateGroupMembershipInfo* | updateMembershipInfo | Update group membership information |=== The groups API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addGroupMembership | *groupId* | The id of group | String | addGroupMembership | *role* | *Optional* The role of the user in this group. Can be null to assign the default role. | Role | addGroupMembership | *userId* | The id of user to be added to group | String | createGroup | *description* | *Optional* The description of the new group | String | createGroup | *externalSyncIdentifier* | *Optional* The external_sync_identifier of the new group | String | createGroup | *invitabilityLevel* | *Optional* The invitibility_level of the new group | String | createGroup | *memberViewabilityLevel* | *Optional* The member_viewability_level of the new group | String | createGroup | *name* | The name of the new group | String | createGroup | *provenance* | *Optional* The provenance of the new group | String | deleteGroup | *groupId* | The id of group to delete | String | deleteGroupMembership | *groupMembershipId* | The id of group membership to delete | String | getGroupInfo | *groupId* | The id of group | String | getGroupMembershipInfo | *groupMembershipId* | The id of group membership | String | getGroupMemberships | *groupId* | The id of group | String | updateGroupInfo | *groupId* | The id of group to update | String | updateGroupInfo | *groupInfo* | The updated information | Info | updateGroupMembershipInfo | *groupMembershipId* | The id of group membership to update | String | updateGroupMembershipInfo | *info* | The updated information | Info |=== In addition to the parameters above, the groups API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: search *Only producer is supported* The search API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.Collection searchFolder(String folderId, String query); ---- The search API is defined in the syntax as follows: ---- box:search/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *searchFolder* | search | Search folder and all descendant folders using the given query |=== The search API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | searchFolder | *folderId* | The id of folder searched | String | searchFolder | *query* | The search query | String |=== In addition to the parameters above, the search API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: tasks *Only producer is supported* The tasks API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxTask addAssignmentToTask(String taskId, com.box.sdk.BoxUser assignTo); com.box.sdk.BoxTask addFileTask(String fileId, com.box.sdk.BoxTask.Action action, java.util.Date dueAt, String message); void deleteTask(String taskId); void deleteTaskAssignment(String taskAssignmentId); java.util.List getFileTasks(String fileId); com.box.sdk.BoxTaskAssignment.Info getTaskAssignmentInfo(String taskAssignmentId); java.util.List getTaskAssignments(String taskId); com.box.sdk.BoxTask.Info getTaskInfo(String taskId); com.box.sdk.BoxTask updateTaskInfo(String taskId, com.box.sdk.BoxTask.Info info); ---- The tasks API is defined in the syntax as follows: ---- box:tasks/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addAssignmentToTask* | addAssignment | Add assignment for task | *addFileTask* | add | Add task to file | *deleteTask* | delete | Delete task | *deleteTaskAssignment* | deleteAssignment | Delete task assignment | *getFileTasks* | tasks | Get a list of any tasks on file | *getTaskAssignmentInfo* | assignmentInfo | Get task assignment information | *getTaskAssignments* | assignments | Get a list of any assignments for task | *getTaskInfo* | info | Get task information | *updateTaskInfo* | updateInfo | Update task information |=== The tasks API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addAssignmentToTask | *assignTo* | The user to assign to task | BoxUser | addAssignmentToTask | *taskId* | The id of task to add assignment for | String | addFileTask | *action* | The action the task assignee will be prompted to do | Action | addFileTask | *dueAt* | The day at which this task is due | Date | addFileTask | *fileId* | The id of file to add task to | String | addFileTask | *message* | *Optional* An optional message to include with the task | String | deleteTask | *taskId* | The id of task to delete | String | deleteTaskAssignment | *taskAssignmentId* | The id of task assignment to delete | String | getFileTasks | *fileId* | The id of file | String | getTaskAssignmentInfo | *taskAssignmentId* | The id of task assignment | String | getTaskAssignments | *taskId* | The id of task | String | getTaskInfo | *taskId* | The id of task | String | updateTaskInfo | *info* | The updated information | Info | updateTaskInfo | *taskId* | The id of task | String |=== In addition to the parameters above, the tasks API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: users *Only producer is supported* The users API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.EmailAlias addUserEmailAlias(String userId, String email); com.box.sdk.BoxUser createAppUser(String name, com.box.sdk.CreateUserParams params); com.box.sdk.BoxUser createEnterpriseUser(String login, String name, com.box.sdk.CreateUserParams params); void deleteUser(String userId, boolean notifyUser, boolean force); void deleteUserEmailAlias(String userId, String emailAliasId); java.util.List getAllEnterpriseOrExternalUsers(String filterTerm, String[] fields); java.util.Collection getUserEmailAlias(String userId); com.box.sdk.BoxUser.Info getUserInfo(String userId); com.box.sdk.BoxFolder.Info moveFolderToUser(String userId, String sourceUserId); com.box.sdk.BoxUser updateUserInfo(String userId, com.box.sdk.BoxUser.Info info); ---- The users API is defined in the syntax as follows: ---- box:users/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addUserEmailAlias* | addEmailAlias | Add a new email alias to user's account | *createAppUser* | create | Provision a new app user in an enterprise with additional user information using Box Developer Edition | *createEnterpriseUser* | create | Provision a new user in an enterprise with additional user information | *deleteUser* | delete | Delete user from an enterprise account | *deleteUserEmailAlias* | deleteEmailAlias | Delete an email alias from user's account | *getAllEnterpriseOrExternalUsers* | users | Get any managed users that match the filter term as well as any external users that match the filter term | *getUserEmailAlias* | emailAlias | Get a collection of all the email aliases for user | *getUserInfo* | info | Get user information | *moveFolderToUser* | | Move root folder for specified user to current user | *updateUserInfo* | updateInfo | Update user information |=== The users API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addUserEmailAlias | *email* | The email address to add as an alias | String | addUserEmailAlias | *userId* | The id of user | String | createAppUser | *name* | The name of the user | String | createAppUser | *params* | *Optional* Additional user information | CreateUserParams | createEnterpriseUser | *login* | The email address the user will use to login | String | createEnterpriseUser | *name* | The name of the user | String | createEnterpriseUser | *params* | *Optional* Additional user information | CreateUserParams | deleteUser | *force* | Whether or not this user should be deleted even if they still own files | Boolean | deleteUser | *notifyUser* | Whether or not to send an email notification to the user that their account has been deleted | Boolean | deleteUser | *userId* | The id of user to delete | String | deleteUserEmailAlias | *emailAliasId* | The id of the email alias to delete | String | deleteUserEmailAlias | *userId* | The id of user | String | getAllEnterpriseOrExternalUsers | *fields* | *Optional* The fields to retrieve. Leave this out for the standard fields. | String[] | getAllEnterpriseOrExternalUsers | *filterTerm* | *Optional* The filter term to lookup users by (login for external, login or name for managed); if null all managed users are returned. | String | getUserEmailAlias | *userId* | The id of user | String | getUserInfo | *userId* | The id of user | String | moveFolderToUser | *sourceUserId* | The user id of the user whose files will be the source for this operation | String | moveFolderToUser | *userId* | The id of user | String | updateUserInfo | *info* | The updated information | Info | updateUserInfo | *userId* | The id of user to update | String |=== In addition to the parameters above, the users API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. // endpoint options: END == Samples The following route uploads new files to the user's root folder: [source,java] ---- from(""file:..."") .to(""box://files/upload/inBody=fileUploadRequest""); ---- The following route polls user's account for updates: [source,java] ---- from(""box://events/listen?startingPosition=-1"") .to(""bean:blah""); ---- The following route uses a producer with dynamic header options. The *fileId* property has the Box file id and the *output* property has the output stream of the file contents, so they are assigned to the *CamelBox.fileId* header and *CamelBox.output* header respectively as follows: [source,java] ---- from(""direct:foo"") .setHeader(""CamelBox.fileId"", header(""fileId"")) .setHeader(""CamelBox.output"", header(""output"")) .to(""box://files/download"") .to(""file://...""); ---- === More information See more details at the Box API reference: https://developer.box.com/reference include::camel-spring-boot::page$box-starter.adoc[] ",12350,True,2565.5789821663884,median " // Use these for links to issue and pulls. Note issues and pulls redirect one to // each other on Github, so don't worry too much on using the right prefix. :issue: https://github.com/elastic/beats/issues/ :pull: https://github.com/elastic/beats/pull/ //////////////////////////////////////////////////////////// // Template, add newest changes here === Beats version HEAD https://github.com/elastic/beats/compare/v5.0.0...master[Check the HEAD diff] ==== Breaking changes *Affecting all Beats* *Metricbeat* *Packetbeat* *Topbeat* *Filebeat* *Winlogbeat* ==== Bugfixes *Affecting all Beats* *Metricbeat* - Calculate the fsstat values per mounting point, and not filesystem. {pull}2777[2777] - Fix `system.process.start_time` on Windows. {pull}2848[2848] *Packetbeat* *Topbeat* *Filebeat* - Fix registry cleanup issue when files falling under ignore_older after restart. {issue}2818[2818] *Winlogbeat* ==== Added *Affecting all Beats* - Add add_cloud_metadata processor for collecting cloud provider metadata. {pull}2728[2728] *Metricbeat* - Add experimental filebeat metricset in the beats module. {pull}2297[2297] - Add experimental libbeat metricset in the beats module. {pull}2339[2339] - Add experimental docker module. Provided by Ingensi and @douaejeouit based on dockbeat. *Packetbeat* - Define `client_geoip.location` as geo_point in the mappings to be used by the GeoIP processor in the Ingest Node pipeline. {pull}2795[2795] *Topbeat* *Filebeat* - Add command line option -once to run filebeat only once and then close. {pull}2456[2456] *Winlogbeat* - Add `event_logs.batch_read_size` configuration option. {pull}2641[2641] ==== Deprecated *Affecting all Beats* *Metricbeat* *Packetbeat* *Topbeat* *Filebeat* *Winlogbeat* //////////////////////////////////////////////////////////// include::libbeat/docs/release-notes/5.0.0.asciidoc[] [[release-notes-5.0.0-ga]] === Beats version 5.0.0-GA https://github.com/elastic/beats/compare/v5.0.0-rc1...v5.0.0[View commits] The list below covers the changes between 5.0.0-rc1 and 5.0.0 GA only. ==== Bugfixes *Affecting all Beats* - Fix kafka output re-trying batches with too large events. {issue}2735[2735] - Fix kafka output protocol error if `version: 0.10` is configured. {issue}2651[2651] - Fix kafka output connection closed by broker on SASL/PLAIN. {issue}2717[2717] *Metricbeat* - Fix high CPU usage on macOS when encountering processes with long command lines. {issue}2747[2747] - Fix high value of `system.memory.actual.free` and `system.memory.actual.used`. {issue}2653[2653] - Change several `OpenProcess` calls on Windows to request the lowest possible access provilege. {issue}1897[1897] - Fix system.memory.actual.free high value on Windows. {issue}2653[2653] *Filebeat* - Fix issue when clean_removed and clean_inactive were used together that states were not directly removed from the registry. - Fix issue where upgrading a 1.x registry file resulted in duplicate state entries. {pull}2792[2792] ==== Added *Affecting all Beats* - Add beat.version fields to all events. [[release-notes-5.0.0-rc1]] === Beats version 5.0.0-rc1 https://github.com/elastic/beats/compare/v5.0.0-beta1...v5.0.0-rc1[View commits] ==== Breaking changes *Affecting all Beats* - A dynamic mapping rule is added to the default Elasticsearch template to treat strings as keywords by default. {pull}2688[2688] ==== Bugfixes *Affecting all Beats* - Make sure Beats sent always float values when they are defined as float by sending 5.00000 instead of 5. {pull}2627[2627] - Fix ignoring all fields from drop_fields in case the first field is unknown. {pull}2685[2685] - Fix dynamic configuration int/uint to float type conversion. {pull}2698[2698] - Fix primitive types conversion if values are read from environment variables. {pull}2698[2698] *Metricbeat* - Fix default configuration file on Windows to not enabled the `load` metricset. {pull}2632[2632] *Packetbeat* - Fix the `bpf_filter` setting. {issue}2660[2660] *Filebeat* - Fix input buffer on encoding problem. {pull}2416[2416] ==== Deprecated *Affecting all Beats* - Setting `port` has been deprecated in Redis and Logstash outputs. {pull}2620[2620] [[release-notes-5.0.0-beta1]] === Beats version 5.0.0-beta1 https://github.com/elastic/beats/compare/v5.0.0-alpha5...v5.0.0-beta1[View commits] ==== Breaking changes *Affecting all Beats* - Change Elasticsearch output index configuration to be based on format strings. If index has been configured, no date will be appended anymore to the index name. {pull}2119[2119] - Replace `output.kafka.use_type` by `output.kafka.topic` accepting a format string. {pull}2188[2188] - If the path specified by the `-c` flag is not absolute and `-path.config` is not specified, it is considered relative to the current working directory. {pull}2245[2245] - rename `tls` configurations section to `ssl`. {pull}2330[2330] - rename `certificate_key` configuration to `key`. {pull}2330[2330] - replace `tls.insecure` with `ssl.verification_mode` setting. {pull}2330[2330] - replace `tls.min/max_version` with `ssl.supported_protocols` setting requiring full protocol name. {pull}2330[2330] *Metricbeat* - Change field type system.process.cpu.start_time from keyword to date. {issue}1565[1565] - redis/info metricset fields were renamed up according to the naming conventions. *Packetbeat* - Group HTTP fields under `http.request` and `http.response` {pull}2167[2167] - Export `http.request.body` and `http.response.body` when configured under `include_body_for` {pull}2167[2167] - Move `ignore_outgoing` config to `packetbeat.ignore_outgoing` {pull}2393[2393] *Filebeat* - Set close_inactive default to 5 minutes (was 1 hour before) - Set clean_removed and close_removed to true by default ==== Bugfixes *Affecting all Beats* - Fix logstash output handles error twice when asynchronous sending fails. {pull}2441[2441] - Fix Elasticsearch structured error response parsing error. {issue}2229[2229] - Fixed the run script to allow the overriding of the configuration file. {issue}2171[2171] - Fix logstash output crash if no hosts are configured. {issue}2325[2325] - Fix array value support in -E CLI flag. {pull}2521[2521] - Fix merging array values if -c CLI flag is used multiple times. {pull}2521[2521] - Fix beats failing to start due to invalid duplicate key error in configuration file. {pull}2521[2521] - Fix panic on non writable logging directory. {pull}2571[2571] *Metricbeat* - Fix module filters to work properly with drop_event filter. {issue}2249[2249] *Packetbeat* - Fix mapping for some Packetbeat flow metrics that were not marked as being longs. {issue}2177[2177] - Fix handling of messages larger than the maximum message size (10MB). {pull}2470[2470] *Filebeat* - Fix processor failure in Filebeat when using regex, contain, or equals with the message field. {issue}2178[2178] - Fix async publisher sending empty events {pull}2455[2455] - Fix potential issue with multiple harvester per file on large file numbers or slow output {pull}2541[2541] *Winlogbeat* - Fix corrupt registry file that occurs on power loss by disabling file write caching. {issue}2313[2313] ==== Added *Affecting all Beats* - Add script to generate the Kibana index-pattern from fields.yml. {pull}2122[2122] - Enhance Redis output key selection based on format string. {pull}2169[2169] - Configurable Redis `keys` using filters and format strings. {pull}2169[2169] - Add format string support to `output.kafka.topic`. {pull}2188[2188] - Add `output.kafka.topics` for more advanced kafka topic selection per event. {pull}2188[2188] - Add support for Kafka 0.10. {pull}2190[2190] - Add SASL/PLAIN authentication support to kafka output. {pull}2190[2190] - Make Kafka metadata update configurable. {pull}2190[2190] - Add Kafka version setting (optional) enabling kafka broker version support. {pull}2190[2190] - Add Kafka message timestamp if at least version 0.10 is configured. {pull}2190[2190] - Add configurable Kafka event key setting. {pull}2284[2284] - Add settings for configuring the kafka partitioning strategy. {pull}2284[2284] - Add partitioner settings `reachable_only` to ignore partitions not reachable by network. {pull}2284[2284] - Enhance contains condition to work on fields that are arrays of strings. {issue}2237[2237] - Lookup the configuration file relative to the `-path.config` CLI flag. {pull}2245[2245] - Re-write import_dashboards.sh in Golang. {pull}2155[2155] - Update to Go 1.7. {pull}2306[2306] - Log total non-zero internal metrics on shutdown. {pull}2349[2349] - Add support for encrypted private key files by introducing `ssl.key_passphrase` setting. {pull}2330[2330] - Add experimental symlink support with `symlinks` config {pull}2478[2478] - Improve validation of registry file on startup. *Metricbeat* - Use the new scaled_float Elasticsearch type for the percentage values. {pull}2156[2156] - Add experimental cgroup metrics to the system/process MetricSet. {pull}2184[2184] - Added a PostgreSQL module. {pull}2253[2253] - Improve mapping by converting half_float to scaled_float and integers to long. {pull}2430[2430] - Add experimental haproxy module. {pull}2384[2384] - Add Kibana dashboard for cgroups data {pull}2555[2555] *Packetbeat* - Add Cassandra protocol analyzer to Packetbeat. {pull}1959[1959] - Match connections with IPv6 addresses to processes {pull}2254[2254] - Add IP address to -devices command output {pull}2327[2327] - Add configuration option for the maximum message size. Used to be hard-coded to 10 MB. {pull}2470[2470] *Filebeat* - Introduce close_timeout harvester options {issue}1926[1926] - Strip BOM from first message in case of BOM files {issue}2351[2351] - Add harvester_limit option {pull}2417[2417] ==== Deprecated *Affecting all Beats* - Topology map is deprecated. This applies to the settings: refresh_topology_freq, topology_expire, save_topology, host_topology, password_topology, db_topology. [[release-notes-5.0.0-alpha5]] === Beats version 5.0.0-alpha5 https://github.com/elastic/beats/compare/v5.0.0-alpha4...v5.0.0-alpha5[View commits] ==== Breaking changes *Affecting all Beats* - Rename the `filters` section to `processors`. {pull}1944[1944] - Introduce the condition with `when` in the processor configuration. {pull}1949[1949] - The Elasticsearch template is now loaded by default. {pull}1993[1993] - The Redis output `index` setting is renamed to `key`. `index` still works but it's deprecated. {pull}2077[2077] - The undocumented file output `index` setting was removed. Use `filename` instead. {pull}2077[2077] *Metricbeat* - Create a separate metricSet for load under the system module and remove load information from CPU stats. {pull}2101[2101] - Add `system.load.norm.1`, `system.load.norm.5` and `system.load.norm.15`. {pull}2101[2101] - Add threads fields to mysql module. {pull}2484[2484] *Packetbeat* - Set `enabled` ` in `packetbeat.protocols.icmp` configuration to `true` by default. {pull}1988[1988] ==== Bugfixes *Affecting all Beats* - Fix sync publisher `PublishEvents` return value if client is closed concurrently. {pull}2046[2046] *Metricbeat* - Do not send zero values when no value was present in the source. {issue}1972[1972] *Filebeat* - Fix potential data loss between Filebeat restarts, reporting unpublished lines as published. {issue}2041[2041] - Fix open file handler issue. {issue}2028[2028] {pull}2020[2020] - Fix filtering of JSON events when using integers in conditions. {issue}2038[2038] *Winlogbeat* - Fix potential data loss between Winlogbeat restarts, reporting unpublished lines as published. {issue}2041[2041] ==== Added *Affecting all Beats* - Periodically log internal metrics. {pull}1955[1955] - Add enabled setting to all output modules. {pull}1987[1987] - Command line flag `-c` can be used multiple times. {pull}1985[1985] - Add OR/AND/NOT to the condition associated with the processors. {pull}1983[1983] - Add `-E` CLI flag for overwriting single config options via command line. {pull}1986[1986] - Choose the mapping template file based on the Elasticsearch version. {pull}1993[1993] - Check stdout being available when console output is configured. {issue}2035[2035] *Metricbeat* - Add pgid field to process information. {pull} 2021[2021] *Packetbeat* - Add enabled setting to Packetbeat protocols. {pull}1988[1988] - Add enabled setting to Packetbeat network flows configuration. {pull}1988[1988] *Filebeat* - Introduce `close_removed` and `close_renamed` harvester options. {issue}1600[1600] - Introduce `close_eof` harvester option. {issue}1600[1600] - Add `clean_removed` and `clean_inactive` config option. {issue}1600[1600] ==== Deprecated *Filebeat* - Deprecate `close_older` option and replace it with `close_inactive`. {issue}2051[2051] - Deprecate `force_close_files` option and replace it with `close_removed` and `close_renamed`. {issue}1600[1600] [[release-notes-5.0.0-alpha4]] === Beats version 5.0.0-alpha4 https://github.com/elastic/beats/compare/v5.0.0-alpha3...v5.0.0-alpha4[View commits] ==== Breaking changes *Affecting all Beats* - The topology_expire option of the Elasticserach output was removed. {pull}1907[1907] *Filebeat* - Stop following symlink. Symlinks are now ignored: {pull}1686[1686] ==== Bugfixes *Affecting all Beats* - Reset backoff factor on partial ACK. {issue}1803[1803] - Fix beats load balancer deadlock if max_retries: -1 or publish_async is enabled in filebeat. {issue}1829[1829] - Fix logstash output with pipelining mode enabled not reconnecting. {issue}1876[1876] - Empty configuration sections become merge-able with variables containing full path. {pull}1900[1900] - Fix error message about required fields missing not printing the missing field name. {pull}1900[1900] *Metricbeat* - Fix the CPU values returned for each core. {issue}1863[1863] *Packetbeat* - Add missing nil-check to memcached GapInStream handler. {issue}1162[1162] - Fix NFSv4 Operation returning the first found first-class operation available in compound requests. {pull}1821[1821] - Fix TCP overlapping segments not being handled correctly. {pull}1898[1898] *Winlogbeat* - Fix issue with rendering forwarded event log records. {pull}1891[1891] ==== Added *Affecting all Beats* - Improve error message if compiling regular expression from config files fails. {pull}1900[1900] - Compression support in the Elasticsearch output. {pull}1835[1835] *Metricbeat* - Add MongoDB module. {pull}1837[1837] [[release-notes-5.0.0-alpha3]] === Beats version 5.0.0-alpha3 https://github.com/elastic/beats/compare/v5.0.0-alpha2...v5.0.0-alpha3[View commits] ==== Breaking changes *Affecting all Beats* - All configuration settings under `shipper:` are moved to be top level configuration settings. I.e. `shipper.name:` becomes `name:` in the configuration file. {pull}1570[1570] *Topbeat* - Topbeat is replaced by Metricbeat. *Filebeat* - The state for files which fall under ignore_older is not stored anymore. This has the consequence, that if a file which fell under ignore_older is updated, the whole file will be crawled. ==== Bugfixes *Winlogbeat* - Adding missing argument to the ""Stop processing"" log message. {pull}1590[1590] ==== Added *Affecting all Beats* - Add conditions to generic filtering. {pull}1623[1623] *Metricbeat* - First public release, containing the following modules: apache, mysql, nginx, redis, system, and zookeeper. *Filebeat* - The registry format was changed to an array instead of dict. The migration to the new format will happen automatically at the first startup. {pull}1703[1703] ==== Deprecated *Affecting all Beats* - The support for doing GeoIP lookups is deprecated and will be removed in version 6.0. {pull}1601[1601] [[release-notes-5.0.0-alpha2]] === Beats version 5.0.0-alpha2 https://github.com/elastic/beats/compare/v5.0.0-alpha1...v5.0.0-alpha2[View commits] ==== Breaking changes *Affecting all Beats* - On DEB/RPM installations, the binary files are now found under `/usr/share/{{beat_name}}/bin`, not in `/usr/bin`. {pull}1385[1385] - The logs are written by default to self rotating files, instead of syslog. {pull}1371[1371] - Remove deprecated `host` option from elasticsearch, logstash and redis outputs. {pull}1474[1474] *Packetbeat* - Configuration of redis topology support changed. {pull}1353[1353] - Move all Packetbeat configuration options under the packetbeat namespace {issue}1417[1417] *Filebeat* - Default location for the registry file was changed to be `data/registry` from the binary directory, rather than `.filebeat` in the current working directory. This affects installations for zip/tar.gz/source, the location for DEB and RPM packages stays the same. {pull}1373[1373] ==== Bugfixes *Affecting all Beats* - Drain response buffers when pipelining is used by Redis output. {pull}1353[1353] - Unterminated environment variable expressions in config files will now cause an error {pull}1389[1389] - Fix issue with the automatic template loading when Elasticsearch is not available on Beat start. {issue}1321[1321] - Fix bug affecting -cpuprofile, -memprofile, and -httpprof CLI flags {pull}1415[1415] - Fix race when multiple outputs access the same event with logstash output manipulating event {issue}1410[1410] {pull}1428[1428] - Seed random number generator using crypto.rand package. {pull}1503{1503] - Fix beats hanging in -configtest {issue}1213[1213] - Fix kafka log message output {pull}1516[1516] *Filebeat* - Improvements in registrar dealing with file rotation. {pull}1281[1281] - Fix issue with JSON decoding where `@timestamp` or `type` keys with the wrong type could cause Filebeat to crash. {issue}1378[1378] - Fix issue with JSON decoding where values having `null` as values could crash Filebeat. {issue}1466[1466] - Multiline reader normalizing newline to use `\\n`. {pull}1552[1552] *Winlogbeat* - Fix panic when reading messages larger than 32K characters on Windows XP and 2003. {pull}1498[1498] - Fix panic that occurs when reading a large events on Windows Vista and newer. {pull}1499[1499] ==== Added *Affecting all Beats* - Add support for TLS to Redis output. {pull}1353[1353] - Add SOCKS5 proxy support to Redis output. {pull}1353[1353] - Failover and load balancing support in redis output. {pull}1353[1353] - Multiple-worker per host support for redis output. {pull}1353[1353] - Added ability to escape `${x}` in config files to avoid environment variable expansion {pull}1389[1389] - Configuration options and CLI flags for setting the home, data and config paths. {pull}1373[1373] - Configuration options and CLI flags for setting the default logs path. {pull}1437[1437] - Update to Go 1.6.2 {pull}1447[1447] - Add Elasticsearch template files compatible with Elasticsearch 2.x. {pull}1501[1501] - Add scripts for managing the dashboards of a single Beat {pull}1359[1359] *Packetbeat* - Fix compile issues for OpenBSD. {pull}1347[1347] *Topbeat* - Updated elastic/gosigar version so Topbeat can compile on OpenBSD. {pull}1403[1403] [[release-notes-5.0.0-alpha1]] === Beats version 5.0.0-alpha1 https://github.com/elastic/beats/compare/v1.2.0...v5.0.0-alpha1[View commits] ==== Breaking changes *libbeat* - Run function to start a Beat now returns an error instead of directly exiting. {pull}771[771] - The method signature of HandleFlags() was changed to allow returning an error {pull}1249[1249] - Require braces for environment variable expansion in config files {pull}1304[1304] *Packetbeat* - Rename output fields in the dns package. Former flag `recursion_allowed` becomes `recursion_available`. {pull}803[803] Former SOA field `ttl` becomes `minimum`. {pull}803[803] - The fully qualified domain names which are part of output fields values of the dns package now terminate with a dot. {pull}803[803] - Remove the count field from the exported event {pull}1210[1210] *Topbeat* - Rename `proc.cpu.user_p` with `proc.cpu.total_p` as it includes CPU time spent in kernel space {pull}631[631] - Remove `count` field from the exported fields {pull}1207[1207] - Rename `input` top level config option to `topbeat` *Filebeat* - Scalar values in used in the `fields` configuration setting are no longer automatically converted to strings. {pull}1092[1092] - Count field was removed from event as not used in filebeat {issue}778[778] *Winlogbeat* - The `message_inserts` field was replaced with the `event_data` field {issue}1053[1053] - The `category` field was renamed to `task` to better align with the Windows Event Log API naming {issue}1053[1053] - Remove the count field from the exported event {pull}1218[1218] ==== Bugfixes *Affecting all Beats* - Logstash output will not retry events that are not JSON-encodable {pull}927[927] *Packetbeat* - Create a proper BPF filter when ICMP is the only enabled protocol {issue}757[757] - Check column length in pgsql parser. {issue}565[565] - Harden pgsql parser. {issue}565[565] *Topbeat* - Fix issue with `cpu.system_p` being greater than 1 on Windows {pull}1128[1128] *Filebeat* - Stop filebeat if started without any prospectors defined or empty prospectors {pull}644[644] {pull}647[647] - Improve shutdown of crawler and prospector to wait for clean completion {pull}720[720] - Omit `fields` from Filebeat events when null {issue}899[899] *Winlogbeat* ==== Added *Affecting all Beats* - Update builds to Golang version 1.6 - Add option to Elasticsearch output to pass http parameters in index operations {issue}805[805] - Improve Logstash and Elasticsearch backoff behavior. {pull}927[927] - Add experimental Kafka output. {pull}942[942] - Add config file option to configure GOMAXPROCS. {pull}969[969] - Improve shutdown handling in libbeat. {pull}1075[1075] - Add `fields` and `fields_under_root` options under the `shipper` configuration {pull}1092[1092] - Add the ability to use a SOCKS5 proxy with the Logstash output {issue}823[823] - The `-configtest` flag will now print ""Config OK"" to stdout on success {pull}1249[1249] *Packetbeat* - Change the DNS library used throughout the dns package to github.com/miekg/dns. {pull}803[803] - Add support for NFS v3 and v4. {pull}1231[1231] - Add support for EDNS and DNSSEC. {pull}1292[1292] *Topbeat* - Add `username` to processes {pull}845[845] *Filebeat* - Add the ability to set a list of tags for each prospector {pull}1092[1092] - Add JSON decoding support {pull}1143[1143] *Winlogbeat* - Add caching of event metadata handles and the system render context for the wineventlog API {pull}888[888] - Improve config validation by checking for unknown top-level YAML keys. {pull}1100[1100] - Add the ability to set tags, fields, and fields_under_root as options for each event log {pull}1092[1092] - Add additional data to the events published by Winlogbeat. The new fields are `activity_id`, `event_data`, `keywords`, `opcode`, `process_id`, `provider_guid`, `related_activity_id`, `task`, `thread_id`, `user_data`, and `version`. {issue}1053[1053] - Add `event_id`, `level`, and `provider` configuration options for filtering events {pull}1218[1218] - Add `include_xml` configuration option for including the raw XML with the event {pull}1218[1218] ==== Known issues * All Beats can hang or panic on shutdown if the next server in the pipeline (e.g. Elasticsearch or Logstash) is not reachable. {issue}1319[1319] * When running the Beats as a service on Windows, you need to manually load the Elasticsearch mapping template. {issue}1315[1315] * The ES template automatic load doesn't work if Elasticsearch is not available when the Beat is starting. {issue}1321[1321] [[release-notes-1.3.1]] === Beats version 1.3.1 https://github.com/elastic/beats/compare/v1.3.0...v1.3.1[View commits] ==== Bugfixes *Filebeat* - Fix a concurrent bug on filebeat startup with a large number of prospectors defined. {pull}2509[2509] *Packetbeat* - Fix description for the -I CLI flag. {pull}2480[2480] *Winlogbeat* - Fix corrupt registry file that occurs on power loss by disabling file write caching. {issue}2313[2313] [[release-notes-1.3.0]] === Beats version 1.3.0 https://github.com/elastic/beats/compare/v1.2.3...v1.3.0[View commits] ==== Deprecated *Filebeat* - Undocumented support for following symlinks is deprecated. Filebeat will not follow symlinks in version 5.0. {pull}1767[1767] ==== Bugfixes *Affecting all Beats* - Fix beats load balancer deadlock if `max_retries: -1` or `publish_async` is enabled in filebeat. {issue}1829[1829] - Fix output modes backoff counter reset. {issue}1803[1803] {pull}1814[1814] {pull}1818[1818] - Set logstash output default bulk_max_size to 2048. {issue}1662[1662] - Seed random number generator using crypto.rand package. {pull}1503[1503] - Check stdout being available when console output is configured. {issue}2063[2063] *Packetbeat* - Add missing nil-check to memcached GapInStream handler. {issue}1162[1162] - Fix NFSv4 Operation returning the first found first-class operation available in compound requests. {pull}1821[1821] - Fix TCP overlapping segments not being handled correctly. {pull}1917[1917] ==== Added *Affecting all Beats* - Updated to Go 1.7 [[release-notes-1.2.3]] === Beats version 1.2.3 https://github.com/elastic/beats/compare/v1.2.2...v1.2.3[View commits] ==== Bugfixes *Topbeat* - Fix high CPU usage when using filtering under Windows. {pull}1598[1598] *Filebeat* - Fix rotation issue with ignore_older. {issue}1528[1528] *Winlogbeat* - Fix panic when reading messages larger than 32K characters on Windows XP and 2003. {pull}1498[1498] ==== Added *Filebeat* - Prevent file opening for files which reached ignore_older. {pull}1649[1649] [[release-notes-1.2.2]] === Beats version 1.2.2 https://github.com/elastic/beats/compare/v1.2.0...v1.2.2[View commits] ==== Bugfixes *Affecting all Beats* - Fix race when multiple outputs access the same event with Logstash output manipulating event. {issue}1410[1410] - Fix go-daemon (supervisor used in init scripts) hanging when executed over SSH. {issue}1394[1394] *Filebeat* - Improvements in registrar dealing with file rotation. {issue}1281[1281] [[release-notes-1.2.1]] === Beats version 1.2.1 https://github.com/elastic/beats/compare/v1.2.0...v1.2.1[View commits] ==== Breaking changes *Affecting all Beats* - Require braces for environment variable expansion in config files {pull}1304[1304] - Removed deprecation warning for the Redis output. {pull}1282[1282] *Topbeat* - Fixed name of the setting `stats.proc` to `stats.process` in the default configuration file. {pull}1343[1343] - Fix issue with cpu.system_p being greater than 1 on Windows {pull}1128[1128] ==== Added *Topbeat* - Add username to processes {pull}845[845] [[release-notes-1.2.0]] === Beats version 1.2.0 https://github.com/elastic/beats/compare/v1.1.2...v1.2.0[View commits] ==== Breaking changes *Filebeat* - Default config for ignore_older is now infinite instead of 24h, means ignore_older is disabled by default. Use close_older to only close file handlers. ==== Bugfixes *Packetbeat* - Split real_ip_header value when it contains multiple IPs {pull}1241[1241] *Winlogbeat* - Fix invalid `event_id` on Windows XP and Windows 2003 {pull}1227[1227] ==== Added *Affecting all Beats* - Add ability to override configuration settings using environment variables {issue}114[114] - Libbeat now always exits through a single exit method for proper cleanup and control {pull}736[736] - Add ability to create Elasticsearch mapping on startup {pull}639[639] *Topbeat* - Add the command line used to start processes {issue}533[533] *Filebeat* - Add close_older configuration option to complete ignore_older https://github.com/elastic/filebeat/issues/181[181] [[release-notes-1.1.2]] === Beats version 1.1.2 https://github.com/elastic/beats/compare/v1.1.1...v1.1.2[View commits] ==== Bugfixes *Filebeat* - Fix registrar bug for rotated files {pull}1010[1010] [[release-notes-1.1.1]] === Beats version 1.1.1 https://github.com/elastic/beats/compare/v1.1.0...v1.1.1[View commits] ==== Bugfixes *Affecting all Beats* - Fix logstash output loop hanging in infinite loop on too many output errors. {pull}944[944] - Fix critical bug in filebeat and winlogbeat potentially dropping events. {pull}953[953] [[release-notes-1.1.0]] === Beats version 1.1.0 https://github.com/elastic/beats/compare/v1.0.1...v1.1.0[View commits] ==== Bugfixes *Affecting all Beats* - Fix logging issue with file based output where newlines could be misplaced during concurrent logging {pull}650[650] - Reduce memory usage by separate queue sizes for single events and bulk events. {pull}649[649] {issue}516[516] - Set default default bulk_max_size value to 2048 {pull}628[628] *Packetbeat* - Fix setting direction to out and use its value to decide when dropping events if ignore_outgoing is enabled {pull}557[557] - Fix logging issue with file-based output where newlines could be misplaced during concurrent logging {pull}650[650] - Reduce memory usage by having separate queue sizes for single events and bulk events. {pull}649[649] {issue}516[516] - Set default bulk_max_size value to 2048 {pull}628[628] - Fix logstash window size of 1 not increasing. {pull}598[598] *Packetbeat* - Fix the condition that determines whether the direction of the transaction is set to ""outgoing"". Packetbeat uses the direction field to determine which transactions to drop when dropping outgoing transactions. {pull}557[557] - Allow PF_RING sniffer type to be configured using pf_ring or pfring {pull}671[671] *Filebeat* - Set spool_size default value to 2048 {pull}628[628] ==== Added *Affecting all Beats* - Add include_fields and drop_fields as part of generic filtering {pull}1120[1120] - Make logstash output compression level configurable. {pull}630[630] - Some publisher options refactoring in libbeat {pull}684[684] - Move event preprocessor applying GeoIP to packetbeat {pull}772[772] *Packetbeat* - Add support for capturing DNS over TCP network traffic. {pull}486[486] {pull}554[554] *Topbeat* - Group all CPU usage per core statistics and export them optionally if cpu_per_core is configured {pull}496[496] *Filebeat* - Add multiline support for combining multiple related lines into one event. {issue}461[461] - Add `exclude_lines` and `include_lines` options for regexp based line filtering. {pull}430[430] - Add `exclude_files` configuration option. {pull}563[563] - Add experimental option to enable filebeat publisher pipeline to operate asynchonrously {pull}782[782] *Winlogbeat* - First public release of Winlogbeat [[release-notes-1.0.1]] === Beats version 1.0.1 https://github.com/elastic/beats/compare/v1.0.0...v1.0.1[Check 1.0.1 diff] ==== Bugfixes *Filebeat* - Fix force_close_files in case renamed file appeared very fast. https://github.com/elastic/filebeat/pull/302[302] *Packetbeat* - Improve MongoDB message correlation. {issue}377[377] - Improve redis parser performance. {issue}442[422] - Fix panic on nil in redis protocol parser. {issue}384[384] - Fix errors redis parser when messages are split in multiple TCP segments. {issue}402[402] - Fix errors in redis parser when length prefixed strings contain sequences of CRLF. {issue}#402[402] - Fix errors in redis parser when dealing with nested arrays. {issue}402[402] [[release-notes-1.0.0]] === Beats version 1.0.0 https://github.com/elastic/beats/compare/1.0.0-rc2...1.0.0[Check 1.0.0 diff] ==== Breaking changes *Topbeat* - Change proc type to process #138 ==== Bugfixes *Affecting all Beats* - Fix random panic on shutdown by calling shutdown handler only once. elastic/filebeat#204 - Fix credentials are not send when pinging an elasticsearch host. elastic/fileabeat#287 *Filebeat* - Fix problem that harvesters stopped reading after some time and filebeat stopped processing events #257 - Fix line truncating by internal buffers being reused by accident #258 - Set default ignore_older to 24 hours #282 [[release-notes-1.0.0-rc2]] === Beats version 1.0.0-rc2 https://github.com/elastic/beats/compare/1.0.0-rc1...1.0.0-rc2[Check 1.0.0-rc2 diff] ==== Breaking changes *Affecting all Beats* - The `shipper` output field is renamed to `beat.name`. #285 - Use of `enabled` as a configuration option for outputs (elasticsearch, logstash, etc.) has been removed. #264 - Use of `disabled` as a configuration option for tls has been removed. #264 - The `-test` command line flag was renamed to `-configtest`. #264 - Disable geoip by default. To enable it uncomment in config file. #305 *Filebeat* - Removed utf-16be-bom encoding support. Support will be added with fix for #205 - Rename force_close_windows_files to force_close_files and make it available for all platforms. ==== Bugfixes *Affecting all Beats* - Disable logging to stderr after configuration phase. #276 - Set the default file logging path when not set in config. #275 - Fix bug silently dropping records based on current window size. elastic/filebeat#226 - Fix direction field in published events. #300 - Fix elasticsearch structured errors breaking error handling. #309 *Packetbeat* - Packetbeat will now exit if a configuration error is detected. #357 - Fixed an issue handling DNS requests containing no questions. #369 *Topbeat* - Fix leak of Windows handles. #98 - Fix memory leak of process information. #104 *Filebeat* - Filebeat will now exit if a configuration error is detected. #198 - Fix to enable prospector to harvest existing files that are modified. #199 - Improve line reading and encoding to better keep track of file offsets based on encoding. #224 - Set input_type by default to ""log"" ==== Added *Affecting all Beats* - Added `beat.hostname` to contain the hostname where the Beat is running on as returned by the operating system. #285 - Added timestamp for file logging. #291 *Filebeat* - Handling end of line under windows was improved #233 [[release-notes-1.0.0-rc1]] === Beats version 1.0.0-rc1 https://github.com/elastic/beats/compare/1.0.0-beta4...1.0.0-rc1[Check 1.0.0-rc1 diff] ==== Breaking changes *Affecting all Beats* - Rename timestamp field with @timestamp. #237 *Packetbeat* - Rename timestamp field with @timestamp. #343 *Topbeat* - Rename timestamp field with @timestamp for a better integration with Logstash. #80 *Filebeat* - Rename the timestamp field with @timestamp #168 - Rename tail_on_rotate prospector config to tail_files - Removal of line field in event. Line number was not correct and does not add value. #217 ==== Bugfixes *Affecting all Beats* - Use stderr for console log output. #219 - Handle empty event array in publisher. #207 - Respect '*' debug selector in IsDebug. #226 (elastic/packetbeat#339) - Limit number of workers for Elasticsearch output. elastic/packetbeat#226 - On Windows, remove service related error message when running in the console. #242 - Fix waitRetry no configured in single output mode configuration. elastic/filebeat#144 - Use http as the default scheme in the elasticsearch hosts #253 - Respect max bulk size if bulk publisher (collector) is disabled or sync flag is set. - Always evaluate status code from Elasticsearch responses when indexing events. #192 - Use bulk_max_size configuration option instead of bulk_size. #256 - Fix max_retries=0 (no retries) configuration option. #266 - Filename used for file based logging now defaults to beat name. #267 *Packetbeat* - Close file descriptors used to monitor processes. #337 - Remove old RPM spec file. It moved to elastic/beats-packer. #334 *Topbeat* - Don't wait for one period until shutdown #75 *Filebeat* - Omit 'fields' from event JSON when null. #126 - Make offset and line value of type long in elasticsearch template to prevent overflow. #140 - Fix locking files for writing behaviour. #156 - Introduce 'document_type' config option per prospector to define document type for event stored in elasticsearch. #133 - Add 'input_type' field to published events reporting the prospector type being used. #133 - Fix high CPU usage when not connected to Elasticsearch or Logstash. #144 - Fix issue that files were not crawled anymore when encoding was set to something other then plain. #182 ==== Added *Affecting all Beats* - Add Console output plugin. #218 - Add timestamp to log messages #245 - Send @metadata.beat to Logstash instead of @metadata.index to prevent possible name clashes and give user full control over index name used for Elasticsearch - Add logging messages for bulk publishing in case of error #229 - Add option to configure number of parallel workers publishing to Elasticsearch or Logstash. - Set default bulk size for Elasticsearch output to 50. - Set default http timeout for Elasticsearch to 90s. - Improve publish retry if sync flag is set by retrying only up to max bulk size events instead of all events to be published. *Filebeat* - Introduction of backoff, backoff_factor, max_backoff, partial_line_waiting, force_close_windows_files config variables to make crawling more configurable. - All Godeps dependencies were updated to master on 2015-10-21 [#122] - Set default value for ignore_older config to 10 minutes. #164 - Added the fields_under_root setting to optionally store the custom fields top level in the output dictionary. #188 - Add more encodings by using x/text/encodings/htmlindex package to select encoding by name. [[release-notes-1.0.0-beta4]] === Beats version 1.0.0-beta4 https://github.com/elastic/beats/compare/1.0.0-beta3...1.0.0-beta4[Check 1.0.0-beta4 diff] ==== Breaking changes *Affecting all Beats* - Update tls config options naming from dash to underline #162 - Feature/output modes: Introduction of PublishEvent(s) to be used by beats #118 #115 *Packetbeat* - Renamed http module config file option 'strip_authorization' to 'redact_authorization' - Save_topology is set to false by default - Rename elasticsearch index to [packetbeat-]YYYY.MM.DD *Topbeat* - Percentage fields (e.g user_p) are exported as a float between 0 and 1 #34 ==== Bugfixes *Affecting all Beats* - Determine Elasticsearch index for an event based on UTC time #81 - Fixing ES output's defaultDeadTimeout so that it is 60 seconds #103 - ES outputer: fix timestamp conversion #91 - Fix TLS insecure config option #239 - ES outputer: check bulk API per item status code for retransmit on failure. *Packetbeat* - Support for lower-case header names when redacting http authorization headers - Redact proxy-authorization if redact-authorization is set - Fix some multithreading issues #203 - Fix negative response time #216 - Fix memcache TCP connection being nil after dropping stream data. #299 - Add missing DNS protocol configuration to documentation #269 *Topbeat* - Don't divide the reported memory by an extra 1024 #60 ==== Added *Affecting all Beats* - Add logstash output plugin #151 - Integration tests for Beat -> Logstash -> Elasticsearch added #195 #188 #168 #137 #128 #112 - Large updates and improvements to the documentation - Add direction field to publisher output to indicate inbound/outbound transactions #150 - Add tls configuration support to elasticsearch and logstash outputers #139 - All external dependencies were updated to the latest version. Update to Golang 1.5.1 #162 - Guarantee ES index is based in UTC time zone #164 - Cache: optional per element timeout #144 - Make it possible to set hosts in different ways. #135 - Expose more TLS config options #124 - Use the Beat name in the default configuration file path #99 *Packetbeat* - add [.editorconfig file](http://editorconfig.org/) - add (experimental/unsupported?) saltstack files - Sample config file cleanup - Moved common documentation to [libbeat repository](https://github.com/elastic/libbeat) - Update build to go 1.5.1 - Adding device descriptions to the -device output. - Generate coverage for system tests - Move go-daemon dependency to beats-packer - Rename integration tests to system tests - Made the `-devices` option more user friendly in case `sudo` is not used. Issue #296. - Publish expired DNS transactions #301 - Update protocol guide to libbeat changes - Add protocol registration to new protocol guide - Make transaction timeouts configurable #300 - Add direction field to the exported fields #317 *Topbeat* - Document fields in a standardized format (etc/fields.yml) #34 - Updated to use new libbeat Publisher #37 #41 - Update to go 1.5.1 #43 - Updated configuration files with comments for all options #65 - Documentation improvements ==== Deprecated *Affecting all Beats* - Redis output was deprecated #169 #145 - Host and port configuration options are deprecated. They are replaced by the hosts configuration option. #141 ",12262,True,2542.8847147809092,median "// // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Getting Started with Apache NiFi ================================ Apache NiFi Team :homepage: http://nifi.apache.org Who is This Guide For? ---------------------- This guide is written for user who have never used, have had limited exposure to, or only accomplished specific tasks within NiFi. This guide is not intended to be an exhaustive instruction manual or a reference guide. The link:user-guide.html[User Guide] provides a great deal of information and is intended to be a much more exhaustive resource and is very useful as a reference guide, as well. This guide, in comparison, is intended to provide users with just the information needed in order to understand how to work with NiFi in order to quickly and easily build powerful and agile dataflows. Because some of the information in this guide is applicable only for first-time users while other information may be applicable for those who have used NiFi a bit, this guide is broken up into several different sections, some of which may not be useful for some readers. Feel free to jump to the sections that are most appropriate for you. This guide does expect that the user has a basic understanding of what NiFi is and does not delve into this level of detail. This level of information can be found in the link:overview.html[Overview] documentation. Terminology Used in This Guide ------------------------------ In order to talk about NiFi, there are a few key terms that readers should be familiar with. We will explain those NiFi-specific terms here, at a high level. *FlowFile*: Each piece of ""User Data"" (i.e., data that the user brings into NiFi for processing and distribution) is referred to as a FlowFile. A FlowFile is made up of two parts: Attributes and Content. The Content is the User Data itself. Attributes are key-value pairs that are associated with the User Data. *Processor*: The Processor is the NiFi component that is responsible for creating, sending, receiving, transforming, routing, splitting, merging, and processing FlowFiles. It is the most important building block available to NiFi users to build their dataflows. Downloading and Installing NiFi ------------------------------- NiFi can be downloaded from the link:http://nifi.apache.org/download.html[NiFi Downloads Page]. There are two packaging options available: a ""tarball"" that is tailored more to Linux and a zip file that is more applicable for Windows users. Mac OSX users may also use the tarball or can install via Homebrew. To install via Homebrew, simply run the command `brew install nifi`. For users who are not running OSX or do not have Homebrew installed, after downloading the version of NiFi that you would like to use simply extract the archive to the location that you wish to run the application from. For information on how to configure the instance of NiFi (for instance, to configure security, data storage configuration, or the port that NiFi is running on), see the link:administration-guide.html[Admin Guide]. Starting NiFi ------------- Once NiFi has been downloaded and installed as described above, it can be started by using the mechanism appropriate for your operating system. === For Windows Users For Windows users, navigate to the folder where NiFi was installed. Within this folder is a subfolder named `bin`. Navigate to this subfolder and double-click the `run-nifi.bat` file. This will launch NiFi and leave it running in the foreground. To shut down NiFi, select the window that was launched and hold the Ctrl key while pressing C. === For Linux/Mac OSX users For Linux and OSX users, use a Terminal window to navigate to the directory where NiFi was installed. To run NiFi in the foreground, run `bin/nifi.sh run`. This will leave the application running until the user presses Ctrl-C. At that time, it will initiate shutdown of the application. To run NiFi in the background, instead run `bin/nifi.sh start`. This will initiate the application to begin running. To check the status and see if NiFi is currently running, execute the command `bin/nifi.sh status`. NiFi can be shutdown by executing the command `bin/nifi.sh stop`. === Installing as a Service Currently, installing NiFi as a service is supported only for Linux and Mac OSX users. To install the application as a service, navigate to the installation directory in a Terminal window and execute the command `bin/nifi.sh install` to install the service with the default name `nifi`. To specify a custom name for the service, execute the command with an optional second argument that is the name of the service. For example, to install NiFi as a service with the name `dataflow`, use the command `bin/nifi.sh install dataflow`. Once installed, the service can be started and stopped using the appropriate commands, such as `sudo service nifi start` and `sudo service nifi stop`. Additionally, the running status can be checked via `sudo service nifi status`. I Started NiFi. Now What? ------------------------- Now that NiFi has been started, we can bring up the User Interface (UI) in order to create and monitor our dataflow. To get started, open a web browser and navigate to `http://localhost:8080/nifi`. The port can be changed by editing the `nifi.properties` file in the NiFi `conf` directory, but the default port is 8080. This will bring up the User Interface, which at this point is a blank canvas for orchestrating a dataflow: image:new-flow.png[""New Flow""] Near the top of the UI are a few toolbars that will be very important to create your first dataflow: image:nifi-toolbar-components.png[""Toolbar Components""] === Adding a Processor We can now begin creating our dataflow by adding a Processor to our canvas. To do this, drag the Processor icon image:iconProcessor.png[""Processor""] from the top-left of the screen into the middle of the canvas (the graph paper-like background) and drop it there. This will give us a dialog that allows us to choose which Processor we want to add: image:add-processor.png[""Add Processor""] We have quite a few options to choose from. For the sake of becoming oriented with the system, let's say that we just want to bring in files from our local disk into NiFi. When a developer creates a Processor, the developer can assign ""tags"" to that Processor. These can be thought of as keywords. We can filter by these tags or by Processor name by typing into the Filter box in the top-right corner of the dialog. Type in the keywords that you would think of when wanting to ingest files from a local disk. Typing in keyword ""file"", for instance, will provide us a few different Processors that deal with files. Filtering by the term ""local"" will narrow down the list pretty quickly, as well. If we select a Processor from the list, we will see a brief description of the Processor near the bottom of the dialog. This should tell us exactly what the Processor does. The description of the *GetFile* Processor tells us that it pulls data from our local disk into NiFi and then removes the local file. We can then double-click the Processor type or select it and choose the `Add` button. The Processor will be added to the canvas in the location that it was dropped. === Configuring a Processor Now that we have added the GetFile Processor, we can configure it by right-clicking on the Processor and choosing the `Configure` menu item. The provided dialog allows us to configure many different options that can be read about in the link:user-guide.html[User Guide], but for the sake of this guide, we will focus on the Properties tab. Once the Properties tab has been selected, we are given a list of several different properties that we can configure for the Processor. The properties that are available depend on the type of Processor and are generally different for each type. Properties that are in bold are required properties. The Processor cannot be started until all required properties have been configured. The most important property to configure for GetFile is the directory from which to pick up files. If we set the directory name to `./data-in`, this will cause the Processor to start picking up any data in the `data-in` subdirectory of the NiFi Home directory. We can choose to configure several different Properties for this Processor. If unsure what a particular Property does, we can hover over the help icon ( image:iconInfo.png[""Help""] ) next to the Property Name with the mouse in order to read a description of the property. Additionally, the tooltip that is displayed when hovering over the help icon will provide the default value for that property, if one exists, information about whether or not the property supports the Expression Language (see the <> section below), and previously configured values for that property. In order for this property to be valid, create a directory named `data-in` in the NiFi home directory and then click the `OK` button to close the dialog. === Connecting Processors Each Processor has a set of defined ""Relationships"" that it is able to send data to. When a Processor finishes handling a FlowFile, it transfers it to one of these Relationships. This allows a user to configure how to handle FlowFiles based on the result of Processing. For example, many Processor define two Relationships: `success` and `failure`. Users are then able to configure data to be routed through the flow one way if the Processor is able to successfully process the data and route the data through the flow in a completely different many if the Processor cannot process the data for some reason. Or, depending on the use case, the may simply route both relationships to the same route through the flow. Now that we have added and configured our GetFile processor and applied the configuration, we can see in the top-left corner of the Processor an Alert icon ( image:iconAlert.png[Alert] ) signaling that the Processor is not in a valid state. Hovering over this icon, we can see that the `success` relationship has not been defined. This simply means that we have not told NiFi what to do with the data that the Processor transfers to the `success` Relationship. In order to address this, let's add another Processor that we can connect the GetFile Processor to, by following the same steps above. This time, however, we will simply log the attributes that exist for the FlowFile. To do this, we will add a LogAttributes Processor. We can now send the output of the GetFile Processor to the LogAttribute Processor. Hover over the GetFile Processor with the mouse and a Connection Icon ( image:iconConnection.png[Connection] ) will appear over the middle of the Processor. We can drag this icon from the GetFile Processor to the LogAttribute Processor. This gives us a dialog to choose which Relationships we want to include for this connection. Because GetFile has only a single Relationship, `success`, it is automatically selected for us. Clicking on the Settings tab provides a handful of options for configuring how this Connection should behave: image:connection-settings.png[Connection Settings] We can give the Connection a name, if we like. Otherwise, the Connection name will be based on the selected Relationships. We can also set an expiration for the data. By default, it is set to ""0 sec"" which indicates that the data should not expire. However, we can change the value so that when data in this Connection reaches a certain age, it will automatically be deleted (and a corresponding EXPIRE Provenance event will be created). The backpressure thresholds allow us to specify how full the queue is allowed to become before the source Processor is no longer scheduled to run. This allows us to handle cases where one Processor is capable of producing data faster than the next Processor is capable of consuming that data. If the backpressure is configured for each Connection along the way, the Processor that is bringing data into the system will eventually experience the backpressure and stop bringing in new data so that our system has the ability to recover. Finally, we have the Prioritizers on the right-hand side. This allows us to control how the data in this queue is ordered. We can drag Prioritizers from the ""Available prioritizers"" list to the ""Selected prioritizers"" list in order to active the prioritizer. If multiple prioritizers are activated, they will be evaluated such that the Prioritizer listed first will be evaluated first and if two FlowFiles are determined to be equal according to that Prioritizers, the second Prioritizer will be used. For the sake of this discuss, we can simply click `Add`. to add the Connection to our graph. We should now see that the Alert icon has changed to a Stopped icon ( image:iconStop.png[Stopped] ). The LogAttribute Processor, however, is now invalid because its `success` Relationship has not been connected to anything. Let's address this by signaling that data that is routed to `success` by LogAttribute should be ""Auto Terminated,"" meaning that NiFi should consider the FlowFile's processing complete and ""drop"" the data. To do this, we configure the LogAttribute Processor. On the Settings tab, in the right-hand side we can check the box next to the `success` Relationship to Auto Terminate the data. Clicking `OK` will close the dialog and show that both Processors are now stopped. === Starting and Stopping Processors At this point, we have two Processors on our graph, but nothing is happening. In order to start the Processors, we can click on each one individually and then right-click and choose the `Start` menu item. Alternatively, we can select the first Processor, and then hold the Shift key while selecting the other Processor in order to select both. Then, we can right-click and choose the `Start` menu item. As an alternative to using the context menu, we can select the Processors and then click the Start icon in the toolbar at the top of the screen. Once started, the icon in the top-left corner of the Processors will change from a stopped icon to a Running icon. We can then stop the Processors in the same manner that we started them but using the Stop icon in the toolbar or the Stop menu item as opposed to the Start button. Once a Processor has started, we are not able to configure it anymore. Instead, when we right-click on the Processor, we are given the option to view its current configuration. In order to configure a Processor, we must first stop the Processor and wait for any tasks that may be executing to finish. The number of tasks currently executing is shown in the top-right corner of the Processor, but nothing is shown there if there are currently no tasks. === Getting More Info for a Processor With each Processor having the ability to expose multiple different Properties and Relationships, it can become quite difficult to remember how all of the different pieces work for each Processor. To address this, you are able to right-click on a Processor and choose the `Usage` menu item. This will provide you with the Processor's usage information, such as a description of the Processor, the different Relationships that are available, when the different Relationships are used, Properties that are exposed by the Processor and their documentation, as well as which FlowFile Attributes (if any) are expected on incoming FlowFiles and which Attributes (if any) are added to outgoing FlowFiles. === Other Components The toolbar that provides users the ability to drag and drop Processors onto the graph includes several other components that can be used to build a dataflow. These components include Input and Output Ports, Funnels, Process Groups, and Remote Process Groups. Due to the intended scope of this document, we will not discuss these elements here, but information is readily available in the link:user-guide.html#building-dataflow[Building a Dataflow section] of the link:user-guide.html[User Guide]. What Processors are Available ----------------------------- In order to create an effective dataflow, the users must understand what types of Processors are available to them. NiFi contains many different Processors out of the box. These Processors provide capabilities to ingest data from numerous different systems, route, transform, process, split, and aggregate data, and distribute data to many systems. The number of Processors that are available increases in nearly each release of NiFi. As a result, we will not attempt to name each of the Processors that are available, but we will highlight some of the most frequently used Processors, categorizing them by their functions. === Data Transformation - *CompressContent*: Compress or Decompress Content - *ConvertCharacterSet*: Convert the character set used to encode the content from one character set to another - *EncryptContent*: Encrypt or Decrypt Content - *ReplaceText*: Use Regular Expressions to modify textual Content - *TransformXml*: Apply an XSLT transform to XML Content === Routing and Mediation - *ControlRate*: Throttle the rate at which data can flow through one part of the flow - *DetectDuplicate*: Monitor for duplicate FlowFiles, based on some user-defined criteria. Often used in conjunction with HashContent - *DistributeLoad*: Load balance or sample data by distributing only a portion of data to each user-defined Relationship - *MonitorActivity*: Sends a notification when a user-defined period of time elapses without any data coming through a particular point in the flow. Optionally send a notification when dataflow resumes. - *RouteOnAttribute*: Route FlowFile based on the attributes that it contains. - *ScanAttribute*: Scans the user-defined set of Attributes on a FlowFile, checking to see if any of the Attributes match the terms found in a user-defined dictionary. - *RouteOnContent*: Search Content of a FlowFile to see if it matches any user-defined Regular Expression. If so, the FlowFile is routed to the configured Relationship. - *ScanContent*: Search Content of a FlowFile for terms that are present in a user-defined dictionary and route based on the presence or absence of those terms. The dictionary can consist of either textual entries or binary entries. - *ValidateXml*: Validation XML Content against an XML Schema; routes FlowFile based on whether or not the Content of the FlowFile is valid according to the user-defined XML Schema. === Database Access - *ConvertJSONToSQL*: Convert a JSON document into a SQL INSERT or UPDATE command that can then be passed to the PutSQL Processor - *ExecuteSQL*: Executes a user-defined SQL SELECT command, writing the results to a FlowFile in Avro format - *PutSQL*: Updates a database by executing the SQL DDM statement defined by the FlowFile's content [[AttributeExtraction]] === Attribute Extraction - *EvaluateJsonPath*: User supplies JSONPath Expressions (Similar to XPath, which is used for XML parsing/extraction), and these Expressions are then evaluated against the JSON Content to either replace the FlowFile Content or extract the value into the user-named Attribute. - *EvaluateXPath*: User supplies XPath Expressions, and these Expressions are then evaluated against the XML Content to either replace the FlowFile Content or extract the value into the user-named Attribute. - *EvaluateXQuery*: User supplies an XQuery query, and this query is then evaluated against the XML Content to either replace the FlowFile Content or extract the value into the user-named Attribute. - *ExtractText*: User supplies one or more Regular Expressions that are then evaluated against the textual content of the FlowFile, and the values that are extracted are then added as user-named Attributes. - *HashAttribute*: Performs a hashing function against the concatenation of a user-defined list of existing Attributes. - *HashContent*: Performs a hashing function against the content of a FlowFile and adds the hash value as an Attribute. - *IdentifyMimeType*: Evaluates the content of a FlowFile in order to determine what type of file the FlowFile encapsulates. This Processor is capable of detecting many different MIME Types, such as images, word processor documents, text, and compression formats just to name a few. - *UpdateAttribute*: Adds or updates any number of user-defined Attributes to a FlowFile. This is useful for adding statically configured values, as well as deriving Attribute values dynamically by using the Expression Language. This processor also provides an ""Advanced User Interface,"" allowing users to update Attributes conditionally, based on user-supplied rules. === System Interaction - *ExecuteProcess*: Runs the user-defined Operating System command. The Process's StdOut is redirected such that the content that is written to StdOut becomes the content of the outbound FlowFile. This Processor is a Source Processor - its output is expected to generate a new FlowFile, and the system call is expected to receive no input. In order to provide input to the process, use the ExecuteStreamCommand Processor. - *ExecuteStreamCommand*: Runs the user-defined Operating System command. The contents of the FlowFile are optionally streamed to the StdIn of the process. The content that is written to StdOut becomes the content of hte outbound FlowFile. This Processor cannot be used a Source Processor - it must be fed incoming FlowFiles in order to perform its work. To perform the same type of functionality with a Source Processor, see the ExecuteProcess Processor. === Data Ingestion - *GetFile*: Streams the contents of a file from a local disk (or network-attached disk) into NiFi and then deletes the original file. This Processor is expected to move the file from one location to another location and is not to be used for copying the data. - *GetFTP*: Downloads the contents of a remote file via FTP into NiFi and then deletes the original file. This Processor is expected to move the data from one location to another location and is not to be used for copying the data. - *GetSFTP*: Downloads the contents of a remote file via SFTP into NiFi and then deletes the original file. This Processor is expected to move the data from one location to another location and is not to be used for copying the data. - *GetJMSQueue*: Downloads a message from a JMS Queue and creates a FlowFile based on the contents of the JMS message. The JMS Properties are optionally copied over as Attributes, as well. - *GetJMSTopic*: Downloads a message from a JMS Topic and creates a FlowFile based on the contents of the JMS message. The JMS Properties are optionally copied over as Attributes, as well. This Processor supports both durable and non-durable subscriptions. - *GetHTTP*: Downloads the contents of a remote HTTP- or HTTPS-based URL into NiFi. The Processor will remember the ETag and Last-Modified Date in order to ensure that the data is not continually ingested. - *ListenHTTP*: Starts an HTTP (or HTTPS) Server and listens for incoming connections. For any incoming POST request, the contents of the request are written out as a FlowFile, and a 200 response is returned. - *ListenUDP*: Listens for incoming UDP packets and creates a FlowFile per packet or per bundle of packets (depending on configuration) and emits the FlowFile to the 'success' relationship. - *GetHDFS*: Monitors a user-specified directory in HDFS. Whenever a new file enters HDFS, it is copied into NiFi and deleted from HDFS. This Processor is expected to move the file from one location to another location and is not to be used for copying the data. This Processor is also expected to be run On Primary Node only, if run within a cluster. In order to copy the data from HDFS and leave it in-tact, or to stream the data from multiple nodes in the cluster, see the ListHDFS Processor. - *ListHDFS* / *FetchHDFS*: ListHDFS monitors a user-specified directory in HDFS and emits a FlowFile containing the filename for each file that it encounters. It then persists this state across the entire NiFi cluster by way of a Distributed Cache. These FlowFiles can then be fanned out across the cluster and sent to the FetchHDFS Processor, which is responsible for fetching the actual content of those files and emitting FlowFiles that contain the content fetched from HDFS. - *FetchS3Object*: Fetches the contents of an object from the Amazon Web Services (AWS) Simple Storage Service (S3). The outbound FlowFile contains the contents received from S3. - *GetKafka*: Consumes messages from Apache Kafka. The messages can be emitted as a FlowFile per message or can be batched together using a user-specified delimiter. - *GetMongo*: Executes a user-specified query against MongoDB and writes the contents to a new FlowFile. - *GetTwitter*: Allows Users to register a filter to listen to the Twitter ""garden hose"" or Enterprise endpoint, creating a FlowFile for each tweet that is received. === Data Egress / Sending Data - *PutEmail*: Sends an E-mail to the configured recipients. The content of the FlowFile is optionally sent as an attachment. - *PutFile*: Writes the contents of a FlowFile to a directory on the local (or network attached) file system. - *PutFTP*: Copies the contents of a FlowFile to a remote FTP Server. - *PutSFTP*: Copies the contents of a FlowFile to a remote SFTP Server. - *PutJMS*: Sends the contents of a FlowFile as a JMS message to a JMS broker, optionally adding JMS Properties based on Attributes. - *PutSQL*: Executes the contents of a FlowFile as a SQL DDL Statement (INSERT, UPDATE, or DELETE). The contents of the FlowFile must be a valid SQL statement. Attributes can be used as parameters so that the contents of the FlowFile can be parameterized SQL statements in order to avoid SQL injection attacks. - *PutKafka*: Sends the contents of a FlowFile to Kafka as a message. The FlowFile can be sent as a single message or a delimiter, such as a new-line can be specified, in order to send many messages for a single FlowFile. - *PutMongo*: Sends the contents of a FlowFile to Mongo as an INSERT or an UPDATE. === Splitting and Aggregation - *SplitText*: SplitText takes in a single FlowFile whose contents are textual and splits it into 1 or more FlowFiles based on the configured number of lines. For example, the Processor can be configured to split a FlowFile into many FlowFiles, each of which is only 1 line. - *SplitJson*: Allows the user to split a JSON object that is comprised of an array or many child objects into a FlowFile per JSON element. - *SplitXml*: Allows the user to split an XML message into many FlowFiles, each containing a segment of the original. This is generally used when several XML elements have been joined together with a ""wrapper"" element. This Processor then allows those elements to be split out into individual XML elements. - *UnpackContent*: Unpacks different types of archive formats, such as ZIP and TAR. Each file within the archive is then transferred as a single FlowFile. - *MergeContent*: This Processor is responsible for merging many FlowFiles into a single FlowFile. The FlowFiles can be merged by concatenating their content together along with optional header, footer, and demarcator, or by specifying an archive format, such as ZIP or TAR. FlowFiles can be binned together based on a common attribute, or can be ""defragmented"" if they were split apart by some other Splitting process. The minimum and maximum size of each bin is user-specified, based on number of elements or total size of FlowFiles' contents, and an optional Timeout can be assigned as well so that FlowFiles will only wait for their bin to become full for a certain amount of time. - *SegmentContent*: Segments a FlowFile into potentially many smaller FlowFiles based on some configured data size. The splitting is not performed against any sort of demarcator but rather just based on byte offsets. This is used before transmitting FlowFiles in order to provide lower latency by sending many different pieces in parallel. On the other side, these FlowFiles can then be reassembled by the MergeContent processor using the Defragment mode. - *SplitContent*: Splits a single FlowFile into potentially many FlowFiles, similarly to SegmentContent. However, with SplitContent, the splitting is not performed on arbitrary byte boundaries but rather a byte sequence is specified on which to split the content. === HTTP - *GetHTTP*: Downloads the contents of a remote HTTP- or HTTPS-based URL into NiFi. The Processor will remember the ETag and Last-Modified Date in order to ensure that the data is not continually ingested. - *ListenHTTP*: Starts an HTTP (or HTTPS) Server and listens for incoming connections. For any incoming POST request, the contents of the request are written out as a FlowFile, and a 200 response is returned. - *InvokeHTTP*: Performs an HTTP Request that is configured by the user. This Processor is much more versatile than the GetHTTP and PostHTTP but requires a bit more configuration. This Processor cannot be used as a Source Processor and is required to have incoming FlowFiles in order to be triggered to perform its task. - *PostHTTP*: Performs an HTTP POST request, sending the contents of the FlowFile as the body of the message. This is often used in conjunction with ListenHTTP in order to transfer data between two different instances of NiFi in cases where Site-to-Site cannot be used (for instance, when the nodes cannot access each other directly and are able to communicate through an HTTP proxy). - *HandleHttpRequest* / *HandleHttpResponse*: The HandleHttpRequest Processor is a Source Processor that starts an embedded HTTP(S) server similarly to ListenHTTP. However, it does not send a response to the client. Instead, the FlowFile is sent out with the body of the HTTP request as its contents and attributes for all of the typical Servlet parameters, headers, etc. as Attributes. The HandleHttpResponse then is able to send a response back to the client after the FlowFile has finished being processed. These Processors are always expected to be used in conjunction with one another and allow the user to visually create a Web Service within NiFi. This is particularly useful for adding a front-end to a non-web- based protocol or to add a simple web service around some functionality that is already performed by NiFi, such as data format conversion. === Amazon Web Services - *FetchS3Object*: Fetches the content of an object stored in Amazon Simple Storage Service (S3). The content that is retrieved from S3 is then written to the content of the FlowFile. - *PutS3Object*: Writes the contents of a FlowFile to an Amazon S3 object using the configured credentials, key, and bucket name. - *PutSNS*: Sends the contents of a FlowFile as a notification to the Amazon Simple Notification Service (SNS). - *GetSQS*: Pulls a message from the Amazon Simple Queuing Service (SQS) and writes the contents of the message to the content of the FlowFile. - *PutSQS*: Sends the contents of a FlowFile as a message to the Amazon Simple Queuing Service (SQS). - *DeleteSQS*: Deletes a message from the Amazon Simple Queuing Service (SQS). This can be used in conjunction with the GetSQS in order to receive a message from SQS, perform some processing on it, and then delete the object from the queue only after it has successfully completed processing. Working With Attributes ----------------------- Each FlowFile is created with several Attributes, and these Attributes will change over the life of the FlowFile. The concept of a FlowFile is extremely powerful and provides three primary benefits. First, it allows the user to make routing decisions in the flow so that FlowFiles that meeting some criteria can be handled differently than other FlowFiles. This is done using the RouteOnAttribute and similar Processors. Secondly, Attributes are used in order to configure Processors in such a way that the configurationg of the Processor is dependent on the data itself. For instance, the PutFile Processor is able to use the Attributes in order to know where to store each FlowFile, while the directory and filename Attributes may be different for each FlowFile. Finally, the Attributes provide extremely valuable context about the data. This is useful when reviewing the Provenance data for a FlowFile. This allows the user to search for Provenance data that match specific criteria, and it also allows the user to view this context when inspecting the details of a Provenance Event. By doing this, the user is then able to gain valuable insight as to why the data was processed one way or another, simply by glancing at this context that is carried along with the content. === Common Attributes Each FlowFile has a minimum set of Attributes: - *filename*: A filename that can be used to store the data to a local or remote file system - *path*: The name of a directory that can be used to store the data to a local or remote file system - *uuid*: A Universally Unique Identifier that distinguishes the FlowFile from other FlowFiles in the system. - *entryDate*: The date and time at which the FlowFile entered the system (i.e., was created). The value of this attribute is a number that represents the number of milliseconds since midnight, Jan. 1, 1970 (UTC). - *lineageStartDate*: Any time that a FlowFile is cloned, merged, or split, this results in a ""child"" FlowFile being created. As those children are then cloned, merged, or split, a chain of ancestors is built. This value represents the date and time at which the oldest ancestor entered the system. Another way to think about this is that this attribute represents the latency of the FlowFile through the system. The value is a number that represents the number of milliseconds since midnight, Jan. 1, 1970 (UTC). - *fileSize*: This attribute represents the number of bytes taken up by the FlowFile's Content. Note that the `uuid`, `entryDate`, `lineageStartDate`, and `fileSize` attributes are system-generated and cannot be changed. === Extracting Attributes NiFi provides several different Processors out of the box for extracting Attributes from FlowFiles. A list of commonly used Processors for this purpose can be found above in the <> section. This is a very common use case for building custom Processors, as well. Many Processors are written to understand a specific data format and extract pertinent information from a FlowFile's content, creating Attributes to hold that information, so that decisions can then be made about how to route or process the data. === Adding User-Defined Attributes In addition to having Processors that are able to extract particular pieces of information from FlowFile content into Attributes, it is also common for users to want to add their own user-defined Attributes to each FlowFile at a particular place in the flow. The UpdateAttribute Processor is designed specifically for this purpose. Users are able to add a new property to the Processor in the Configure dialog by clicking the ""New Property"" button in the top-right corner of the Properties tab. The user is then prompted to enter the name of the property and then a value. For each FlowFile that is processed by this UpdateAttribute Processor, an Attribute will be added for each user-defined property. The name of the Attribute will be the same as the name of the property that was added. The value of the Attribute will be the same as the value of the property. The value of the property may contain the Expression Language, as well. This allows Attributes to be modified or added based on other Attributes. For example, if we want to prepend the hostname that is processing a file as well as the date to a filename, we could do this by adding a property with the name `filename` and the value `${hostname()}-${now():format('yyyy-dd-MM')}-${filename}`. While this may seem confusing at first, the section below on <> will help to clear up what is going on here. In addition to always adding a defined set of Attributes, the UpdateAttribute Processor has an Advanced UI that allows the user to configure a set of rules for which Attributes should be added when. To access this capability, in the Configure dialog's Properties tab, click the `Advanced...` button at the bottom of the dialog. This will provide a UI that is tailored specifically to this Processor, rather than the simple Properties table that is provided for all Processors. Within this UI, the user is able to configure a rules engine, essentially, specifying rules that must match in order to have the configured Attributes added to the FlowFile. === Routing on Attributes One of the most powerful features of NiFi is the ability to route FlowFiles based on their Attributes. The primary mechanism for doing this is the RouteOnAttribute Processor. This Processor, like UpdateAttribute, is configured by adding user-defined properties. Any number of properties can be added by clicking the ""New Property"" icon in the top-right corner of the Properties tab in the Processor's Configure dialog. Each FlowFile's Attributes will be compared against the configured properties to determine whether or not the FlowFile meets the specified criteria. The value of each property is expected to be an Expression Language expression and return a boolean value. For more on the Expression Language, see the <> section below. After evaluating the Expression Language expressions provided against the FlowFile's Attributes, the Processor determines how to route the FlowFile based on the Routing Strategy selected. The most common strategy is the ""Route to Property name"" strategy. With this strategy selected, the Processor will expose a Relationship for each property configured. If the FlowFile's Attributes satisfy the given expression, a copy of the FlowFile will be routed to the corresponding Relationship. For example, if we had a new property with the name ""begins-with-r"" and the value ""${filename:startsWith(\\'r')}"" then any FlowFile whose filename starts with the letter 'r' will be routed to that Relationship. All other FlowFiles will be routed to 'unmatched'. [[ExpressionLanguage]] === Expression Language / Using Attributes in Property Values As we extract Attributes from FlowFiles' contents and add user-defined Attributes, they don't do us much good as an operator unless we have some mechanism by which we can use them. The NiFi Expression Language allows us to access and manipulate FlowFile Attribute values as we configure our flows. Not all Processor properties allow the Expression Language to be used, but many do. In order to determine whether or not a property supports the Expression Language, a user can hover over the Help icon ( icon:iconInfo.png[""Help Icon""] ) in the Properties tab of the Processor Configure dialog. This will provide a tooltip that shows a description of the property, the default value, if any, and whether or not the property supports the Expression Language. For properties that do support the Expression Language, it is used by adding an expression within the opening `${` tag and the closing `}` tag. An expression can be as simple as an attribute name. For example, to reference the `uuid` Attribute, we can simply use the value `${uuid}`. If the Attribute name begins with any character other than a letter, or if it contians a character other than a number, a letter, a period (.), or an underscore (_), the Attribute name will need to be quoted. For example, `${My Attribute Name}` will be invalid, but `${'My Attribute Name'}` will refer to the Attribute `My Attribute Name`. In addition to referencing Attribute values, we can perform a number of functions and comparisons on those Attributes. For example, if we want to check if the `filename` attribute contains the letter 'r' without paying attention to case (upper case or lower case), we can do this by using the expression `${filename:toLower():contains('r')}`. Note here that the functions are separated by colons. We can chain together any number of functions to build up more complex expressions. It is also important to understand here that even though we are calling `filename:toLower()`, this does not alter the value of the `filename` Attribute in anyway but rather just gives us a new value to work with. We can also embed one expression within another. For example, if we wanted to compare the value of the `attr1` Attribute to the value of the `attr2` Attribute, we can do this with the following expression: `${attr1:equals( ${attr2} )}`. The Expression Language contains many different functions that can be used in order to perform the tasks needed for routing and manipulating Attributes. Functions exist for parsing and manipulating strings, comparing string and numeric values, manipulating and replacing values, and comparing values. A full explanation of the different functions available is out of scope of this document, but the link:expression-language-guide.html[Expression Language Guide] provides far greater detail for each of the functions. In addition, this Expression Language guide is built in to the application so that users are able to easily see which functions are available and see their documentation while typing. When setting the value of a property that supports the Expression Language, if the cursor is within the Expression Language start and end tags, pressing Ctrl + Space on the keyword will provide a popup of all of the available functions and will provide auto-complete functionality. Clicking on or using the keyboard to navigate to one of the functions listed in the popup will cause a tooltip to show, which explains what the function does, the arguments that it expects, and the return type of the function. Working With Templates ---------------------- As we use Processors to build more and more complex dataflows in NiFi, we often will find that we string together the same sequence of Processors to perform some task. This can become tedious and inefficient. To address this, NiFi provides a concept of Templates. A template can be thought of as a reusable sub-flow. To create a template, follow these steps: - Select the components to include in the template. We can select multiple components by clicking on the first component and then holding the Shift key while selecting additional components (to include the Connections between those components), or by holding the Shift key while dragging a box around the desired components on the canvas. - Select the Create Template Icon ( image:iconTemplate.png[Template Icon] ) from the middle toolbar at the top of the screen. - Provide a name and optionally comments about the template. - Click the Create button. Once we have created a template, we can now use it as a building block in our flow, just as we would a Processor. To do this, we will click and drag the Template icon from the left-most toolbar onto our canvas. We can then choose the template that we would like to add or our canvas and click the Add button. Finally, we have the ability to manage our templates by using the Template Management dialog. To access this dialog, click the Template icon in the top-right toolbar. From here, we can see which templates exist and filter the templates to find the templates of interest. On the right-hand side of the table is icon to Export, or Download, the template as an XML file. This can then be provided to others so that they can use your template. To import a template into your NiFi instance, click the Browse button in the top-right corner of the dialog and navigate to the file on your computer. Then click the Import button. The template will now show up in your table, and you can drag it onto your canvas as you would any other template that you have created. There are a few important notes to remember when working with templates: - Any properties that are identified as being Sensitive Properties (such as a password that is configured in a Processor) will not be added to the template. These sensitive properties will have to be populated each time that the template is added to the canvas. - If a component that is included in the template references a Controller Service, the Controller Service will also be added to the template. This means that each time that the template is added to the graph, it will create a copy of the Controller Service. Monitoring NiFi --------------- As data flows through your dataflow in NiFi, it is important to understand how well your system is performing in order to assess if you will require more resources and in order to assess the health of your current resources. NiFi provides a few mechanisms for monitoring your system. === Status Bar Near the top of the NiFi screen is a blue bar that is referred to as the Status Bar. It contains a few important statistics about the current health of NiFi. The number of Active Threads can indicate how hard NiFi is currently working, and the Queued stat indicates how many FlowFiles are currently queued across the entire flow, as well as the total size of those FlowFiles. If the NiFi instance is in a cluster, we will also see an indicator here telling us how many nodes are in the cluster and how many are currently connected. In this case, the number of active threads and the queue size are indicative of all the sum of all nodes that are currently connected. === Component Statistics Each Processor, Process Group, and Remote Process Group on the canvas provides several statistics about how much data has been processed by the component. These statistics provide information about how much data has been processed in the past five minutes. This is a rolling window and allows us to see things like the number of FlowFiles that have been consumed by a Processor, as well as the number of FlowFiles that have been emitted by the Processor. The connections between Processors also expose the number of items that are currently queued. It may also be valuable to see historical values for these metrics and, if clustered, how the different nodes compare to one another. In order to see this information, we can right-click on a component and choose the Status menu item. This will show us a graph that spans the time since NiFi was started, or up to 24 hours, whichever is less. The amount of time that is shown here can be extended or reduced by changing the configuration in the properties file. In the top-right corner is a drop-down that allows the user to select which metric they are viewing. The graph on the bottom allows the user to select a smaller portion of the graph to zoom in. === Bulletins In addition to the statistics provided by each component, as a user we will want to know if any problems occur. While we could monitor the logs for anything interesting, it is much more convenient to have notifications pop up on the screen. If a Processor logs anything as a WARNING or ERROR, we will see a ""Bulletin Indicator"" show up in the top-left-hand corner of the Processor. This indicator looks like a sticky note and will be shown for five minutes after the event occurs. Hovering over the bulletin provides information about what happened so that the user does not have to sift through log messages to find it. If in a cluster, the bulletin will also indicate which node in the cluster emitted the bulletin. We can also change the log level at which bulletins will occur in the Settings tab of the Configure dialog for a Processor. If the framework emits a bulletin, we will also see this bulletin indicator occur in the Status Bar at the top of the screen. The right-most icon in the NiFi Toolbar is the Bulletin Board icon. Clicking this icon will take us to the bulletin board where we can see all bulletins that occur across the NiFi instance and can filter based on the component, the message, etc. Data Provenance --------------- NiFi keeps a very granular level of detail about each piece of data that it ingests. As the data is processed through the system and is transformed, routed, split, aggregated, and distributed to other endpoints, this information is all stored within NiFi's Provenance Repository. In order to search and view this information, we can click the Data Provenance icon ( image:iconProvenance.png[Data Provenance, width=28]) in the top-right corner of the canvas. This will provide us a table that lists the Provenance events that we have searched for: image:provenance-table.png[Provenance Table] Initially, this table is populated with the most recent 1,000 Provenance Events that have occurred (though it may take a few seconds for the information to be processed after the events occur). From this dialog, there is a Search button that allows the user to search for events that happened by a particular Processor, for a particular FlowFile by filename or UUID, or several other fields. The `nifi.properties` file provides the ability to configure which of these properties are indexed, or made searchable. Additionally, the properties file also allows you to choose specific FlowFile Attributes that will be indexed. As a result, you can choose which Attributes will be important to your specific dataflows and make those Attributes searchable. [[EventDetails]] === Event Details Once we have performed our search, our table will be populated only with the events that match the search criteria. From here, we can choose the Info icon ( image:iconInfo.png[Info Icon] ) on the left-hand side of the table to view the details of that event: image:event-details.png[Event Details] From here, we can see exactly when that event occurred, which FlowFile the event affected, which component (Processor, etc.) performed the event, how long the event took, and the overall time that the data had been in NiFi when the event occurred (total latency). The next tab provides a listing of all Attributes that existed on the FlowFile at the time that the event occurred: image:event-attributes.png[Event Attributes] From here, we can see all the Attributes that existed on the FlowFile when the event occurred, as well as the previous values for those Attributes. This allows us to know which Attributes changed as a result of this event and how they changed. Additionally, in the right-hand corner is a checkbox that allows the user to see only those Attributes that changed. This may not be particularly useful if the FlowFile has only a handful of Attributes, but can be very helpful when a FlowFile has hundreds of Attributes. This is very important, because it allows the user to understand the exactly context in which the FlowFile was processed. This is very helpful to understand 'why' the FlowFile was processed the way that it was, especially when the Processor was configured using the Expression Language. Finally, we have the Content tab: image:event-content.png[Event Content] This tab provides us information about where in the Content Repository the FlowFile's content was stored. If the event modified the content of the FlowFile, we will see the 'before' and 'after' content claims. We are then given the option to Download the content or to View the content within NiFi itself, if the data format is one that NiFi understands how to render. Additionally, there is 'Replay' button that allows the user to re-insert the FlowFile into the flow and re-process it from exactly the point at which the event happened. This provides a very powerful mechanism, as we are able to modify our flow in real time, re-process a FlowFile, and then view the results. If they are not as expected, we can modify the flow again, and re-process the FlowFile again. We are able to perform this iterative development of the flow until it is processing the data exactly as intended. === Lineage Graph In addition to viewing the details of a Provenance event, we can also view the lineage of the FlowFile involved by clicking on the Lineage Icon ( image:iconLineage.png[Lineage] ) from the table view. This provides us with a graphical representation of exactly what happened to that piece of data as it traversed the system: image:lineage-graph-annotated.png[Lineage Graph] From here, we can right-click on any of the events represented and click the ""View Details"" menu item to see the <>. This graphical representation shows us exactly which events occurred to the data. There are a view ""special"" event types to be aware of. If we see a JOIN, FORK, or CLONE event, we can right-click and choose to Find Parents or Expand. This allows us to see the lineage of parent FlowFiles and children FlowFiles that were created as well. The slider in the bottom-left corner allows us to see the time at which these events occurred. By sliding it left and right, we can see which events introduced latency into the system so that we have a very good understanding of where in our system we may need to provide more resources, such as the number of Concurrent Tasks for a Processor. Or it may reveal, for example, that most of the latency was introduced by a JOIN event, in which we were waiting for more FlowFiles to join together. In either case, the ability to easily see where this is occurring is a very powerful feature that will help users to understand how the enterprise is operating. Where To Go For More Information -------------------------------- The NiFi community has built up a significant amount of documentation on how to use the software. The following guides are available, in addition to this Getting Started Guide: - link:overview.html[Apache NiFi Overview] - Provides an overview of what Apache NiFi is, what it does, and why it was created. - link:user-guide.html[Apache NiFi User Guide] - A fairly extensive guide that is often used more as a Reference Guide, as it has pretty lengthy in discussing all of the different components that comprise the application. This guide is written with the NiFi Operator as its audience. It provides information on each of the different components available in NiFi and explains how to use the different features provided by the application. - link:administration-guide.html[Administration Guide] - A guide for setting up and administering Apache NiFi for production environments. This guide provides information about the different system-level settings, such as setting up clusters of NiFi and securing access to the web UI and data. - link:expression-language-guide.html[Express Language Guide] - A far more exhaustive guide for understanding the Expression Language than is provided above. This guide is the definitive documentation for the NiFi Expression Language. It provides an introduction to the EL and an explanation of each function, its arguments, and return types as well as providing examples. - link:developer-guide.html[Developer's Guide] - While not an exhaustive guide to All Things NiFi Development, this guide does provide a comprehensive overview of the different API's available and how they should be used. In addition, it provides Best Practices for developing NiFi components and common Processor idioms to help aid in understanding the logic behind many of the existing NiFi components. - link:https://cwiki.apache.org/confluence/display/NIFI/Contributor+Guide[Contributor's Guide] - A guide for explaining how to contribute work back to the Apache NiFi community so that others can make use of it. Several blog postings have also been added to the Apache NiFi blog site: link:https://blogs.apache.org/nifi/[https://blogs.apache.org/nifi/] In addition to the blog and guides provided here, you can browse the different link:https://nifi.apache.org/mailing_lists.html[NiFi Mailing Lists] or send an e-mail to one of the mailing lists at link:mailto:users@nifi.apache.org[users@nifi.apache.org] or link:mailto:dev@nifi.apache.org[dev@nifi.apache.org]. Many of the members of the NiFi community are also available on Twitter and actively monitor for tweets that mention @apachenifi. ",12063,False,2027.6818239551576,median " [[springSpringBoot]] === Spring Boot Spring Boot is an application framework which, according to link:$$http://projects.spring.io/spring-boot/$$[its website], _makes it easy to create stand-alone, production-grade Spring based Applications that can you can ""just run"". It takes an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration_. For more information on Spring Boot, see link:$$http://projects.spring.io/spring-boot/$$[http://projects.spring.io/spring-boot/] The Spring Boot - Flowable integration has been developed together with Spring committers. ==== Compatibility Flowable supports both Spring Boot 2.0 and 1.5 with the same starters. The base support is for Spring Boot 2.0, which means that the actuator endpoints are only supported on 2.0. The Flowable starters are also puling spring boot starter transitively, which means that users will have to define the 1.5 version of the spring boot starters in their own build files. [[springSpringBootGettingStarted]] ==== Getting started Spring Boot is all about convention over configuration. To get started, you would need to create a Spring Boot project. The easiest way to do this would be to create a project via link:$$https://start.spring.io/$$[start.spring.io]. For example create a project with web and h2 dependencies. Then in the created project simply add the _flowable-spring-boot-starter_ or _flowable-spring-boot-starter-rest_ dependency. In case you don't need all the engines see the other <>. For example for Maven: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter ${flowable.version} ---- That's all that's needed. This dependency will transitively add the correct Flowable dependencies to the classpath. You can now run your Spring Boot application: [source,java,,linenums] ---- import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ---- You will see an output like this: ---- . ____ _ __ _ _ /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\ ( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\ \\\\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.0.RELEASE) MyApplication : Starting MyApplication on ... MyApplication : No active profile set, falling back to default profiles: default ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4fdfa676: startup date [Wed Mar 28 12:04:00 CEST 2018]; root of context hierarchy o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) o.apache.catalina.core.StandardService : Starting service [Tomcat] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28 o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3085 ms o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable IDM Rest API mapped to [/idm-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable Form Rest API mapped to [/form-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable DMN Rest API mapped to [/dmn-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable Content Rest API mapped to [/content-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable CMMN Rest API mapped to [/cmmn-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable BPMN Rest API mapped to [/process-api/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] uration$$EnhancerBySpringCGLIB$$3d0c70ac : No deployment resources were found for autodeployment uration$$EnhancerBySpringCGLIB$$8131eb1a : No deployment resources were found for autodeployment o.f.e.i.c.ProcessEngineConfigurationImpl : Found 5 Engine Configurators in total: o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) .d.AbstractSqlScriptBasedDbSchemaManager : performing create on identity with resource org/flowable/idm/db/create/flowable.h2.create.identity.sql o.f.idm.engine.impl.IdmEngineImpl : IdmEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.dmn.engine.impl.DmnEngineImpl : DmnEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.form.engine.impl.FormEngineImpl : FormEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.c.engine.ContentEngineConfiguration : Content file system root : ... o.f.c.engine.impl.ContentEngineImpl : ContentEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) o.f.cmmn.engine.CmmnEngineConfiguration : Found 1 Engine Configurators in total: o.f.cmmn.engine.CmmnEngineConfiguration : class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.cmmn.engine.CmmnEngineConfiguration : Executing beforeInit() of class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.cmmn.engine.CmmnEngineConfiguration : Executing configure() of class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.idm.engine.impl.IdmEngineImpl : IdmEngine default created o.f.cmmn.engine.impl.CmmnEngineImpl : CmmnEngine default created o.f.engine.impl.ProcessEngineImpl : ProcessEngine default created o.f.j.s.i.a.AbstractAsyncExecutor : Starting up the async job executor [org.flowable.spring.job.service.SpringAsyncExecutor]. o.f.j.s.i.a.AcquireAsyncJobsDueRunnable : starting to acquire async jobs due o.f.j.s.i.a.AcquireTimerJobsRunnable : starting to acquire async jobs due o.f.j.s.i.a.ResetExpiredJobsRunnable : starting to reset expired jobs o.f.e.impl.cmd.ValidateV5EntitiesCmd : Total of v5 deployments found: 0 s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4fdfa676: startup date [Wed Mar 28 12:04:00 CEST 2018]; root of context hierarchy s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped ""{[/error]}"" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest) s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped ""{[/error],produces=[text/html]}"" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase -20 o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0 o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 20 o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' flowable.Application : Started Application in 18.235 seconds (JVM running for 19.661) ---- So, by just adding the dependency to the classpath and using the _@SpringBootAplication_ annotation a lot has happened behind the scenes: * An in-memory datasource is created automatically (because the H2 driver is on the classpath) and passed to the Flowable process engine configuration * A Flowable ProcessEngine, CmmnEngine, DmnEngine, FormEngine, ContentEngine and IdmEngine beans have been created and exposed * All the Flowable services are exposed as Spring beans * The Spring Job Executor is created Also: * Any BPMN 2.0 process definitions in the _processes_ folder will be automatically deployed. Create a folder _processes_ and add a dummy process definition (named _one-task-process.bpmn20.xml_) to this folder. The content of this file is shown below. * Any CMMN 1.1 case definitions in the _cases_ folder will be automatically deployed. * Any DMN 1.1 dmn definitions in the _dmn_ folder will be automatically deployed. * Any Form definitions in the _forms_ folder will be automatically deployed. The XML content of the process definition is shown below. Notice that, for the moment, we are hard-coding an assignee called ""kermit"" to the user task. We'll come back to this later. [source,xml,linenums] ---- ---- Also, add following code lines to test if the deployment actually worked. The _CommandLineRunner_ is a special kind of Spring bean that is executed when the application boots: [source,java,linenums] ---- @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Bean public CommandLineRunner init(final RepositoryService repositoryService, final RuntimeService runtimeService, final TaskService taskService) { return new CommandLineRunner() { @Override public void run(String... strings) throws Exception { System.out.println(""Number of process definitions : "" + repositoryService.createProcessDefinitionQuery().count()); System.out.println(""Number of tasks : "" + taskService.createTaskQuery().count()); runtimeService.startProcessInstanceByKey(""oneTaskProcess""); System.out.println(""Number of tasks after process start: "" + taskService.createTaskQuery().count()); } }; } } ---- The output expected will be: ---- Number of process definitions : 1 Number of tasks : 0 Number of tasks after process start : 1 ---- ==== Changing the database and connection pool As stated above, Spring Boot is about convention over configuration. By default, by having only H2 on the classpath, it created an in-memory datasource and passed that to the Flowable process engine configuration. To change the datasource, simply add the database driver dependencies and provide the URL to the database. For example, to switch to a MySQL database: [source,linenums] ---- spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable-spring-boot?characterEncoding=UTF-8 spring.datasource.username=flowable spring.datasource.password=flowable ---- Remove H2 from the Maven dependencies and add the MySQL driver to the classpath: [source,xml,linenums] ---- mysql mysql-connector-java 5.1.45 ---- When the app is now booted up, you'll see it uses MySQL as database (and the HikariCP connection pooling framework): ---- org.flowable.engine.impl.db.DbSqlSession : performing create on engine with resource org/flowable/db/create/flowable.mysql.create.engine.sql org.flowable.engine.impl.db.DbSqlSession : performing create on history with resource org/flowable/db/create/flowable.mysql.create.history.sql org.flowable.engine.impl.db.DbSqlSession : performing create on identity with resource org/flowable/db/create/flowable.mysql.create.identity.sql ---- When you reboot the application multiple times, you'll see the number of tasks go up (the H2 in-memory database does not survive a shutdown, MySQL does). For more information about how to configure the datasource have a look in link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-configure-datasource$$[Configure a DataSource] in the Spring Boot reference guide. ==== REST support Often, a REST API is used on top of the embedded Flowable engine (interacting with the different services in a company). Spring Boot makes this really easy. Add following dependency to the classpath: [source,xml,linenums] ---- org.springframework.boot spring-boot-starter-web ${spring.boot.version} ---- Create a new class, a Spring service and create two methods: one to start our process and one to get a task list for a given assignee. We simply wrap Flowable calls here, but in real-life scenarios this will be more complex. [source,java,linenums] ---- @Service public class MyService { @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Transactional public void startProcess() { runtimeService.startProcessInstanceByKey(""oneTaskProcess""); } @Transactional public List getTasks(String assignee) { return taskService.createTaskQuery().taskAssignee(assignee).list(); } } ---- We can now create a REST endpoint by annotating a class with _@RestController_. Here, we simply delegate to the service defined above. [source,java,linenums] ---- @RestController public class MyRestController { @Autowired private MyService myService; @PostMapping(value=""/process"") public void startProcessInstance() { myService.startProcess(); } @RequestMapping(value=""/tasks"", method= RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) public List getTasks(@RequestParam String assignee) { List tasks = myService.getTasks(assignee); List dtos = new ArrayList(); for (Task task : tasks) { dtos.add(new TaskRepresentation(task.getId(), task.getName())); } return dtos; } static class TaskRepresentation { private String id; private String name; public TaskRepresentation(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ---- Both the _@Service_ and the _@RestController_ will be found by the automatic component scan for a Spring Boot application. Run the application class again. We can now interact with the REST API, for example, by using cURL: ---- curl http://localhost:8080/tasks?assignee=kermit [] curl -X POST http://localhost:8080/process curl http://localhost:8080/tasks?assignee=kermit [{""id"":""10004"",""name"":""my task""}] ---- As can be seen, we are referring to the assignee, ""kermit"", which was hard-coded into the process definition XML earlier. We'll change this later on to allow the assignee to be set when the workflow instance is started. ==== JPA support To add JPA support for Flowable in Spring Boot, add following dependency: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter ${flowable.version} org.springframework.boot spring-boot-starter-data-jpa ${spring-boot.version ---- This will add in the Spring configuration and beans for using JPA. By default, the JPA provider will be Hibernate. Let's create a simple Entity class: [source,java,linenums] ---- @Entity class Person { @Id @GeneratedValue private Long id; private String username; private String firstName; private String lastName; private Date birthDate; public Person() { } public Person(String username, String firstName, String lastName, Date birthDate) { this.username = username; this.firstName = firstName; this.lastName = lastName; this.birthDate = birthDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } } ---- By default, when not using an in-memory database, the tables won't be created automatically. Create a file _application.properties_ on the classpath and add following property: ---- spring.jpa.hibernate.ddl-auto=update ---- Add following class: [source,java,linenums] ---- @Repository public interface PersonRepository extends JpaRepository { Person findByUsername(String username); } ---- This is a Spring repository, which offers CRUD out of the box. We add the method to find a Person by username. Spring will automatically implement this based on conventions (typically, the property names used). We now enhance our service further: * by adding _@Transactional_ to the class. Note that by adding the JPA dependency above, the DataSourceTransactionManager which we were using before is now automatically swapped out by a JpaTransactionManager. * The _startProcess_ now gets an assignee username passed in, which is used to look up the Person, and put the Person JPA object as a process variable in the process instance. * A method to create Dummy users is added. This is used in the CommandLineRunner to populate the database. [source,java,linenums] ---- @Service @Transactional public class MyService { @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Autowired private PersonRepository personRepository; public void startProcess(String assignee) { Person person = personRepository.findByUsername(assignee); Map variables = new HashMap(); variables.put(""person"", person); runtimeService.startProcessInstanceByKey(""oneTaskProcess"", variables); } public List getTasks(String assignee) { return taskService.createTaskQuery().taskAssignee(assignee).list(); } public void createDemoUsers() { if (personRepository.findAll().size() == 0) { personRepository.save(new Person(""jbarrez"", ""Joram"", ""Barrez"", new Date())); personRepository.save(new Person(""trademakers"", ""Tijs"", ""Rademakers"", new Date())); } } } ---- The CommandLineRunner now looks like: [source,java,linenums] ---- @Bean public CommandLineRunner init(final MyService myService) { return new CommandLineRunner() { public void run(String... strings) throws Exception { myService.createDemoUsers(); } }; } ---- The RestController is also modified slightly to incorporate the changes above (only showing new methods) and the HTTP POST now has a body that contains the assignee username: ---- @RestController public class MyRestController { @Autowired private MyService myService; @PostMapping(value=""/process"") public void startProcessInstance(@RequestBody StartProcessRepresentation startProcessRepresentation) { myService.startProcess(startProcessRepresentation.getAssignee()); } ... static class StartProcessRepresentation { private String assignee; public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } } ---- And finally, to try out the Spring-JPA-Flowable integration, we assign the task using the ID of the Person JPA object in the process definition: [source,xml,linenums] ---- ---- This replaces the hard-coded recipient, ""kermit"", which we had initially set. We can now start a new process instance, providing the user name in the POST body: ---- curl -H ""Content-Type: application/json"" -d '{""assignee"" : ""jbarrez""}' http://localhost:8080/process ---- And the task list is now fetched using the person ID: ---- curl http://localhost:8080/tasks?assignee=1 [{""id"":""12505"",""name"":""my task""}] ---- [[springBootActuatorEndpoint]] ==== Flowable Actuator Endpoints Flowable provides a Spring Boot Actuator Endpoint that exposes information for the Processes that are running. By default the `flowable` endpoint is mapped to `/actuator/flowable`. Spring Boot by default only exposes the `info` and `health` endpoints. In order to enable the `flowable` endpoint you need to add `management.endpoint.flowable.enabled=true` to your `application.properties`. In order to make enable Actuator endpoints you need to add a dependency on Actuator, e.g. by using {sc-flowable-starter}/flowable-spring-boot-starter-actuator/pom.xml[flowable-spring-boot-starter-actuator]. `curl http://localhost:8080/actuator/flowable` [source,json] ---- { ""completedTaskCountToday"": 0, ""deployedProcessDefinitions"": [ ""oneTaskProcess (v1)"" ], ""processDefinitionCount"": 1, ""cachedProcessDefinitionCount"": 0, ""runningProcessInstanceCount"": { ""oneTaskProcess (v1)"": 0 }, ""completedTaskCount"": 2, ""completedActivities"": 3, ""completedProcessInstanceCount"": { ""oneTaskProcess (v1)"": 0 }, ""openTaskCount"": 0 } ---- For more information about Spring Boot Actuator see link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html$$[Production Ready Endpoint] in the Spring Boot reference documentation. [[springBootInfoContributor]] ==== Flowable Info Contributor Flowable also provides a Spring Boot `InfoContributor` which looks like: `curl http://localhost:8080/actuator/info` [source,json] ---- { ""flowable"": { ""version"": ""6.5.0-SNAPSHOT"" } } ---- [[springBootFlowableProperties]] ==== Flowable Application Properties The Flowable auto configuration is leveraging the Spring Boot properties and configuration mechanism. See link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html$$[Properties and Configuration] in the Spring Boot reference guide. Here is a list of configuration properties that the Flowable Spring Boot support consumes. [source,properties,indent=0,subs=""verbatim,attributes,macros""] ---- # =================================================================== # Common Flowable Spring Boot Properties # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # =================================================================== # Core (Process) {sc-flowable-boot}/FlowableProperties.java[FlowableProperties] flowable.check-process-definitions=true # Whether process definitions need to be auto deployed. flowable.custom-mybatis-mappers= # The FQN of custom Mybatis mappers that need to be added to the engine. flowable.custom-mybatis-x-m-l-mappers= # The location of the custom Mybatis XML Mappers that need to be added to the engine. flowable.database-schema= # In some situations you want to set the schema to use for table checks / generation if the database metadata doesn't return that correctly. flowable.database-schema-update=true # The strategy that should be used for the database schema. flowable.db-history-used=true # Whether db history should be used. flowable.deployment-name=SpringBootAutoDeployment # The name of the auto deployment. flowable.history-level=audit # The history level that needs to be used. flowable.process-definition-location-prefix=classpath*:/processes/ # The folder in which processes need to be searched for auto deployment. flowable.process-definition-location-suffixes=**.bpmn20.xml,**.bpmn # The suffixes (extensions) of the files that needs to be deployed from the 'processDefinitionLocationPrefix' location. # Process {sc-flowable-boot}/process/FlowableProcessProperties.java[FlowableProcessProperties] flowable.process.definition-cache-limit=-1 # The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions). flowable.process.enable-safe-xml=true # Enables extra checks on the BPMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.process.servlet.load-on-startup=-1 # Load on startup of the Process dispatcher servlet. flowable.process.servlet.name=Flowable BPMN Rest API # The name of the Process servlet. flowable.process.servlet.path=/process-api # The context path for the Process rest servlet. # Process Async Executor flowable.process.async-executor-activate=true # Whether the async executor should be activated. flowable.process.async.executor.async-job-lock-time-in-millis=300000 # The amount of time (in milliseconds) an async job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. flowable.process.async.executor.default-async-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the async job acquisition thread will wait to execute the next acquirement query. This happens when no new async jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.process.async.executor.default-queue-size-full-wait-time-in-millis=0 # The time (in milliseconds) the async job (both timer and async continuations) acquisition thread will wait when the queue is full to execute the next query. By default set to 0 (for backwards compatibility) flowable.process.async.executor.default-timer-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the timer job acquisition thread will wait to execute the next acquirement query. This happens when no new timer jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.process.async.executor.max-async-jobs-due-per-acquisition=1 # ??? flowable.process.async.executor.retry-wait-time-in-millis=500 # ??? flowable.process.async.executor.timer-lock-time-in-millis=300000 # The amount of time (in milliseconds) a timer job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. # CMMN {sc-flowable-boot}/cmmn/FlowableCmmnProperties.java[FlowableCmmnProperties] flowable.cmmn.deploy-resources=true # Whether to perform deployment of resources, default is 'true'. flowable.cmmn.deployment-name=SpringBootAutoDeployment # The name of the deployment for the CMMN resources. flowable.cmmn.enable-safe-xml=true # Enables extra checks on the DMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.cmmn.enabled=true # Whether the CMMN engine needs to be started. flowable.cmmn.resource-location=classpath*:/cases/ # The location where the CMMN resources are located. flowable.cmmn.resource-suffixes=**.cmmn,**.cmmn11,**.cmmn.xml,**.cmmn11.xml # The suffixes for the resources that need to be scanned. flowable.cmmn.servlet.load-on-startup=-1 # Load on startup of the CMMN dispatcher servlet. flowable.cmmn.servlet.name=Flowable CMMN Rest API # The name of the CMMN servlet. flowable.cmmn.servlet.path=/cmmn-api # The context path for the CMMN rest servlet. # CMMN Async Executor flowable.cmmn.async-executor-activate=true # Whether the async executor should be activated. flowable.cmmn.async.executor.async-job-lock-time-in-millis=300000 # The amount of time (in milliseconds) an async job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. flowable.cmmn.async.executor.default-async-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the async job acquisition thread will wait to execute the next acquirement query. This happens when no new async jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.cmmn.async.executor.default-queue-size-full-wait-time-in-millis=0 # The time (in milliseconds) the async job (both timer and async continuations) acquisition thread will wait when the queue is full to execute the next query. By default set to 0 (for backwards compatibility) flowable.cmmn.async.executor.default-timer-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the timer job acquisition thread will wait to execute the next acquirement query. This happens when no new timer jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.cmmn.async.executor.max-async-jobs-due-per-acquisition=1 # ??? flowable.cmmn.async.executor.retry-wait-time-in-millis=500 # ??? flowable.cmmn.async.executor.timer-lock-time-in-millis=300000 # The amount of time (in milliseconds) a timer job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. # Content {sc-flowable-boot}/content/FlowableContentProperties.java[FlowableContentProperties] flowable.content.enabled=true # Whether the content engine needs to be started. flowable.content.servlet.load-on-startup=-1 # Load on startup of the Content dispatcher servlet. flowable.content.servlet.name=Flowable Content Rest API # The name of the Content servlet. flowable.content.servlet.path=/content-api # The context path for the Content rest servlet. flowable.content.storage.create-root=true # If the root folder doesn't exist, should it be created? flowable.content.storage.root-folder= # Root folder location where content files will be stored, for example, task attachments or form file uploads. # DMN {sc-flowable-boot}/dmn/FlowableDmnProperties.java[FlowableDmnProperties] flowable.dmn.deploy-resources=true # Whether to perform deployment of resources, default is 'true'. flowable.dmn.deployment-name=SpringBootAutoDeployment # The name of the deployment for the dmn resources. flowable.dmn.enable-safe-xml=true # Enables extra checks on the DMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.dmn.enabled=true # Whether the dmn engine needs to be started. flowable.dmn.history-enabled=true # Whether the history for the DMN engine should be enabled. flowable.dmn.resource-location=classpath*:/dmn/ # The location where the dmn resources are located. flowable.dmn.resource-suffixes=**.dmn,**.dmn.xml,**.dmn11,**.dmn11.xml # The suffixes for the resources that need to be scanned. flowable.dmn.servlet.load-on-startup=-1 # Load on startup of the DMN dispatcher servlet. flowable.dmn.servlet.name=Flowable DMN Rest API # The name of the DMN servlet. flowable.dmn.servlet.path=/dmn-api # The context path for the DMN rest servlet. flowable.dmn.strict-mode=true # Set this to false if you want to ignore the decision table hit policy validity checks to result in an failed decision table state. A result is that intermediate results created up to the point the validation error occurs are returned. # Form {sc-flowable-boot}/form/FlowableFormProperties.java[FlowableFormProperties] flowable.form.deploy-resources=true # Whether to perform deployment of resources, default is true. flowable.form.deployment-name=SpringBootAutoDeployment # The name of the deployment for the form resources. flowable.form.enabled=true # Whether the form engine needs to be started. flowable.form.resource-location=classpath*:/forms/ # The location where the form resources are located. flowable.form.resource-suffixes=**.form # The suffixes for the resources that need to be scanned. flowable.form.servlet.load-on-startup=-1 # Load on startup of the Form dispatcher servlet. flowable.form.servlet.name=Flowable Form Rest API # The name of the Form servlet. flowable.form.servlet.path=/form-api # The context path for the Form rest servlet. # IDM {sc-flowable-boot}/idm/FlowableIdmProperties.java[FlowableIdmProperties] flowable.idm.enabled=true # Whether the idm engine needs to be started. flowable.idm.password-encoder= # The type of the password encoder that needs to be used. flowable.idm.servlet.load-on-startup=-1 # Load on startup of the IDM dispatcher servlet. flowable.idm.servlet.name=Flowable IDM Rest API # The name of the IDM servlet. flowable.idm.servlet.path=/idm-api # The context path for the IDM rest servlet. # IDM Ldap {sc-flowable-boot}/ldap/FlowableLdapProperties.java[FlowableLdapProperties] flowable.idm.ldap.attribute.email= # Name of the attribute that matches the user email. flowable.idm.ldap.attribute.first-name= # Name of the attribute that matches the user first name. flowable.idm.ldap.attribute.group-id= # Name of the attribute that matches the group id. flowable.idm.ldap.attribute.group-name= # Name of the attribute that matches the group name. flowable.idm.ldap.attribute.group-type= # Name of the attribute that matches the group type. flowable.idm.ldap.attribute.last-name= # Name of the attribute that matches the user last name. flowable.idm.ldap.attribute.user-id= # Name of the attribute that matches the user id. flowable.idm.ldap.base-dn= # The base 'distinguished name' (DN) from which the searches for users and groups are started. flowable.idm.ldap.cache.group-size=-1 # Allows to set the size of the {@link org.flowable.ldap.LDAPGroupCache}. This is an LRU cache that caches groups for users and thus avoids hitting the LDAP system each time the groups of a user needs to be known. flowable.idm.ldap.custom-connection-parameters= # Allows to set all LDAP connection parameters which do not have a dedicated setter. See for example http://docs.oracle.com/javase/tutorial/jndi/ldap/jndi.html for custom properties. Such properties are for example to configure connection pooling, specific security settings, etc. flowable.idm.ldap.enabled=false # Whether to enable LDAP IDM Service. flowable.idm.ldap.group-base-dn= # The base 'distinguished name' (DN) from which the searches for groups are started. flowable.idm.ldap.initial-context-factory=com.sun.jndi.ldap.LdapCtxFactory # The class name for the initial context factory. flowable.idm.ldap.password= # The password that is used to connect to the LDAP system. flowable.idm.ldap.port=-1 # The port on which the LDAP system is running. flowable.idm.ldap.query.all-groups= # The query that is executed when searching for all groups. flowable.idm.ldap.query.all-users= # The query that is executed when searching for all users. flowable.idm.ldap.query.groups-for-user= # The query that is executed when searching for the groups of a specific user. flowable.idm.ldap.query.user-by-full-name-like= # The query that is executed when searching for a user by full name. flowable.idm.ldap.query.user-by-id= # The query that is executed when searching for a user by userId. flowable.idm.ldap.query.group-by-id= # The query that is executed when searching for a specific group by groupId. flowable.idm.ldap.search-time-limit=0 # The timeout (in milliseconds) that is used when doing a search in LDAP. By default set to '0', which means 'wait forever'. flowable.idm.ldap.security-authentication=simple # The value that is used for the 'java.naming.security.authentication' property used to connect to the LDAP system. flowable.idm.ldap.server= # The server host on which the LDAP system can be reached. For example 'ldap://localhost'. flowable.idm.ldap.user= # The user id that is used to connect to the LDAP system. flowable.idm.ldap.user-base-dn= # The base 'distinguished name' (DN) from which the searches for users are started. # Flowable Mail {sc-flowable-boot}/FlowableMailProperties.java[FlowableMailProperties] flowable.mail.server.default-from=flowable@localhost # The default from address that needs to be used when sending emails. flowable.mail.server.force-to= # The force to address(es) that would be used when sending out emails. IMPORTANT: If this is set then all emails will be send to defined address(es) instead of the address configured in the MailActivity. flowable.mail.server.host=localhost # The host of the mail server. flowable.mail.server.password= # The password for the mail server authentication. flowable.mail.server.port=1025 # The port of the mail server. flowable.mail.server.use-ssl=false # Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). flowable.mail.server.use-tls=false # Set or disable the STARTTLS encryption. flowable.mail.server.username= # The username that needs to be used for the mail server authentication. If empty no authentication would be used. # Flowable Http {sc-flowable-boot}/FlowableHttpProperties.java[FlowableHttpProperties] flowable.http.user-system-properties=false # Whether to use system properties (e.g. http.proxyPort). flowable.http.connect-timeout=5s # Connect timeout for the http client flowable.http.socket-timeout=5s # Socket timeout for the http client flowable.http.connection-request-timeout=5s # Connection Request Timeout for the http client flowable.http.request-retry-limit=3 # Request retry limit for the http client flowable.http.disable-cert-verify=false # Whether to disable certificate validation for the http client # Flowable REST flowable.rest.app.cors.enabled=true # Whether to enable CORS requests at all. If false, the other properties have no effect flowable.rest.app.cors.allow-credentials=true # Whether to include credentials in a CORS request flowable.rest.app.cors.allowed-origins=* # Comma-separated URLs to accept CORS requests from flowable.rest.app.cors.allowed-headers=* # Comma-separated HTTP headers to allow in a CORS request flowable.rest.app.cors.allowed-methods=DELETE,GET,PATCH,POST,PUT # Comma-separated HTTP verbs to allow in a CORS request flowable.rest.app.cors.exposed-headers=* # Comma-separated list of headers to expose in CORS response # Actuator management.endpoint.flowable.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.flowable.enabled=true # Whether to enable the flowable endpoint. ---- .Deprecated properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.process.servlet.name |flowable.rest-api-servlet-name |Flowable BPMN Rest API |The name of the Process servlet. |flowable.process.servlet.path |flowable.rest-api-mapping |/process-api |The context path for the Process rest servlet. |flowable.mail.server.host |flowable.mail-server-host |localhost |The host of the mail server. |flowable.mail.server.password |flowable.mail-server-password |- |The password for the mail server authentication. |flowable.mail.server.port |flowable.mail-server-port |1025 |The port of the mail server. |flowable.mail.server.use-ssl |flowable.mail-server-use-ssl |false |Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). |flowable.mail.server.use-tls |flowable.mail-server-use-tls |false |Set or disable the STARTTLS encryption. |flowable.mail.server.username |flowable.mail-server-user-name |- |The username that needs to be used for the mail server authentication. If empty no authentication would be used. |flowable.process.definition-cache-limit |flowable.process-definitions.cache.max |-1 |The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions) |=============== [[springBootFlowableAutoConfiguration]] ==== Flowable Auto-configuration classes Here is a list of all auto-configuration classes provided by Flowable, with links to documentation and source code. Remember to also look at the conditions report in your application for more details of which features are switched on. (To do so, start the app with --debug or -Ddebug or, in an Actuator application, use the conditions endpoint). [cols=*,options=""header""] |=== |Configuration Class |{sc-flowable-boot}/content/ContentEngineAutoConfiguration.java[ContentEngineAutoConfiguration] |{sc-flowable-boot}/content/ContentEngineServicesAutoConfiguration.java[ContentEngineServicesAutoConfiguration] |{sc-flowable-boot}/cmmn/CmmnEngineAutoConfiguration.java[CmmnEngineAutoConfiguration] |{sc-flowable-boot}/cmmn/CmmnEngineServicesAutoConfiguration.java[CmmnEngineServicesAutoConfiguration] |{sc-flowable-boot}/dmn/DmnEngineAutoConfiguration.java[DmnEngineAutoConfiguration] |{sc-flowable-boot}/dmn/DmnEngineServicesAutoConfiguration.java[DmnEngineServicesAutoConfiguration] |{sc-flowable-boot}/EndpointAutoConfiguration.java[EndpointAutoConfiguration] |{sc-flowable-boot}/actuate/info/FlowableInfoAutoConfiguration.java[FlowableInfoAutoConfiguration] |{sc-flowable-boot}/ldap/FlowableLdapAutoConfiguration.java[FlowableLdapAutoConfiguration] |{sc-flowable-boot}/FlowableTransactionAutoConfiguration.java[FlowableTransactionAutoConfiguration] |{sc-flowable-boot}/form/FormEngineAutoConfiguration.java[FormEngineAutoConfiguration] |{sc-flowable-boot}/form/FormEngineServicesAutoConfiguration.java[FormEngineServicesAutoConfiguration] |{sc-flowable-boot}/idm/IdmEngineAutoConfiguration.java[IdmEngineAutoConfiguration] |{sc-flowable-boot}/idm/IdmEngineServicesAutoConfiguration.java[IdmEngineServicesAutoConfiguration] |{sc-flowable-boot}/ProcessEngineAutoConfiguration.java[ProcessEngineAutoConfiguration] |{sc-flowable-boot}/RestApiAutoConfiguration.java[RestApiAutoConfiguration] |{sc-flowable-boot}/SecurityAutoConfiguration.java[SecurityAutoConfiguration] |=== [[springBootFlowableStarter]] ==== Flowable Starters Here is a list of the flowable spring boot starters. [cols=2*,options=""header""] |=== |Starter |Description |{sc-flowable-starter}/flowable-spring-boot-starter-cmmn/pom.xml[flowable-spring-boot-starter-cmmn] |Contains the dependencies for booting the CMMN Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-cmmn-rest/pom.xml[flowable-spring-boot-starter-cmmn-rest] |Contains the dependencies for booting the CMMN Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter-dmn/pom.xml[flowable-spring-boot-starter-dmn] |Contains the dependencies for booting the DMN Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-dmn-rest/pom.xml[flowable-spring-boot-starter-dmn-rest] |Contains the dependencies for booting the DMN Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter-process/pom.xml[flowable-spring-boot-starter-process] |Contains the dependencies for booting the Process Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-process-rest/pom.xml[flowable-spring-boot-starter-process-rest] |Contains the dependencies for booting the Process Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter/pom.xml[flowable-spring-boot-starter] |Contains the dependencies for booting all Flowable Engines (Process, CMMN, DMN, Form, Content and IDM) |{sc-flowable-starter}/flowable-spring-boot-starter-rest/pom.xml[flowable-spring-boot-starter-rest] |Contains the dependencies for booting all Flowable Engines and their respective REST API |{sc-flowable-starter}/flowable-spring-boot-starter-actuator/pom.xml[flowable-spring-boot-starter-actuator] |Contains the required dependencies for Spring Boot |=== ==== Using Liquibase The Flowable engines are using Liquibase to manage the versioning of it's tables. This means that the `LiquibaseAutoConfiguration` from Spring Boot would automatically kick in. However, if you are not using Liquibase then the application will not start and would throw an exception. For this reason Flowable is setting `spring.liquibase.enabled` to `false`, which means that if you need to use Liquibase you have to explicitly enable it. ==== Further Reading Obviously, there is a lot about Spring Boot that hasn't been touched upon yet, like very easy JTA integration or building a WAR file that can be run on major application servers. And there is a lot more to the Spring Boot integration: * Actuator support * Spring Integration support * Rest API integration: boot up the Flowable Rest API embedded within the Spring application * Spring Security support ==== Advanced Configuration ===== Customizing Engine Configuration It's possible to get a hold of the engine configuration by implementing the _org.flowable.spring.boot.EngineConfigurationConfigurer_ interface. Where _T_ is the Spring Type of the particular Engine Configuration. This can be useful for advanced configuration settings or simply because a property has not been exposed (yet). For example: [source, java, linenums] ---- public class MyConfigurer implements EngineConfigurationConfigurer { public void configure(SpringProcessEngineConfiguration processEngineConfiguration) { // advanced configuration } } ---- By exposing an instance of this class as an _@Bean_ in the Spring Boot configuration, the instance will be called before the process engine is fully created. [TIP] ==== You can provide a custom implementation of a Flowable Service by using this. See {sc-flowable-boot}/ldap/FlowableLdapAutoConfiguration.java[FlowableLdapAutoConfiguration] ==== ===== Combining starters In case you need only a combination of the engines then you can add only the required dependencies. For example to use the Process, CMMN, Form and IDM engine and use LDAP you need to add the following dependencies: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter-process ${flowable.version} org.flowable flowable-spring-boot-starter-cmmn ${flowable.version} org.flowable flowable-content-spring-configurator ${flowable.version} org.flowable flowable-form-spring-configurator ${flowable.version} org.flowable flowable-ldap ${flowable.version} ---- ===== Configuring Async Executors The Process and CMMN engines have dedicated `AsyncExecutor`(s) and they can be configured with the `flowable.{engine}.async.executor` property group. Where `engine` is either `process` or `cmmn`. The `AsyncExecutor`(s) per default share the same Spring `TaskExecutor` and `SpringRejectedJobsHandler`. In case you want to provide a dedicated executor for each of the engines you need define a qualified bean with `@Process` and `@Cmmn`. You can configure custom executors in the following way: [source,java,linenums] ---- @Configuration public class MyConfiguration { @Process <1> @Bean public TaskExecutor processTaskExecutor() { return new SimpleAsyncTaskExecutor(); } @Cmmn <2> @Bean public TaskExecutor cmmnTaskExecutor() { return new SyncTaskExecutor(); } } ---- <1> The Async Executor for the Process Engine would use a `SimpleAsyncTaskExecutor` <2> The Async Executor for the CMMN Engine would use a `SyncTaskExecutor` [IMPORTANT] ====== If you define a custom `TaskExecutor` bean the Flowable creation of the bean is not triggered. Which means that if you define a bean qualified with `@Process` you have to define one with `@Cmmn` or `@Primary`, otherwise the Cmmn Async Executor will use the one for the Process ====== ",12193,False,1877.2186512817584,median " Plugin Version @PLUGIN_VERSION@ Revised on May 27, 2019 == Supported versions This plugin was developed and tested against Chef version 10.12.0. IMPORTANT: For all parameter descriptions in the following sections, the required parameters are in [.required]#bold italics#. IMPORTANT: In the {CD} UI, go to the Home page, open the Main Menu, and click *Admin* > *Plugins* to open the Plugin Manager. [[CreateConfiguration]] [[setupconfig]] == Setting up the plugin configuration Plugin configurations are sets of parameters that apply across some or all of the plugin procedures. They reduce repetition of common values, create predefined sets of parameters for end users, and store credentials securely. Each configuration has a unique name that is automatically entered in designated parameters in the procedures. === Input . Go to *Administration* > *Plugins* to open the Plugin Manager. . Find the EC-Chef row. . Click *Configure* to open the Chef Configurations page. . Click *Create Configuration*. . Create a Chef configuration by entering the following information and clicking *OK*. Remember that you might need to create additional configurations later. === Output The Chef Configurations page now shows the new configuration. [[procedures]] == Plugin procedures NOTE: The __DeleteNode__ and __RegisterAndConvergeNode__ procedures are internal procedures that run automatically when you provision cloud resources for dynamic environments. Do not run these procedures. === AddRecipesToNodeRunList procedure The following procedure adds recipes and roles to a node run-list. Run-list items are not validated against the Chef server. The command syntax is: node run_list add ==== Input . Go to the AddRecipesToNodeRunList procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Path to the knife executable, such as _/usr/bin/knife_ (the default value). (Required) |Configuration File |Path to the configuration file, such as _root/.chef/knife.rb_ (the default value). (Required) |Server URL |URL of the Chef server. |Node Name |Name of the node to which recipes are added. (Required) |Run-List Items |Run-list items to add to the node run-list. You must enclose the items in quotes when roles are added, roles are combined with recipes, the fully qualified recipe format is used, or the cookbook recipe format is used. The run-list items are not validated against the Chef server. |Verbose |Displays the more-verbose output format when checked. |After Item |Item in the node run-list that determines where new items are added. The new items are added to the node run-list after the specified item, such as recipe[my_recipe]. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *AddRecipesToNodeRunList* step, click the Log button to see the diagnostic information. [[Bootstrap]] === Bootstrap procedure The following procedure invokes the knife bootstrap subcommand to run a bootstrap operation that installs the chef-client on the target system. The bootstrap operation must specify the IP address or FQDN of the target system. The command syntax is: bootstrap ==== Input . Go to the Bootstrap procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Path to the knife executable, such as _/usr/bin/knife_ (the default value). (Required) |FQDN or Node IP |Provide the IP address of the node to be bootstrapped. (Required) |SSH Agent Forwarding |If checked enables ssh agent forwarding. |Verify API Cert |Verify the SSL certificate on the Chef server. When true, the chef-client always verifies the SSL certificate. When false, the chef-client uses the value of ssl_verify_mode to determine if the SSL certificate requires verification. If this option is not specified, the setting for verify_api_cert in the configuration file is applied |Disable Host key verify |Use --no-host-key-verify to disable host key verification. Default setting: --host-key-verify. |Prerelease gems |Install pre-release gems. |Use sudo password |Perform a bootstrap operation with sudo; specify the password with the -P (or --ssh-password) option. |Sudo |Execute a bootstrap operation with sudo. |Bootstrap Curl options |Specify arbitrary options to be added to the bootstrap command when using Curl |Bootstrap install command |Execute a custom installation command sequence for the chef-client. |Bootstrap install sh |Fetch and execute an installation script at the specified URL |Bootstrap no proxy |The proxy server for the node that is the target of a bootstrap operation. |Bootstrap proxy |The proxy server for the node that is the target of a bootstrap operation. |Bootstrap vault file |The path to a JSON file that contains a list of vaults and items to be updated. |Bootstrap vault item |A single vault and item to update as vault item. |Bootstrap vault JSON |A JSON string that contains a list of vaults and items to be updated. |Bootstrap version |The version of the chef-client to install. |Bootstrap Wget options |Specify arbitrary options to be added to the bootstrap command when using GNU Wget. This option may not be used in the same command with --bootstrap-install-command. |Environment |The name of the environment. When this option is added to a command, the command will run only against the named environment. |SSH Gateway |The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. |Hint |Ohai hints are used to tell Ohai something about the system that it is running on that it would not be able to discover itself |Identify File |The SSH identity file used for authentication. Key-based authentication is recommended. |JSON Attributes |A JSON string that is added to the first run of a chef-client |Node name |The name of the node. |SSH port |The SSH port. |Run list |A comma-separated list of roles and/or recipes to be applied. |Secret key within databag item |The encryption key that is used for values contained within a data bag item. |Secret key path |The path to the file that contains the encryption key. |Bootstrap template |The bootstrap template to use. This may be the name of a bootstrap template or it may be the full path to an Embedded Ruby (ERB) template that defines a custom bootstrap. Default value: chef-full, which installs the chef-client using the omnibus installer on all supported platforms |Debug log-level |Run the initial chef-client run at the debug log-level (e.g. chef-client -l debug). |SSH username |The SSH user name. |SSH password |The SSH password. |SSL verify mode |Set the verify mode for HTTPS requests.Use none to do no validation of SSL certificates.Use peer to do validation of all SSL certificates, including the Chef server connections, S3 connections, and any HTTPS remote_file resource URLs used in the chef-client run. This is the recommended setting. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *Bootstrap* step, click the Log button to see the diagnostic information. [[CookbookLinting]] === CookbookLinting procedure The following procedure makes use of the foodcritic linting tool to check your Chef cookbooks for common problems.It comes with 47 built-in rules that identify problems ranging from simple style inconsistencies to difficult to diagnose issues that will hurt in production. The command syntax is: foodcritic ==== Input . Go to the CookbookLinting procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Cookbook Path |Path of Cookbook. (Required) |Failure Tags |Use to trigger a build failure if any of the specified tags are matched. |Rules Path |Use to specify the path to a file that contains additional Foodcritic rules. |Grammer Path |Use to specify the path to a file that contains additional grammar used when validating search syntax |Checked Tags |Use to only the specified tags when checking against Foodcritic rules. |Show FoodCritic Version |Use to display the version of Foodcritic. |Show Context |Use to show lines matched against Foodcritic rules, rather than the default summary. |REPL |Use to drop into a REPL for interactive rule editing. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *CookbookLinting* step, click the Log button to see the diagnostic information. [[CookbookUnitTesting]] === CookbookUnitTesting procedure The following procedure uses rspec utility to run and test your cookbooks before committing them locally with Chef Solo without actually converging with a node. The command syntax is: chef exec rspec < Cookbook Ppath > ==== Input . Go to the CookbookUnitTesting procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Spec Path |Provide the path to the Spec file or folder. (Required) |Server URL |Provide the URL of the Chef Server to use |Load Path |Specify PATH to add to $LOAD_PATH (may be used more than once). |Default Path |Set the default path where RSpec looks for examples (can be a path to a file or a directory) |Example |Run examples whose full nested names include STRING (may be used more than once). |Tag |Run examples with the specified tag, or exclude examples by adding ~ before the tag |Exclude Pattern |Load files except those matching pattern. Opposite effect of --pattern. |Pattern |Load files matching pattern .Default: ""spec/**/*_spec.rb"" |Profiling |Enable profiling of examples and list the slowest examples (default: 10) |Deprecation File Path |Write deprecation warnings to a file instead of $stderr. |Out File Path |Write output to a file instead of $stdout. This option applies to the previously specified --format, or the default format if no format is specified |Format |Choose a formatter. [p]rogress (default - dots) [d]ocumentation (group and example names) [h]tml [j]son custom formatter class name |Failure Exit Code |Override the exit code used when there are failing specs. |DRb Port |Port to connect to the DRb server. |Require Path |Require a file. |Options Path |Specify the path to a custom options file. |Order |Run examples by the specified order type. [defined] examples and groups are run in the order they are defined [rand] randomize the order of groups and examples [random] alias for rand [random:SEED] e.g. --order random:123 |Seed |Equivalent of --order rand:SEED.. |Next Failure |Apply `--only-failures` and abort after one failure. |Only Failures |Filter to just the examples that failed the last time they ran. |Backtrace |Enable full backtrace |Warnings |Enable ruby warnings. |Color |Enable color in the output |Bisect |Repeatedly runs the suite in order to isolate the failures to the smallest reproducible case. |Initialize with RSpec |Initialize your project with RSpec. |DRb |Run examples via DRb. |Abort On First Failure |Abort the run on first failure. |Dry Run |Print the formatter output of your suite without running any examples or hooks. |Additional options |Additional options if any |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *Cookbook Unit Testing* step, click the Log button to see the diagnostic information. [[CreateClient]] === CreateClient procedure The following procedure is used to create API clients. The command syntax is: client create < Client Name > ==== Input . Go to the CreateClient procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Client Name |Mention the name of the client. This process will generate an RSA key pair for the named API client. The public key will be stored on the Chef server and the private key will be displayed on STDOUT or written to a named file. (Required) |Admin |Create a client as an admin client. This is required for any user to access Open Source Chef as an administrator. This option only works when used with the open source Chef server and will have no effect when used with Enterprise Chef.. |Save key to file |Save a private key to the specified file name. |Validator |Use to create the client as the chef-validator. Default value: true. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *CreateClient* step, click the Log button to see the diagnostic information. [[CreateClientKey]] === CreateClientKey The following procedure is used to create Public Keys. The command syntax is: client create < Client Name > ==== Input . Go to the CreateClient procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Client Name |Mention the name of the client. This process will generate an RSA key pair for the named API client. The public key will be stored on the Chef server and the private key will be displayed on STDOUT or written to a named file.(Required) |Admin |Create a client as an admin client. This is required for any user to access Open Source Chef as an administrator. This option only works when used with the open source Chef server and will have no effect when used with Enterprise Chef.. |Save key to file |Save a private key to the specified file name. |Validator |Use to create the client as the chef-validator. Default value: true. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *CreateClient* step, click the Log button to see the diagnostic information. [[CreateCookbook]] === CreateCookbook procedure The following procedure is used to create cookbooks. The command syntax is: cookbook create < Cookbook Name > < Options > ==== Input . Go to the CreateCookbook procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Cookbook Name |Name of the cookbook to be generated.(Required) |Copyright holder |The name of the copyright holder. This option places a copyright notice that contains the name of the copyright holder in each of the pre-created files. If this option is not specified, a copyright name of your_company_name is used instead; it can easily be modified later. |License |The type of license under which a cookbook is distributed: apachev2, gplv2, gplv3, mit, or none (default). This option places the appropriate license notice in the pre-created files. |Email |The email address for the individual who maintains the cookbook. This option places an email address in each of the pre-created files. If not specified, an email name of your_email is used instead; this can easily be modified later. |Cookbook-path |The directory in which cookbooks are created. This can be a colon-separated path. |Readme format |The document format of the readme file: md (markdown) and rdoc (Ruby docs). |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *CreateCookbook* step, click the Log button to see the diagnostic information. [[CreateDataBag]] === CreateDataBag procedure The following procedure is used to create databags. The command syntax is: data bag create < DataBag Name > < Options > ==== Input . Go to the CreateDataBag procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Data Bag Name |Name of the Data Bag to be generated.(Required) |Data Bag Item |The name of a specific item within a data bag. |Secret Key |The encryption key that is used for values contained within a data bag item. |Secret Key File Path |The path to the file that contains the encryption key. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *CreateDataBag* step, click the Log button to see the diagnostic information. [[CreateNode]] === CreateNode procedure The following procedure is used to create nodes. The command syntax is: node create < Node Name > < Options > ==== Input . Go to the CreateNode procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Node Name |Name of the Node to be created.(Required) |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *CreateNode* step, click the Log button to see the diagnostic information. [[CreateRole]] === CreateRole procedure The following procedure is used to create roles. The command syntax is: role create < Role Name > < Options > ==== Input . Go to the CreateRole procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Role Name |Name of the Role to be created.(Required) |Description |If checked populates the description field for the role on the Chef server. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *CreateRole* step, click the Log button to see the diagnostic information. [[DeleteClient]] === DeleteClient procedure The following procedure is used to delete the registered API clients. The command syntax is: client delete < Client Name > ==== Input . Go to the DeleteClient procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Client Name |Mention the name of the client. This process will generate an RSA key pair for the named API client. The public key will be stored on the Chef server and the private key will be displayed on STDOUT or written to a named file.(Required) |Admin |Create a client as an admin client. This is required for any user to access Open Source Chef as an administrator. This option only works when used with the open source Chef server and will have no effect when used with Enterprise Chef. |Validator |Use to create the client as the chef-validator. Default value: true. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *DeleteClient* step, click the Log button to see the diagnostic information. [[DeleteClientKey]] === DeleteClientKey The following procedure is used to delete Public Keys. The command syntax is: client delete < Client Name > ==== Input . Go to the DeleteClientKey procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Client Name |Mention the name of the client. This process will generate an RSA key pair for the named API client. The public key will be stored on the Chef server and the private key will be displayed on STDOUT or written to a named file.(Required) |Public Key Name |The name of the public key to be deleted. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *DeleteClientKey* step, click the Log button to see the diagnostic information. [[DeleteCookbook]] === DeleteCookbook The following procedure is used to delete cookbooks. The command syntax is: cookbook delete < Cookbook Name > ==== Input . Go to the DeleteCookbook procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Cookbook Name |Name of the cookbook to be deleted.(Required) |All |Delete all cookbooks (and cookbook versions). |Purge |Entirely remove a cookbook (or cookbook version) from the Chef server. Use this action carefully because only one copy of any single file is stored on the Chef server. Consequently, purging a cookbook disables any other cookbook that references one or more files from the cookbook that has been purged. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *DeleteCookbook* step, click the Log button to see the diagnostic information. [[DeleteDatabag]] === DeleteCookbook The following procedure is used to delete databags. The command syntax is: databag delete < Databag Name > ==== Input . Go to the DeleteDatabag procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Databag Name |Name of the Databag to be deleted.(Required) |Databag Item |The name of a specific item within a data bag. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *DeleteDatabag* step, click the Log button to see the diagnostic information. [[DeleteSingleNode]] === DeleteSingleNode The following procedure is used to delete a node. The command syntax is: node delete < Node Name > ==== Input . Go to the DeleteSingleNode procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Node Name |Name of the node to be deleted.(Required) |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *DeleteSingleNode* step, click the Log button to see the diagnostic information. [[DeleteRole]] === DeleteRole The following procedure is used to delete roles. The command syntax is: role delete < Node Name > ==== Input . Go to the DeleteRole procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Role Name |Name of the role to be deleted.(Required) |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *DeleteRole* step, click the Log button to see the diagnostic information. [[DownloadCookbookFromRepository]] === DownloadCookbookFromRepository procedure The following procedure downloads a specific cookbook from the Opscode repository. The command syntax is: cookbook site download ==== Input . Go to the DownloadCookbookFromRepository procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Path to the knife executable, such as _/usr/bin/knife_ (the default value). (Required) |Configuration File |Path to the configuration file, such as _/root/.chef/knife.rb_ (the default value). (Required) |Chef Server URL |URL of the Chef server. |Cookbook Name |Name of the cookbook to download. (Required) |Cookbook Version |Cookbook version to download. If this field is blank, the latest version is downloaded. |Force |Downloads a deprecated cookbook. |Verbose |Displays the more verbose output format. |File Name |Name of the file to which the cookbook is written. The file extension is tar.gz. If this field is blank, the name of the default cookbook is used. |Download To |Path to which the cookbook is downloaded. If this field is blank, the cookbook is downloaded to the current workspace. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *DownloadCookbookFromRepository* step, click the Log button to see the diagnostic information. [[EditClientKey]] === EditClientKey procedure The following procedure can be used to edit an Clients's public key. The command syntax is: client key edit ==== Input . Go to the EditClientKey procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Path to the knife executable, such as _/usr/bin/knife_ (the default value). (Required) |Client Name |Mention the name of the client. This process will generate an RSA key pair for the named API client. The public key will be stored on the Chef server and the private key will be displayed on STDOUT or written to a named file.(Required) |Key Name |Name of key to be edited. |New Public key name |The name of the public key. |Save key to file |Save a public key to the specified file name. If the --key-name and public-key options are not specified the Chef server will generate a private key. |Path to public key file |The path to a file that contains the public key. If this option is not specified, and only if --key-name is specified, the Chef server will generate a public/private key pair. |Expiration Date |The expiration date for the public key, specified as an ISO 8601 formatted string: YYYY-MM-DDTHH:MM:SSZ. If this option is not specified, the public key will not have an expiration date. For example: 2013-12-24T21:00:00Z. |Replace key |Generate a new public/private key pair and replace an existing public key with the newly-generated public key. To replace the public key with an existing public key, use --public-key instead. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *EditClientKey* step, click the Log button to see the diagnostic information. [[EditDatabag]] === EditDatabag procedure The following procedure can be used to edit an Clients's databags. The command syntax is: data bag from file ==== Input . Go to the EditDatabag procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Path to the knife executable, such as _/usr/bin/knife_ (the default value). (Required) |Data Bag |Provide name of data bag. (Required) |Data Bag Item Content |Content of data bag item. |Secret Key |The encryption key that is used for values contained within a data bag item. |Secret Key File Path |The path to the file that contains the encryption key. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *EditDatabag* step, click the Log button to see the diagnostic information. [[EditNode]] === EditNode procedure The following procedure can be used to edit an node attributes. The command syntax is: ==== Input . Go to the EditNode procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Path to the knife executable, such as _/usr/bin/knife_ (the default value). (Required) |Node Name |Provide the name of the node to edit. (Required) |Node Data |Provide the data of the node. (Required) |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *EditNode* step, click the Log button to see the diagnostic information. [[EditRole]] === EditRole procedure The following procedure can be used to edit an roles attributes. The command syntax is: ==== Input . Go to the EditRole procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Path to the knife executable, such as _/usr/bin/knife_ (the default value). (Required) |Role Data |Provide the data of the role. (Required) |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *EditRole* step, click the Log button to see the diagnostic information. [[InstallCookbookOnClient]] === InstallCookbookOnClient procedure The following procedure installs a specific cookbook on a Chef client. The command syntax is: cookbook site download ==== Input . Go to the InstallCookbookOnClient procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Path to the knife executable, such as _/usr/bin/knife_ (the default value). (Required) |Configuration File |Path to the configuration file, such as _/root/.chef/knife.rb_ (the default value). (Required) |Chef Server URL |URL of the Chef server. |Cookbook Name |Name of the cookbook to download. (Required) |Cookbook Version |Cookbook version to download. If this field is blank, the latest version is downloaded. |No Dependencies |Cookbook dependencies are not installed automatically when this checkbox is checked. |Verbose |Displays the more-verbose output format when checked. |Cookbooks Path |Path where the cookbook is installed. You should use the path where all the cookbooks are stored, such as _/etc/chef/cookbooks_ (the default value). |Branch To Work With |Default branch with which to work. If the field is blank, the default branch is _master_. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *InstallCookbookOnClient* step, click the Log button to see the diagnostic information. [[KnifeSearch]] === KnifeSearch The following procedure is used to search The command syntax is: client list ==== Input . Go to the KnifeSearch procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |Index |INDEX is one of client, environment, node, role, or the name of a data bag. |Search Query |SEARCH_QUERY is the search query syntax for the query that will be executed. |Attribute |The attribute (or attributes) to show. |Row |The row at which return results begin. |Filter |Use to return only attributes that match the specified FILTER. For example: \\""ServerName=name, Kernel=kernel.version\\. |Id-Only |Show only matching object IDs. |Long |Display all attributes in the output and show the output as JSON. |Medium |Display normal attributes in the output and to show the output as JSON. |RunList |Show only the runlist. |Sort |The order in which search results are to be sorted. |Row-Count |The number of rows to be returned. |Additional Search Query |Protect search queries that start with a hyphen (-). A -q query may be specified as an argument or an option, but not both. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *KnifeSearch* step, click the Log button to see the diagnostic information. [[ListClient]] === ListClient The following procedure is used to list the existing clients. The command syntax is: client list ==== Input . Go to the ListClient procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |With URI |Show the corresponding URIs. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ListClient* step, click the Log button to see the diagnostic information. [[ListClientKey]] === ListClientKey The following procedure is used to list the existing client keys. The command syntax is: client key list < Client Name > < Options > ==== Input . Go to the ListClientKey procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Client Name |Mention the name of the client. This process will generate an RSA key pair for the named API client. The public key will be stored on the Chef server and the private key will be displayed on STDOUT or written to a named file. (Required) |Only Expired |Show a list of public keys that have expired. |Only Non-Expired |Show a list of public keys that have not expired. |With Details |Show a list of public keys, including URIs and expiration status. |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ListClientKey* step, click the Log button to see the diagnostic information. [[ListDatabag]] === ListDatabag The following procedure is used to list the existing client databags. The command syntax is: data bag list < Options > ==== Input . Go to the ListDatabag procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |With URI |Show the corresponding URIs. |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ListDatabag* step, click the Log button to see the diagnostic information. [[ListCookbook]] === ListCookbook The following procedure is used to list the existing client cookbooks. The command syntax is: cookbook list < Options > ==== Input . Go to the ListCookbook procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |All Available |Show the corresponding URIs. |With URI |Show the corresponding URIs. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ListCookbook* step, click the Log button to see the diagnostic information. [[ListNode]] === ListNode The following procedure is used to list the existing client nodes. The command syntax is: node list < Options > ==== Input . Go to the ListNode procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |With URI |Show the corresponding URIs. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ListNode* step, click the Log button to see the diagnostic information. [[ListRole]] === ListRole The following procedure is used to list the existing roles. The command syntax is: role list < Options > ==== Input . Go to the ListRole procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |With URI |Show the corresponding URIs. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ListRole* step, click the Log button to see the diagnostic information. [[RunChefClient]] === RunChefClient procedure The following procedure runs a chef-client on a node. A chef-client is an agent that performs the steps specified in the configuration file. The command syntax is: ==== Input . Go to the RunChefClient procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Chef-client Path |Path to the chef-client (executable), such as _/usr/bin/chef-client_ (the default value). (Required) |Configuration File |Path to the configuration file, such as _/etc/chef/client.rb_ (the default value). (Required) |Chef Server URL |URL of the Chef server. |Node Name |Name of the node. |Replace Current Run-List |New run-list of items to place instead of those in the current run-list. |JSON Attributes Definition |The JSON file or URL from which to get the attributes. |Daemonize |Runs the executable as a daemon when checked. |Interval(seconds) |Frequency in seconds at which the chef-client runs. |Log Level |Log level that is stored in the log file: *Debug*, *Information*, *Warning*, *Error*, or *Fatal*. |Additional Commands |Additional commands to run the chef-client. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *RunChefClient* step, click the Log button to see the diagnostic information. [[ShowClient]] === ShowClient The following procedure is used to show more details of an existing client. The command syntax is: client show < Options > ==== Input . Go to the ShowClient procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Client Name |Mention the name of the client. (Required) |Attribute(s) |Name of the Attributes to be displayed |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ShowClient* step, click the Log button to see the diagnostic information. [[ShowClientKey]] === ShowClientKey The following procedure is used to show more details of an existing client public key. The command syntax is: client key show < Options > ==== Input . Go to the ShowClientKey procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Client Name |Mention the name of the client. (Required) |Key Name |Name of the key to be displayed |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ShowClientKey* step, click the Log button to see the diagnostic information. [[ShowCookbook]] === ShowCookbook The following procedure is used to show more details of an existing cookbook. The command syntax is: cookbook show < Options > ==== Input . Go to the ShowCookbook procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Cookbook Name |Name of the cookbook. (Required) |Platform Version |The version of the platform |Part |The part of the cookbook to show: attributes, definitions, files, libraries, providers, recipes, resources, or templates. More than one part can be specified |Cookbook Version |The version of a cookbook to be shown. If a cookbook has only one version, this option does not need to be specified. If a cookbook has more than one version and this option is not specified, a list of cookbook versions is returned |FQDN |The FQDN of the host |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |File Name |The name of a file that is associated with a cookbook |Platform |The platform for which a cookbook is designed |With URI |Show the corresponding URIs |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ShowCookbook* step, click the Log button to see the diagnostic information. [[ShowDatabag]] === ShowDatabag The following procedure is used to show more details of an existing databag. The command syntax is: data bag show --config < Options > ==== Input . Go to the ShowDatabag procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Configuration File |Provide the path and name of the configuration file e.g /root/.chef/knife.rb (This is the default value). (Required) |Server URL |Provide the URL of the Chef Server to use |Data Bag |The name of a specific data bag. |Data Bag Item |The name of a specific item within a data bag. |Secret Key |The encryption key that is used for values contained within a data bag item |Secret Key File Path |The path to the file that contains the encryption key |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |Verbose |If checked a more verbose output is showed |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ShowDatabag* step, click the Log button to see the diagnostic information. [[ShowNode]] === ShowNode The following procedure is used to show more details of an existing node. The command syntax is: node show < Options > ==== Input . Go to the ShowNode procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Node Name |Provide the name of the node to show. (Required) |Attribute |The attribute (or attributes) to show |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |Long |Display all attributes in the output and show the output as JSON |Medium |Display normal attributes in the output and to show the output as JSON |Runlist |Show only the runlist. |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ShowNode* step, click the Log button to see the diagnostic information. [[ShowRole]] === ShowRole The following procedure is used to show more details of an existing role. The command syntax is: role show < Options > ==== Input . Go to the ShowRole procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required). |Role Name |Provide the name of the role to show. (Required) |Attribute |The attribute (or attributes) to show |Result Property |The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure, myProject]. (Required) |Additional options |Additional options if any. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *ShowRole* step, click the Log button to see the diagnostic information. [[UploadCookbooksToServer]] === UploadCookbooksToServer procedure The following procedure uploads one or more cookbooks from your local cookbook repositories to the Chef server. Only cookbooks that are not stored on the server are uploaded. The command syntax is: cookbook upload ==== Input . Go to the UploadCookbooksToServer procedure. . Enter the following parameters: [cols="","",options=""header"",] |=== |Parameter |Description |Knife Path |Path to the knife executable, such as _/usr/bin/knife_ (default value). (Required) |Configuration File |Path to the configuration file, such as _/root/.chef/knife.rb_ (the default value). (Required) |Server URL |URL of the Chef server. |Cookbook Names |Names of one or more cookbooks to upload, separated by spaces. (Required) |Include All Cookbooks |Uploads all cookbooks when checked. |Cookbooks Paths |List of paths to one or more cookbooks, separated by colons, such as _/etc/chef/cookbooks/:/etc/chef/more_cookbooks_. |Include Dependencies |Loads cookbooks upon which a cookbook is dependent when checked. |Verbose |Displays more-verbose output when checked. |Additional Commands |Additional commands to upload cookbooks. |=== ==== Output After the job runs, you can view the results on the Job Details page in {CD}. In the *UploadCookbooksToServer* step, click the Log button to see the diagnostic information. [[example]] == Examples and use cases === Install the MySQL cookbook example The following dialog box shows how to install a cookbook on a Chef client: image::cloudbees-common::cd-plugins/ec-chef/example1.png[image] ==== Opscode repository page for the MySQL cookbook The following information appears in the Opscode respository page in the Chef UI: image::cloudbees-common::cd-plugins/ec-chef/example2.png[image] ==== Job summary The following information appears in the Job Details page in the {CD} UI: image::cloudbees-common::cd-plugins/ec-chef/example3.png[image] ==== Summary of the generated log information The following information appears when you click the Log button for a specific step in the {CD} UI: image::cloudbees-common::cd-plugins/ec-chef/example4.png[image] ==== MySQL cookbook and dependencies The following information appears in the Chef UI: image::cloudbees-common::cd-plugins/ec-chef/example5.png[image] ==== Successful installation of MySQL cookbook content The following information appears in the Chef UI after you run the InstallCookbookOnClient procedure: image::cloudbees-common::cd-plugins/ec-chef/example6.png[image] === Upload MySQL cookbook to server example The following dialog box shows how to upload a cookbook to a Chef server: image::cloudbees-common::cd-plugins/ec-chef/example7.png[image] ==== Cookbook list in the chef server web UI The following information appears in the Cookbook list in the Chef server UI: image::cloudbees-common::cd-plugins/ec-chef/example8.png[image] ==== Job Summary The following information appears in the Job Details page in the {CD} UI: image::cloudbees-common::cd-plugins/ec-chef/example9.png[image] ==== Summary of the Generated Log Information The following information appears when you click the Log button for a specific step in the {CD} UI: image::cloudbees-common::cd-plugins/ec-chef/example10.png[image] ==== MySQL cookbook and dependencies on server The following information appears in the Chef UI after you run the UploadCookbooksToServer procedure: image::cloudbees-common::cd-plugins/ec-chef/example11.png[image] ==== Add MySQL and create_file recipe to node example The following dialog box shows how to add recipes to a node: image::cloudbees-common::cd-plugins/ec-chef/example12.png[image] === Current run-list of the ubuntu-client node The following information appears in the run-list for a node in the Chef UI: image::cloudbees-common::cd-plugins/ec-chef/example13.png[image] ==== Job Summary The following information appears in the Job Details page in the {CD} UI: image::cloudbees-common::cd-plugins/ec-chef/example14.png[image] ==== Summary of the log generated The following information appears when you click the Log button for a specific step in the {CD} UI: image::cloudbees-common::cd-plugins/ec-chef/example15.png[image] === Updated run-list of the ubuntu-client node The following information appears in the run-list for a node in the Chef UI after the AddRecipesToNodeRunList procedure runs: image::cloudbees-common::cd-plugins/ec-chef/example16.png[image] ==== Run chef client example—file creation The following dialog box shows how to run a chef-client on a node. image::cloudbees-common::cd-plugins/ec-chef/example17.png[image] ==== Current Run-List of the ubuntu-client Node The following information appears in the run-list for a node in the Chef UI: image::cloudbees-common::cd-plugins/ec-chef/example18.png[image] ==== Job Summary The following information appears in the Job Details page in the {CD} UI: image::cloudbees-common::cd-plugins/ec-chef/example19.png[image] ==== Summary of the Generated Log Information The following information appears when you click the Log button for a specific step in the {CD} UI: image::cloudbees-common::cd-plugins/ec-chef/example20.png[image] ==== Created file on the ubuntu-client node The following information appears in the Chef UI after the RunChefClient procedure runs: image::cloudbees-common::cd-plugins/ec-chef/example21.png[image] [[rns]] == Release notes === EC-Chef 1.2.5 * Documentation has been migrated to the main documentation site. === EC-Chef 1.2.4 Renaming to ""CloudBees"" === EC-Chef 1.2.3 * Configurations can be created by users with ""@"" sign in a name. === EC-Chef 1.2.2 * The plugin icon has been updated. === EC-Chef 1.2.1 * Configured the plugin to allow the ElectricFlow UI to create configs inline of procedure form. * Configured the plugin to allow the ElectricFlow UI to render the plugin procedure parameters entirely using the configured form XMLs. * Enabled the plugin for managing the plugin configurations in-line when defining an application process step or a pipeline stage task. * Fixed non-ascii characters in plugin forms and help file. === EC-Chef 1.2.0 * Added following new procedures: ** CreateRole ** ListRole ** EditRole ** ShowRole ** DeleteRole ** CreateNode ** ListNode ** EditNode ** ShowNode ** DeleteSingleNode ** CreateClient ** ListClient ** ShowClient ** DeleteClient ** CreateClientKey ** ListClientKey ** ShowClientKey ** EditClientKey ** DeleteClientKey ** CreateDataBag ** ListDataBag ** ShowDataBag ** EditDataBag ** DeleteDataBag ** CreateCookbook ** ListCookbook ** ShowCookbook ** DeleteCookbook ** KnifeSearch ** CookbookLinting ** Bootstrap ** CookbookUnitTesting === EC-Chef 1.1.4 * Fixed issue with configurations being cached for IE. === EC-Chef 1.1.3 * Renamed ElectricCommander. === EC-Chef 1.1.2 * Added a check in the _RegisterAndConvergeNode procedure to test whether the ElectricFlow agent running the procedure can communicate with the ElectricFlow server. This is required to identify any network communication issues between the agent and the server, especially when the agent is running on a dynamically provisioned cloud instance. === EC-Chef 1.1.1 * Fixed the _DeleteNode procedure for Windows. === EC-Chef 1.1.0 * Added properties in the ec_configurationmanagement_plugin property sheet to enable the EC-Chef plugin for configuration management. === EC-Chef 1.0.1 * Fixed the Help page. === EC-Chef 1.0.0 * Introduced the EC-Chef plugin. ",12434,True,2997.0187770345847,median "/* * * Copyright (c) 2020-2022 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * mbedTLS based implementation of CHIP crypto primitives */ #include ""CHIPCryptoPAL.h"" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(MBEDTLS_X509_CRT_PARSE_C) #include #endif // defined(MBEDTLS_X509_CRT_PARSE_C) #include #include #include #include #include #include #include #include #include #include #include #include namespace chip { namespace Crypto { #define MAX_ERROR_STR_LEN 128 #define NUM_BYTES_IN_SHA256_HASH 32 // In mbedTLS 3.0.0 direct access to structure fields was replaced with using MBEDTLS_PRIVATE macro. #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) #define CHIP_CRYPTO_PAL_PRIVATE(x) MBEDTLS_PRIVATE(x) #else #define CHIP_CRYPTO_PAL_PRIVATE(x) x #endif #if (MBEDTLS_VERSION_NUMBER >= 0x03000000 && MBEDTLS_VERSION_NUMBER < 0x03010000) #define CHIP_CRYPTO_PAL_PRIVATE_X509(x) MBEDTLS_PRIVATE(x) #else #define CHIP_CRYPTO_PAL_PRIVATE_X509(x) x #endif typedef struct { bool mInitialized; bool mDRBGSeeded; mbedtls_ctr_drbg_context mDRBGCtxt; mbedtls_entropy_context mEntropy; } EntropyContext; static EntropyContext gsEntropyContext; static void _log_mbedTLS_error(int error_code) { if (error_code != 0) { #if defined(MBEDTLS_ERROR_C) char error_str[MAX_ERROR_STR_LEN]; mbedtls_strerror(error_code, error_str, sizeof(error_str)); ChipLogError(Crypto, ""mbedTLS error: %s"", error_str); #else // Error codes defined in 16-bit negative hex numbers. Ease lookup by printing likewise ChipLogError(Crypto, ""mbedTLS error: -0x%04X"", -static_cast(error_code)); #endif } } static bool _isValidTagLength(size_t tag_length) { if (tag_length == 8 || tag_length == 12 || tag_length == 16) { return true; } return false; } static bool _isValidKeyLength(size_t length) { // 16 bytes key for AES-CCM-128, 32 for AES-CCM-256 if (length == 16 || length == 32) { return true; } return false; } CHIP_ERROR AES_CCM_encrypt(const uint8_t * plaintext, size_t plaintext_length, const uint8_t * aad, size_t aad_length, const uint8_t * key, size_t key_length, const uint8_t * nonce, size_t nonce_length, uint8_t * ciphertext, uint8_t * tag, size_t tag_length) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 1; mbedtls_ccm_context context; mbedtls_ccm_init(&context); VerifyOrExit(plaintext != nullptr || plaintext_length == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(ciphertext != nullptr || plaintext_length == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(key != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(_isValidKeyLength(key_length), error = CHIP_ERROR_UNSUPPORTED_ENCRYPTION_TYPE); VerifyOrExit(nonce != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(nonce_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(tag != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(_isValidTagLength(tag_length), error = CHIP_ERROR_INVALID_ARGUMENT); if (aad_length > 0) { VerifyOrExit(aad != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); } // Size of key = key_length * number of bits in a byte (8) // Cast is safe because we called _isValidKeyLength above. result = mbedtls_ccm_setkey(&context, MBEDTLS_CIPHER_ID_AES, Uint8::to_const_uchar(key), static_cast(key_length * 8)); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // Encrypt result = mbedtls_ccm_encrypt_and_tag(&context, plaintext_length, Uint8::to_const_uchar(nonce), nonce_length, Uint8::to_const_uchar(aad), aad_length, Uint8::to_const_uchar(plaintext), Uint8::to_uchar(ciphertext), Uint8::to_uchar(tag), tag_length); _log_mbedTLS_error(result); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: mbedtls_ccm_free(&context); return error; } CHIP_ERROR AES_CCM_decrypt(const uint8_t * ciphertext, size_t ciphertext_len, const uint8_t * aad, size_t aad_len, const uint8_t * tag, size_t tag_length, const uint8_t * key, size_t key_length, const uint8_t * nonce, size_t nonce_length, uint8_t * plaintext) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 1; mbedtls_ccm_context context; mbedtls_ccm_init(&context); VerifyOrExit(plaintext != nullptr || ciphertext_len == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(ciphertext != nullptr || ciphertext_len == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(tag != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(_isValidTagLength(tag_length), error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(key != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(_isValidKeyLength(key_length), error = CHIP_ERROR_UNSUPPORTED_ENCRYPTION_TYPE); VerifyOrExit(nonce != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(nonce_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); if (aad_len > 0) { VerifyOrExit(aad != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); } // Size of key = key_length * number of bits in a byte (8) // Cast is safe because we called _isValidKeyLength above. result = mbedtls_ccm_setkey(&context, MBEDTLS_CIPHER_ID_AES, Uint8::to_const_uchar(key), static_cast(key_length * 8)); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // Decrypt result = mbedtls_ccm_auth_decrypt(&context, ciphertext_len, Uint8::to_const_uchar(nonce), nonce_length, Uint8::to_const_uchar(aad), aad_len, Uint8::to_const_uchar(ciphertext), Uint8::to_uchar(plaintext), Uint8::to_const_uchar(tag), tag_length); _log_mbedTLS_error(result); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: mbedtls_ccm_free(&context); return error; } CHIP_ERROR Hash_SHA256(const uint8_t * data, const size_t data_length, uint8_t * out_buffer) { // zero data length hash is supported. VerifyOrReturnError(data != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) const int result = mbedtls_sha256(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer), 0); #else const int result = mbedtls_sha256_ret(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer), 0); #endif VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA1(const uint8_t * data, const size_t data_length, uint8_t * out_buffer) { // zero data length hash is supported. VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) const int result = mbedtls_sha1(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer)); #else const int result = mbedtls_sha1_ret(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer)); #endif VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } static_assert(kMAX_Hash_SHA256_Context_Size >= sizeof(mbedtls_sha256_context), ""kMAX_Hash_SHA256_Context_Size is too small for the size of underlying mbedtls_sha256_context""); static inline mbedtls_sha256_context * to_inner_hash_sha256_context(HashSHA256OpaqueContext * context) { return SafePointerCast(context); } Hash_SHA256_stream::Hash_SHA256_stream(void) { mbedtls_sha256_context * context = to_inner_hash_sha256_context(&mContext); mbedtls_sha256_init(context); } Hash_SHA256_stream::~Hash_SHA256_stream(void) { mbedtls_sha256_context * context = to_inner_hash_sha256_context(&mContext); mbedtls_sha256_free(context); Clear(); } CHIP_ERROR Hash_SHA256_stream::Begin(void) { mbedtls_sha256_context * const context = to_inner_hash_sha256_context(&mContext); #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) const int result = mbedtls_sha256_starts(context, 0); #else const int result = mbedtls_sha256_starts_ret(context, 0); #endif VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA256_stream::AddData(const ByteSpan data) { mbedtls_sha256_context * const context = to_inner_hash_sha256_context(&mContext); #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) const int result = mbedtls_sha256_update(context, Uint8::to_const_uchar(data.data()), data.size()); #else const int result = mbedtls_sha256_update_ret(context, Uint8::to_const_uchar(data.data()), data.size()); #endif VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA256_stream::GetDigest(MutableByteSpan & out_buffer) { mbedtls_sha256_context * context = to_inner_hash_sha256_context(&mContext); // Back-up context as we are about to finalize the hash to extract digest. mbedtls_sha256_context previous_ctx; mbedtls_sha256_init(&previous_ctx); mbedtls_sha256_clone(&previous_ctx, context); // Pad + compute digest, then finalize context. It is restored next line to continue. CHIP_ERROR result = Finish(out_buffer); // Restore context prior to finalization. mbedtls_sha256_clone(context, &previous_ctx); mbedtls_sha256_free(&previous_ctx); return result; } CHIP_ERROR Hash_SHA256_stream::Finish(MutableByteSpan & out_buffer) { VerifyOrReturnError(out_buffer.size() >= kSHA256_Hash_Length, CHIP_ERROR_BUFFER_TOO_SMALL); mbedtls_sha256_context * const context = to_inner_hash_sha256_context(&mContext); #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) const int result = mbedtls_sha256_finish(context, Uint8::to_uchar(out_buffer.data())); #else const int result = mbedtls_sha256_finish_ret(context, Uint8::to_uchar(out_buffer.data())); #endif VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); out_buffer = out_buffer.SubSpan(0, kSHA256_Hash_Length); return CHIP_NO_ERROR; } void Hash_SHA256_stream::Clear(void) { mbedtls_platform_zeroize(this, sizeof(*this)); } CHIP_ERROR HKDF_sha::HKDF_SHA256(const uint8_t * secret, const size_t secret_length, const uint8_t * salt, const size_t salt_length, const uint8_t * info, const size_t info_length, uint8_t * out_buffer, size_t out_length) { VerifyOrReturnError(secret != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(secret_length > 0, CHIP_ERROR_INVALID_ARGUMENT); // Salt is optional if (salt_length > 0) { VerifyOrReturnError(salt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); } VerifyOrReturnError(info_length > 0, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(info != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); const mbedtls_md_info_t * const md = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); VerifyOrReturnError(md != nullptr, CHIP_ERROR_INTERNAL); const int result = mbedtls_hkdf(md, Uint8::to_const_uchar(salt), salt_length, Uint8::to_const_uchar(secret), secret_length, Uint8::to_const_uchar(info), info_length, Uint8::to_uchar(out_buffer), out_length); _log_mbedTLS_error(result); VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR HMAC_sha::HMAC_SHA256(const uint8_t * key, size_t key_length, const uint8_t * message, size_t message_length, uint8_t * out_buffer, size_t out_length) { VerifyOrReturnError(key != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(key_length > 0, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(message != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(message_length > 0, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_length >= kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); const mbedtls_md_info_t * const md = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); VerifyOrReturnError(md != nullptr, CHIP_ERROR_INTERNAL); const int result = mbedtls_md_hmac(md, Uint8::to_const_uchar(key), key_length, Uint8::to_const_uchar(message), message_length, out_buffer); _log_mbedTLS_error(result); VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR PBKDF2_sha256::pbkdf2_sha256(const uint8_t * password, size_t plen, const uint8_t * salt, size_t slen, unsigned int iteration_count, uint32_t key_length, uint8_t * output) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; const mbedtls_md_info_t * md_info; mbedtls_md_context_t md_ctxt; constexpr int use_hmac = 1; bool free_md_ctxt = false; VerifyOrExit(password != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(plen > 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(salt != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(slen >= kSpake2p_Min_PBKDF_Salt_Length, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(slen <= kSpake2p_Max_PBKDF_Salt_Length, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(key_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(output != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); VerifyOrExit(md_info != nullptr, error = CHIP_ERROR_INTERNAL); mbedtls_md_init(&md_ctxt); free_md_ctxt = true; result = mbedtls_md_setup(&md_ctxt, md_info, use_hmac); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_pkcs5_pbkdf2_hmac(&md_ctxt, Uint8::to_const_uchar(password), plen, Uint8::to_const_uchar(salt), slen, iteration_count, key_length, Uint8::to_uchar(output)); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); if (free_md_ctxt) { mbedtls_md_free(&md_ctxt); } return error; } static EntropyContext * get_entropy_context() { if (!gsEntropyContext.mInitialized) { mbedtls_entropy_init(&gsEntropyContext.mEntropy); mbedtls_ctr_drbg_init(&gsEntropyContext.mDRBGCtxt); gsEntropyContext.mInitialized = true; } return &gsEntropyContext; } static mbedtls_ctr_drbg_context * get_drbg_context() { EntropyContext * const context = get_entropy_context(); mbedtls_ctr_drbg_context * const drbgCtxt = &context->mDRBGCtxt; if (!context->mDRBGSeeded) { const int status = mbedtls_ctr_drbg_seed(drbgCtxt, mbedtls_entropy_func, &context->mEntropy, nullptr, 0); if (status != 0) { _log_mbedTLS_error(status); return nullptr; } context->mDRBGSeeded = true; } return drbgCtxt; } CHIP_ERROR add_entropy_source(entropy_source fn_source, void * p_source, size_t threshold) { VerifyOrReturnError(fn_source != nullptr, CHIP_ERROR_INVALID_ARGUMENT); EntropyContext * const entropy_ctxt = get_entropy_context(); VerifyOrReturnError(entropy_ctxt != nullptr, CHIP_ERROR_INTERNAL); const int result = mbedtls_entropy_add_source(&entropy_ctxt->mEntropy, fn_source, p_source, threshold, MBEDTLS_ENTROPY_SOURCE_STRONG); VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR DRBG_get_bytes(uint8_t * out_buffer, const size_t out_length) { VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT); mbedtls_ctr_drbg_context * const drbg_ctxt = get_drbg_context(); VerifyOrReturnError(drbg_ctxt != nullptr, CHIP_ERROR_INTERNAL); const int result = mbedtls_ctr_drbg_random(drbg_ctxt, Uint8::to_uchar(out_buffer), out_length); VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } static int CryptoRNG(void * ctxt, uint8_t * out_buffer, size_t out_length) { return (chip::Crypto::DRBG_get_bytes(out_buffer, out_length) == CHIP_NO_ERROR) ? 0 : 1; } mbedtls_ecp_group_id MapECPGroupId(SupportedECPKeyTypes keyType) { switch (keyType) { case SupportedECPKeyTypes::ECP256R1: return MBEDTLS_ECP_DP_SECP256R1; default: return MBEDTLS_ECP_DP_NONE; } } static inline mbedtls_ecp_keypair * to_keypair(P256KeypairContext * context) { return SafePointerCast(context); } static inline const mbedtls_ecp_keypair * to_const_keypair(const P256KeypairContext * context) { return SafePointerCast(context); } CHIP_ERROR P256Keypair::ECDSA_sign_msg(const uint8_t * msg, const size_t msg_length, P256ECDSASignature & out_signature) const { #if defined(MBEDTLS_ECDSA_C) VerifyOrReturnError(mInitialized, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError((msg != nullptr) && (msg_length > 0), CHIP_ERROR_INVALID_ARGUMENT); uint8_t digest[kSHA256_Hash_Length]; memset(&digest[0], 0, sizeof(digest)); ReturnErrorOnFailure(Hash_SHA256(msg, msg_length, &digest[0])); return ECDSA_sign_hash(&digest[0], sizeof(digest), out_signature); #else return CHIP_ERROR_NOT_IMPLEMENTED; #endif } CHIP_ERROR P256Keypair::ECDSA_sign_hash(const uint8_t * hash, const size_t hash_length, P256ECDSASignature & out_signature) const { #if defined(MBEDTLS_ECDSA_C) VerifyOrReturnError(mInitialized, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(hash != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(hash_length == kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; mbedtls_mpi r, s; mbedtls_mpi_init(&r); mbedtls_mpi_init(&s); const mbedtls_ecp_keypair * keypair = to_const_keypair(&mKeypair); mbedtls_ecdsa_context ecdsa_ctxt; mbedtls_ecdsa_init(&ecdsa_ctxt); result = mbedtls_ecdsa_from_keypair(&ecdsa_ctxt, keypair); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_ecdsa_sign(&ecdsa_ctxt.CHIP_CRYPTO_PAL_PRIVATE(grp), &r, &s, &ecdsa_ctxt.CHIP_CRYPTO_PAL_PRIVATE(d), Uint8::to_const_uchar(hash), hash_length, CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit((mbedtls_mpi_size(&r) <= kP256_FE_Length) && (mbedtls_mpi_size(&s) <= kP256_FE_Length), error = CHIP_ERROR_INTERNAL); // Concatenate r and s to output. Sizes were checked above. result = mbedtls_mpi_write_binary(&r, out_signature.Bytes() + 0u, kP256_FE_Length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_write_binary(&s, out_signature.Bytes() + kP256_FE_Length, kP256_FE_Length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit(out_signature.SetLength(kP256_ECDSA_Signature_Length_Raw) == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); exit: keypair = nullptr; mbedtls_ecdsa_free(&ecdsa_ctxt); mbedtls_mpi_free(&s); mbedtls_mpi_free(&r); _log_mbedTLS_error(result); return error; #else return CHIP_ERROR_NOT_IMPLEMENTED; #endif } CHIP_ERROR P256PublicKey::ECDSA_validate_msg_signature(const uint8_t * msg, const size_t msg_length, const P256ECDSASignature & signature) const { #if defined(MBEDTLS_ECDSA_C) VerifyOrReturnError((msg != nullptr) && (msg_length > 0), CHIP_ERROR_INVALID_ARGUMENT); uint8_t digest[kSHA256_Hash_Length]; memset(&digest[0], 0, sizeof(digest)); ReturnErrorOnFailure(Hash_SHA256(msg, msg_length, &digest[0])); return ECDSA_validate_hash_signature(&digest[0], sizeof(digest), signature); #else return CHIP_ERROR_NOT_IMPLEMENTED; #endif } CHIP_ERROR P256PublicKey::ECDSA_validate_hash_signature(const uint8_t * hash, const size_t hash_length, const P256ECDSASignature & signature) const { #if defined(MBEDTLS_ECDSA_C) VerifyOrReturnError(hash != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(hash_length == kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(signature.Length() == kP256_ECDSA_Signature_Length_Raw, CHIP_ERROR_INVALID_ARGUMENT); CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; mbedtls_mpi r, s; mbedtls_mpi_init(&r); mbedtls_mpi_init(&s); mbedtls_ecp_keypair keypair; mbedtls_ecp_keypair_init(&keypair); mbedtls_ecdsa_context ecdsa_ctxt; mbedtls_ecdsa_init(&ecdsa_ctxt); result = mbedtls_ecp_group_load(&keypair.CHIP_CRYPTO_PAL_PRIVATE(grp), MapECPGroupId(Type())); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); result = mbedtls_ecp_point_read_binary(&keypair.CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair.CHIP_CRYPTO_PAL_PRIVATE(Q), Uint8::to_const_uchar(*this), Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); result = mbedtls_ecdsa_from_keypair(&ecdsa_ctxt, &keypair); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // Read the big nums from the signature result = mbedtls_mpi_read_binary(&r, Uint8::to_const_uchar(signature.ConstBytes()) + 0u, kP256_FE_Length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_read_binary(&s, Uint8::to_const_uchar(signature.ConstBytes()) + kP256_FE_Length, kP256_FE_Length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_ecdsa_verify(&ecdsa_ctxt.CHIP_CRYPTO_PAL_PRIVATE(grp), Uint8::to_const_uchar(hash), hash_length, &ecdsa_ctxt.CHIP_CRYPTO_PAL_PRIVATE(Q), &r, &s); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_SIGNATURE); exit: mbedtls_ecdsa_free(&ecdsa_ctxt); mbedtls_ecp_keypair_free(&keypair); mbedtls_mpi_free(&s); mbedtls_mpi_free(&r); _log_mbedTLS_error(result); return error; #else return CHIP_ERROR_NOT_IMPLEMENTED; #endif } CHIP_ERROR P256Keypair::ECDH_derive_secret(const P256PublicKey & remote_public_key, P256ECDHDerivedSecret & out_secret) const { #if defined(MBEDTLS_ECDH_C) CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; size_t secret_length = (out_secret.Length() == 0) ? out_secret.Capacity() : out_secret.Length(); mbedtls_ecp_group ecp_grp; mbedtls_ecp_group_init(&ecp_grp); mbedtls_mpi mpi_secret; mbedtls_mpi_init(&mpi_secret); mbedtls_ecp_point ecp_pubkey; mbedtls_ecp_point_init(&ecp_pubkey); const mbedtls_ecp_keypair * keypair = to_const_keypair(&mKeypair); VerifyOrExit(mInitialized, error = CHIP_ERROR_INCORRECT_STATE); result = mbedtls_ecp_group_load(&ecp_grp, MapECPGroupId(remote_public_key.Type())); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_ecp_point_read_binary(&ecp_grp, &ecp_pubkey, Uint8::to_const_uchar(remote_public_key), remote_public_key.Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); result = mbedtls_ecdh_compute_shared(&ecp_grp, &mpi_secret, &ecp_pubkey, &keypair->CHIP_CRYPTO_PAL_PRIVATE(d), CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_write_binary(&mpi_secret, Uint8::to_uchar(out_secret), secret_length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); SuccessOrExit(out_secret.SetLength(secret_length)); exit: keypair = nullptr; mbedtls_ecp_group_free(&ecp_grp); mbedtls_mpi_free(&mpi_secret); mbedtls_ecp_point_free(&ecp_pubkey); _log_mbedTLS_error(result); return error; #else return CHIP_ERROR_NOT_IMPLEMENTED; #endif } void ClearSecretData(uint8_t * buf, size_t len) { mbedtls_platform_zeroize(buf, len); } CHIP_ERROR P256Keypair::Initialize() { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; size_t pubkey_size = 0; Clear(); mbedtls_ecp_group_id group = MapECPGroupId(mPublicKey.Type()); mbedtls_ecp_keypair * keypair = to_keypair(&mKeypair); mbedtls_ecp_keypair_init(keypair); result = mbedtls_ecp_gen_key(group, keypair, CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_ecp_point_write_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair->CHIP_CRYPTO_PAL_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED, &pubkey_size, Uint8::to_uchar(mPublicKey), mPublicKey.Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(pubkey_size == mPublicKey.Length(), error = CHIP_ERROR_INVALID_ARGUMENT); keypair = nullptr; mInitialized = true; exit: if (keypair != nullptr) { mbedtls_ecp_keypair_free(keypair); keypair = nullptr; } _log_mbedTLS_error(result); return error; } CHIP_ERROR P256Keypair::Serialize(P256SerializedKeypair & output) const { const mbedtls_ecp_keypair * keypair = to_const_keypair(&mKeypair); size_t len = output.Length() == 0 ? output.Capacity() : output.Length(); Encoding::BufferWriter bbuf(output, len); uint8_t privkey[kP256_PrivateKey_Length]; CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; bbuf.Put(mPublicKey, mPublicKey.Length()); VerifyOrExit(bbuf.Available() == sizeof(privkey), error = CHIP_ERROR_INTERNAL); VerifyOrExit(mbedtls_mpi_size(&keypair->CHIP_CRYPTO_PAL_PRIVATE(d)) <= bbuf.Available(), error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_write_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(d), Uint8::to_uchar(privkey), sizeof(privkey)); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); bbuf.Put(privkey, sizeof(privkey)); VerifyOrExit(bbuf.Fit(), error = CHIP_ERROR_BUFFER_TOO_SMALL); output.SetLength(bbuf.Needed()); exit: ClearSecretData(privkey, sizeof(privkey)); _log_mbedTLS_error(result); return error; } CHIP_ERROR P256Keypair::Deserialize(P256SerializedKeypair & input) { Encoding::BufferWriter bbuf(mPublicKey, mPublicKey.Length()); int result = 0; CHIP_ERROR error = CHIP_NO_ERROR; Clear(); mbedtls_ecp_keypair * keypair = to_keypair(&mKeypair); mbedtls_ecp_keypair_init(keypair); result = mbedtls_ecp_group_load(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), MapECPGroupId(mPublicKey.Type())); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit(input.Length() == mPublicKey.Length() + kP256_PrivateKey_Length, error = CHIP_ERROR_INVALID_ARGUMENT); bbuf.Put((const uint8_t *) input, mPublicKey.Length()); VerifyOrExit(bbuf.Fit(), error = CHIP_ERROR_NO_MEMORY); result = mbedtls_ecp_point_read_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair->CHIP_CRYPTO_PAL_PRIVATE(Q), Uint8::to_const_uchar(mPublicKey), mPublicKey.Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); { const uint8_t * privkey = Uint8::to_const_uchar(input) + mPublicKey.Length(); result = mbedtls_mpi_read_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(d), privkey, kP256_PrivateKey_Length); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); } mInitialized = true; exit: _log_mbedTLS_error(result); return error; } void P256Keypair::Clear() { if (mInitialized) { mbedtls_ecp_keypair * keypair = to_keypair(&mKeypair); mbedtls_ecp_keypair_free(keypair); mInitialized = false; } } P256Keypair::~P256Keypair() { Clear(); } CHIP_ERROR P256Keypair::NewCertificateSigningRequest(uint8_t * out_csr, size_t & csr_length) const { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; size_t out_length; mbedtls_x509write_csr csr; mbedtls_x509write_csr_init(&csr); mbedtls_pk_context pk; pk.CHIP_CRYPTO_PAL_PRIVATE(pk_info) = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY); pk.CHIP_CRYPTO_PAL_PRIVATE(pk_ctx) = to_keypair(&mKeypair); VerifyOrExit(pk.CHIP_CRYPTO_PAL_PRIVATE(pk_info) != nullptr, error = CHIP_ERROR_INTERNAL); VerifyOrExit(mInitialized, error = CHIP_ERROR_INCORRECT_STATE); mbedtls_x509write_csr_set_key(&csr, &pk); mbedtls_x509write_csr_set_md_alg(&csr, MBEDTLS_MD_SHA256); // TODO: mbedTLS CSR parser fails if the subject name is not set (or if empty). // CHIP Spec doesn't specify the subject name that can be used. // Figure out the correct value and update this code. result = mbedtls_x509write_csr_set_subject_name(&csr, ""O=CSR""); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_x509write_csr_der(&csr, out_csr, csr_length, CryptoRNG, nullptr); VerifyOrExit(result > 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit(CanCastTo(result), error = CHIP_ERROR_INTERNAL); out_length = static_cast(result); result = 0; VerifyOrExit(out_length <= csr_length, error = CHIP_ERROR_INTERNAL); if (csr_length != out_length) { // mbedTLS API writes the CSR at the end of the provided buffer. // Let's move it to the start of the buffer. size_t offset = csr_length - out_length; memmove(out_csr, &out_csr[offset], out_length); } csr_length = out_length; exit: mbedtls_x509write_csr_free(&csr); _log_mbedTLS_error(result); return error; } CHIP_ERROR VerifyCertificateSigningRequest(const uint8_t * csr_buf, size_t csr_length, P256PublicKey & pubkey) { #if defined(MBEDTLS_X509_CSR_PARSE_C) // TODO: For some embedded targets, mbedTLS library doesn't have mbedtls_x509_csr_parse_der, and mbedtls_x509_csr_parse_free. // Taking a step back, embedded targets likely will not process CSR requests. Adding this action item to reevaluate // this if there's a need for this processing for embedded targets. CHIP_ERROR error = CHIP_NO_ERROR; size_t pubkey_size = 0; mbedtls_ecp_keypair * keypair = nullptr; P256ECDSASignature signature; MutableByteSpan out_raw_sig_span(signature.Bytes(), signature.Capacity()); mbedtls_x509_csr csr; mbedtls_x509_csr_init(&csr); int result = mbedtls_x509_csr_parse_der(&csr, csr_buf, csr_length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // Verify the signature algorithm and public key type VerifyOrExit(csr.CHIP_CRYPTO_PAL_PRIVATE(sig_md) == MBEDTLS_MD_SHA256, error = CHIP_ERROR_UNSUPPORTED_SIGNATURE_TYPE); VerifyOrExit(csr.CHIP_CRYPTO_PAL_PRIVATE(sig_pk) == MBEDTLS_PK_ECDSA, error = CHIP_ERROR_WRONG_KEY_TYPE); keypair = mbedtls_pk_ec(csr.CHIP_CRYPTO_PAL_PRIVATE_X509(pk)); // Copy the public key from the CSR result = mbedtls_ecp_point_write_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair->CHIP_CRYPTO_PAL_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED, &pubkey_size, Uint8::to_uchar(pubkey), pubkey.Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit(pubkey_size == pubkey.Length(), error = CHIP_ERROR_INTERNAL); // Convert DER signature to raw signature error = EcdsaAsn1SignatureToRaw(kP256_FE_Length, ByteSpan{ csr.CHIP_CRYPTO_PAL_PRIVATE(sig).CHIP_CRYPTO_PAL_PRIVATE_X509(p), csr.CHIP_CRYPTO_PAL_PRIVATE(sig).CHIP_CRYPTO_PAL_PRIVATE_X509(len) }, out_raw_sig_span); VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(out_raw_sig_span.size() == (kP256_FE_Length * 2), error = CHIP_ERROR_INTERNAL); signature.SetLength(out_raw_sig_span.size()); // Verify the signature using the public key error = pubkey.ECDSA_validate_msg_signature(csr.CHIP_CRYPTO_PAL_PRIVATE_X509(cri).CHIP_CRYPTO_PAL_PRIVATE_X509(p), csr.CHIP_CRYPTO_PAL_PRIVATE_X509(cri).CHIP_CRYPTO_PAL_PRIVATE_X509(len), signature); SuccessOrExit(error); exit: mbedtls_x509_csr_free(&csr); _log_mbedTLS_error(result); return error; #else ChipLogError(Crypto, ""MBEDTLS_X509_CSR_PARSE_C is not enabled. CSR cannot be parsed""); return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; #endif } typedef struct Spake2p_Context { mbedtls_ecp_group curve; const mbedtls_md_info_t * md_info; mbedtls_ecp_point M; mbedtls_ecp_point N; mbedtls_ecp_point X; mbedtls_ecp_point Y; mbedtls_ecp_point L; mbedtls_ecp_point Z; mbedtls_ecp_point V; mbedtls_mpi w0; mbedtls_mpi w1; mbedtls_mpi xy; mbedtls_mpi tempbn; } Spake2p_Context; static inline Spake2p_Context * to_inner_spake2p_context(Spake2pOpaqueContext * context) { return SafePointerCast(context); } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::InitInternal(void) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); memset(context, 0, sizeof(Spake2p_Context)); mbedtls_ecp_group_init(&context->curve); result = mbedtls_ecp_group_load(&context->curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); context->md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); VerifyOrExit(context->md_info != nullptr, error = CHIP_ERROR_INTERNAL); mbedtls_ecp_point_init(&context->M); mbedtls_ecp_point_init(&context->N); mbedtls_ecp_point_init(&context->X); mbedtls_ecp_point_init(&context->Y); mbedtls_ecp_point_init(&context->L); mbedtls_ecp_point_init(&context->V); mbedtls_ecp_point_init(&context->Z); M = &context->M; N = &context->N; X = &context->X; Y = &context->Y; L = &context->L; V = &context->V; Z = &context->Z; mbedtls_mpi_init(&context->w0); mbedtls_mpi_init(&context->w1); mbedtls_mpi_init(&context->xy); mbedtls_mpi_init(&context->tempbn); w0 = &context->w0; w1 = &context->w1; xy = &context->xy; tempbn = &context->tempbn; G = &context->curve.G; order = &context->curve.N; return error; exit: _log_mbedTLS_error(result); Clear(); return error; } void Spake2p_P256_SHA256_HKDF_HMAC::Clear() { VerifyOrReturn(state != CHIP_SPAKE2P_STATE::PREINIT); Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); mbedtls_ecp_point_free(&context->M); mbedtls_ecp_point_free(&context->N); mbedtls_ecp_point_free(&context->X); mbedtls_ecp_point_free(&context->Y); mbedtls_ecp_point_free(&context->L); mbedtls_ecp_point_free(&context->Z); mbedtls_ecp_point_free(&context->V); mbedtls_mpi_free(&context->w0); mbedtls_mpi_free(&context->w1); mbedtls_mpi_free(&context->xy); mbedtls_mpi_free(&context->tempbn); mbedtls_ecp_group_free(&context->curve); state = CHIP_SPAKE2P_STATE::PREINIT; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::Mac(const uint8_t * key, size_t key_len, const uint8_t * in, size_t in_len, MutableByteSpan & out_span) { HMAC_sha hmac; VerifyOrReturnError(out_span.size() >= kSHA256_Hash_Length, CHIP_ERROR_BUFFER_TOO_SMALL); ReturnErrorOnFailure(hmac.HMAC_SHA256(key, key_len, in, in_len, out_span.data(), kSHA256_Hash_Length)); out_span = out_span.SubSpan(0, kSHA256_Hash_Length); return CHIP_NO_ERROR; } /** * This function implements constant time memcmp. It's good practice * to use constant time functions for cryptographic functions. */ static inline int constant_time_memcmp(const void * a, const void * b, size_t n) { const uint8_t * A = (const uint8_t *) a; const uint8_t * B = (const uint8_t *) b; uint8_t diff = 0; for (size_t i = 0; i < n; i++) { diff |= (A[i] ^ B[i]); } return diff; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::MacVerify(const uint8_t * key, size_t key_len, const uint8_t * mac, size_t mac_len, const uint8_t * in, size_t in_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; uint8_t computed_mac[kSHA256_Hash_Length]; MutableByteSpan computed_mac_span{ computed_mac }; VerifyOrExit(mac_len == kSHA256_Hash_Length, error = CHIP_ERROR_INVALID_ARGUMENT); SuccessOrExit(error = Mac(key, key_len, in, in_len, computed_mac_span)); VerifyOrExit(computed_mac_span.size() == mac_len, error = CHIP_ERROR_INTERNAL); VerifyOrExit(constant_time_memcmp(mac, computed_mac, kSHA256_Hash_Length) == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FELoad(const uint8_t * in, size_t in_len, void * fe) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; result = mbedtls_mpi_read_binary((mbedtls_mpi *) fe, Uint8::to_const_uchar(in), in_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi((mbedtls_mpi *) fe, (mbedtls_mpi *) fe, (const mbedtls_mpi *) order); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEWrite(const void * fe, uint8_t * out, size_t out_len) { if (mbedtls_mpi_write_binary((const mbedtls_mpi *) fe, Uint8::to_uchar(out), out_len) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEGenerate(void * fe) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); result = mbedtls_ecp_gen_privkey(&context->curve, (mbedtls_mpi *) fe, CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEMul(void * fer, const void * fe1, const void * fe2) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; result = mbedtls_mpi_mul_mpi((mbedtls_mpi *) fer, (const mbedtls_mpi *) fe1, (const mbedtls_mpi *) fe2); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi((mbedtls_mpi *) fer, (mbedtls_mpi *) fer, (const mbedtls_mpi *) order); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointLoad(const uint8_t * in, size_t in_len, void * R) { Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_point_read_binary(&context->curve, (mbedtls_ecp_point *) R, Uint8::to_const_uchar(in), in_len) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointWrite(const void * R, uint8_t * out, size_t out_len) { memset(out, 0, out_len); size_t mbedtls_out_len = out_len; Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_point_write_binary(&context->curve, (const mbedtls_ecp_point *) R, MBEDTLS_ECP_PF_UNCOMPRESSED, &mbedtls_out_len, Uint8::to_uchar(out), out_len) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointMul(void * R, const void * P1, const void * fe1) { Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_mul(&context->curve, (mbedtls_ecp_point *) R, (const mbedtls_mpi *) fe1, (const mbedtls_ecp_point *) P1, CryptoRNG, nullptr) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointAddMul(void * R, const void * P1, const void * fe1, const void * P2, const void * fe2) { Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_muladd(&context->curve, (mbedtls_ecp_point *) R, (const mbedtls_mpi *) fe1, (const mbedtls_ecp_point *) P1, (const mbedtls_mpi *) fe2, (const mbedtls_ecp_point *) P2) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointInvert(void * R) { mbedtls_ecp_point * Rp = (mbedtls_ecp_point *) R; Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_mpi_sub_mpi(&Rp->CHIP_CRYPTO_PAL_PRIVATE(Y), &context->curve.P, &Rp->CHIP_CRYPTO_PAL_PRIVATE(Y)) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) { return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; mbedtls_ecp_group curve; mbedtls_mpi w1_bn; mbedtls_ecp_point Ltemp; mbedtls_ecp_group_init(&curve); mbedtls_mpi_init(&w1_bn); mbedtls_ecp_point_init(&Ltemp); result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_ecp_mul(&curve, &Ltemp, &w1_bn, &curve.G, CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); memset(Lout, 0, *L_len); result = mbedtls_ecp_point_write_binary(&curve, &Ltemp, MBEDTLS_ECP_PF_UNCOMPRESSED, L_len, Uint8::to_uchar(Lout), *L_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); mbedtls_ecp_point_free(&Ltemp); mbedtls_mpi_free(&w1_bn); mbedtls_ecp_group_free(&curve); return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointIsValid(void * R) { Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_check_pubkey(&context->curve, (mbedtls_ecp_point *) R) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR ValidateCertificateChain(const uint8_t * rootCertificate, size_t rootCertificateLen, const uint8_t * caCertificate, size_t caCertificateLen, const uint8_t * leafCertificate, size_t leafCertificateLen, CertificateChainValidationResult & result) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt certChain; mbedtls_x509_crt rootCert; int mbedResult; uint32_t flags; result = CertificateChainValidationResult::kInternalFrameworkError; VerifyOrReturnError(rootCertificate != nullptr && rootCertificateLen != 0, (result = CertificateChainValidationResult::kRootArgumentInvalid, CHIP_ERROR_INVALID_ARGUMENT)); VerifyOrReturnError(caCertificate != nullptr && caCertificateLen != 0, (result = CertificateChainValidationResult::kICAArgumentInvalid, CHIP_ERROR_INVALID_ARGUMENT)); VerifyOrReturnError(leafCertificate != nullptr && leafCertificateLen != 0, (result = CertificateChainValidationResult::kLeafArgumentInvalid, CHIP_ERROR_INVALID_ARGUMENT)); mbedtls_x509_crt_init(&certChain); mbedtls_x509_crt_init(&rootCert); /* Start of chain */ mbedResult = mbedtls_x509_crt_parse(&certChain, Uint8::to_const_uchar(leafCertificate), leafCertificateLen); VerifyOrExit(mbedResult == 0, (result = CertificateChainValidationResult::kLeafFormatInvalid, error = CHIP_ERROR_INTERNAL)); /* Add the intermediate to the chain */ mbedResult = mbedtls_x509_crt_parse(&certChain, Uint8::to_const_uchar(caCertificate), caCertificateLen); VerifyOrExit(mbedResult == 0, (result = CertificateChainValidationResult::kICAFormatInvalid, error = CHIP_ERROR_INTERNAL)); /* Parse the root cert */ mbedResult = mbedtls_x509_crt_parse(&rootCert, Uint8::to_const_uchar(rootCertificate), rootCertificateLen); VerifyOrExit(mbedResult == 0, (result = CertificateChainValidationResult::kRootFormatInvalid, error = CHIP_ERROR_INTERNAL)); /* Verify the chain against the root */ mbedResult = mbedtls_x509_crt_verify(&certChain, &rootCert, NULL, NULL, &flags, NULL, NULL); switch (mbedResult) { case 0: VerifyOrExit(flags == 0, (result = CertificateChainValidationResult::kInternalFrameworkError, error = CHIP_ERROR_INTERNAL)); result = CertificateChainValidationResult::kSuccess; break; case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED: result = CertificateChainValidationResult::kChainInvalid; error = CHIP_ERROR_CERT_NOT_TRUSTED; break; default: SuccessOrExit((result = CertificateChainValidationResult::kInternalFrameworkError, error = CHIP_ERROR_INTERNAL)); } exit: _log_mbedTLS_error(mbedResult); mbedtls_x509_crt_free(&certChain); mbedtls_x509_crt_free(&rootCert); #else (void) rootCertificate; (void) rootCertificateLen; (void) caCertificate; (void) caCertificateLen; (void) leafCertificate; (void) leafCertificateLen; (void) result; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } inline bool IsTimeGreaterThanEqual(const mbedtls_x509_time * const timeA, const mbedtls_x509_time * const timeB) { // checks if two values are different and if yes, then returns first > second. #define RETURN_STRICTLY_GREATER_IF_DIFFERENT(component) \\ { \\ auto valueA = timeA->CHIP_CRYPTO_PAL_PRIVATE_X509(component); \\ auto valueB = timeB->CHIP_CRYPTO_PAL_PRIVATE_X509(component); \\ \\ if (valueA != valueB) \\ { \\ return valueA > valueB; \\ } \\ } RETURN_STRICTLY_GREATER_IF_DIFFERENT(year); RETURN_STRICTLY_GREATER_IF_DIFFERENT(mon); RETURN_STRICTLY_GREATER_IF_DIFFERENT(day); RETURN_STRICTLY_GREATER_IF_DIFFERENT(hour); RETURN_STRICTLY_GREATER_IF_DIFFERENT(min); RETURN_STRICTLY_GREATER_IF_DIFFERENT(sec); // all above are equal return true; } CHIP_ERROR IsCertificateValidAtIssuance(const ByteSpan & referenceCertificate, const ByteSpan & toBeEvaluatedCertificate) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt mbedReferenceCertificate; mbedtls_x509_crt mbedToBeEvaluatedCertificate; mbedtls_x509_time refNotBeforeTime; mbedtls_x509_time tbeNotBeforeTime; mbedtls_x509_time tbeNotAfterTime; int result; VerifyOrReturnError(!referenceCertificate.empty() && !toBeEvaluatedCertificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); mbedtls_x509_crt_init(&mbedReferenceCertificate); mbedtls_x509_crt_init(&mbedToBeEvaluatedCertificate); result = mbedtls_x509_crt_parse(&mbedReferenceCertificate, Uint8::to_const_uchar(referenceCertificate.data()), referenceCertificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_x509_crt_parse(&mbedToBeEvaluatedCertificate, Uint8::to_const_uchar(toBeEvaluatedCertificate.data()), toBeEvaluatedCertificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); refNotBeforeTime = mbedReferenceCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(valid_from); tbeNotBeforeTime = mbedToBeEvaluatedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(valid_from); tbeNotAfterTime = mbedToBeEvaluatedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(valid_to); // check if referenceCertificate is issued at or after tbeCertificate's notBefore timestamp VerifyOrExit(IsTimeGreaterThanEqual(&refNotBeforeTime, &tbeNotBeforeTime), error = CHIP_ERROR_CERT_EXPIRED); // check if referenceCertificate is issued at or before tbeCertificate's notAfter timestamp VerifyOrExit(IsTimeGreaterThanEqual(&tbeNotAfterTime, &refNotBeforeTime), error = CHIP_ERROR_CERT_EXPIRED); exit: _log_mbedTLS_error(result); mbedtls_x509_crt_free(&mbedReferenceCertificate); mbedtls_x509_crt_free(&mbedToBeEvaluatedCertificate); #else (void) referenceCertificate; (void) toBeEvaluatedCertificate; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } CHIP_ERROR IsCertificateValidAtCurrentTime(const ByteSpan & certificate) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt mbedCertificate; int result; VerifyOrReturnError(!certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); mbedtls_x509_crt_init(&mbedCertificate); result = mbedtls_x509_crt_parse(&mbedCertificate, Uint8::to_const_uchar(certificate.data()), certificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // check if certificate's notBefore timestamp is earlier than or equal to current time. result = mbedtls_x509_time_is_past(&mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(valid_from)); VerifyOrExit(result == 1, error = CHIP_ERROR_CERT_EXPIRED); // check if certificate's notAfter timestamp is later than current time. result = mbedtls_x509_time_is_future(&mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(valid_to)); VerifyOrExit(result == 1, error = CHIP_ERROR_CERT_EXPIRED); exit: _log_mbedTLS_error(result); mbedtls_x509_crt_free(&mbedCertificate); #else (void) certificate; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } CHIP_ERROR ExtractPubkeyFromX509Cert(const ByteSpan & certificate, Crypto::P256PublicKey & pubkey) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt mbed_cert; mbedtls_ecp_keypair * keypair = nullptr; size_t pubkey_size = 0; mbedtls_x509_crt_init(&mbed_cert); int result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit(mbedtls_pk_get_type(&(mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(pk))) == MBEDTLS_PK_ECKEY, error = CHIP_ERROR_INVALID_ARGUMENT); keypair = mbedtls_pk_ec(mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(pk)); VerifyOrExit(keypair->CHIP_CRYPTO_PAL_PRIVATE(grp).id == MapECPGroupId(pubkey.Type()), error = CHIP_ERROR_INVALID_ARGUMENT); // Copy the public key from the cert in raw point format result = mbedtls_ecp_point_write_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair->CHIP_CRYPTO_PAL_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED, &pubkey_size, Uint8::to_uchar(pubkey.Bytes()), pubkey.Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit(pubkey_size == pubkey.Length(), error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); mbedtls_x509_crt_free(&mbed_cert); #else (void) certificate; (void) pubkey; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } namespace { CHIP_ERROR ExtractKIDFromX509Cert(bool extractSKID, const ByteSpan & certificate, MutableByteSpan & kid) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt mbed_cert; unsigned char * p; const unsigned char * end; size_t len; constexpr uint8_t sOID_Extension_SubjectKeyIdentifier[] = { 0x55, 0x1D, 0x0E }; constexpr uint8_t sOID_Extension_AuthorityKeyIdentifier[] = { 0x55, 0x1D, 0x23 }; mbedtls_x509_crt_init(&mbed_cert); int result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // TODO: The mbedTLS team is working on supporting SKID and AKID extensions processing. // Once it is supported, this code should be updated. p = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(v3_ext).CHIP_CRYPTO_PAL_PRIVATE_X509(p); end = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(v3_ext).CHIP_CRYPTO_PAL_PRIVATE_X509(p) + mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(v3_ext).CHIP_CRYPTO_PAL_PRIVATE_X509(len); result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); while (p < end) { result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OID); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); bool extractCurrentExtSKID = extractSKID && (sizeof(sOID_Extension_SubjectKeyIdentifier) == len) && (memcmp(p, sOID_Extension_SubjectKeyIdentifier, len) == 0); bool extractCurrentExtAKID = !extractSKID && (sizeof(sOID_Extension_AuthorityKeyIdentifier) == len) && (memcmp(p, sOID_Extension_AuthorityKeyIdentifier, len) == 0); p += len; int is_critical = 0; result = mbedtls_asn1_get_bool(&p, end, &is_critical); VerifyOrExit(result == 0 || result == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG, error = CHIP_ERROR_WRONG_CERT_TYPE); result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); if (extractCurrentExtSKID || extractCurrentExtAKID) { if (extractCurrentExtSKID) { result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); } else { result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONTEXT_SPECIFIC); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); // Other optional fields, authorityCertIssuer and authorityCertSerialNumber, // will be skipped if present. } VerifyOrExit(len == kSubjectKeyIdentifierLength, error = CHIP_ERROR_WRONG_CERT_TYPE); VerifyOrExit(len <= kid.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(kid.data(), p, len); if (kid.size() > len) { kid.reduce_size(len); } break; } p += len; } exit: _log_mbedTLS_error(result); mbedtls_x509_crt_free(&mbed_cert); #else (void) certificate; (void) kid; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } } // namespace CHIP_ERROR ExtractSKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan & skid) { return ExtractKIDFromX509Cert(true, certificate, skid); } CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan & akid) { return ExtractKIDFromX509Cert(false, certificate, akid); } CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCertVidPid & vidpid) { #if defined(MBEDTLS_X509_CRT_PARSE_C) constexpr uint8_t sOID_AttributeType_CommonName[] = { 0x55, 0x04, 0x03 }; constexpr uint8_t sOID_AttributeType_MatterVendorId[] = { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xA2, 0x7C, 0x02, 0x01 }; constexpr uint8_t sOID_AttributeType_MatterProductId[] = { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xA2, 0x7C, 0x02, 0x02 }; CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt mbed_cert; mbedtls_asn1_named_data * dnIterator = nullptr; AttestationCertVidPid vidpidFromCN; mbedtls_x509_crt_init(&mbed_cert); int result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); for (dnIterator = &mbed_cert.CHIP_CRYPTO_PAL_PRIVATE_X509(subject); dnIterator != nullptr; dnIterator = dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(next)) { size_t oid_len = dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(oid).CHIP_CRYPTO_PAL_PRIVATE_X509(len); uint8_t * oid_p = dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(oid).CHIP_CRYPTO_PAL_PRIVATE_X509(p); size_t val_len = dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(val).CHIP_CRYPTO_PAL_PRIVATE_X509(len); uint8_t * val_p = dnIterator->CHIP_CRYPTO_PAL_PRIVATE_X509(val).CHIP_CRYPTO_PAL_PRIVATE_X509(p); if (oid_p != nullptr && val_p != nullptr) { DNAttrType attrType = DNAttrType::kUnspecified; if ((oid_len == sizeof(sOID_AttributeType_CommonName)) && (memcmp(sOID_AttributeType_CommonName, oid_p, oid_len) == 0)) { attrType = DNAttrType::kCommonName; } else if ((oid_len == sizeof(sOID_AttributeType_MatterVendorId)) && (memcmp(sOID_AttributeType_MatterVendorId, oid_p, oid_len) == 0)) { attrType = DNAttrType::kMatterVID; } else if ((oid_len == sizeof(sOID_AttributeType_MatterProductId)) && (memcmp(sOID_AttributeType_MatterProductId, oid_p, oid_len) == 0)) { attrType = DNAttrType::kMatterPID; } error = ExtractVIDPIDFromAttributeString(attrType, ByteSpan(val_p, val_len), vidpid, vidpidFromCN); SuccessOrExit(error); } } // If Matter Attributes were not found use values extracted from the CN Attribute, // which might be uninitialized as well. if (!vidpid.Initialized()) { vidpid = vidpidFromCN; } exit: _log_mbedTLS_error(result); mbedtls_x509_crt_free(&mbed_cert); #else (void) certificate; (void) vidpid; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } } // namespace Crypto } // namespace chip ",16139,True,2848.6774614257306,median "// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include #include ""base/bind.h"" #include ""base/run_loop.h"" #include ""base/test/task_environment.h"" #include ""build/build_config.h"" #include ""components/viz/common/frame_sinks/begin_frame_args.h"" #include ""components/viz/common/quads/compositor_frame.h"" #include ""components/viz/common/quads/compositor_render_pass.h"" #include ""components/viz/common/quads/debug_border_draw_quad.h"" #include ""components/viz/common/quads/solid_color_draw_quad.h"" #include ""components/viz/common/resources/resource_format.h"" #include ""components/viz/common/resources/resource_settings.h"" #include ""components/viz/common/resources/returned_resource.h"" #include ""components/viz/common/resources/transferable_resource.h"" #include ""components/viz/common/surfaces/region_capture_bounds.h"" #include ""components/viz/common/surfaces/subtree_capture_id.h"" #include ""components/viz/common/surfaces/surface_info.h"" #include ""components/viz/common/surfaces/surface_range.h"" #include ""components/viz/test/begin_frame_args_test.h"" #include ""components/viz/test/compositor_frame_helpers.h"" #include ""gpu/ipc/common/mailbox_holder_mojom_traits.h"" #include ""gpu/ipc/common/mailbox_mojom_traits.h"" #include ""gpu/ipc/common/sync_token_mojom_traits.h"" #include ""ipc/ipc_message_utils.h"" #include ""mojo/public/cpp/base/time_mojom_traits.h"" #include ""mojo/public/cpp/bindings/remote.h"" #include ""mojo/public/cpp/test_support/test_utils.h"" #include ""services/viz/public/cpp/compositing/begin_frame_args_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/compositor_frame_metadata_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/compositor_frame_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/compositor_render_pass_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/copy_output_request_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/copy_output_result_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/filter_operation_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/filter_operations_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/frame_sink_id_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/local_surface_id_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/resource_settings_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/returned_resource_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/selection_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/shared_quad_state_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/surface_id_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/surface_info_mojom_traits.h"" #include ""services/viz/public/cpp/compositing/transferable_resource_mojom_traits.h"" #include ""services/viz/public/mojom/compositing/begin_frame_args.mojom.h"" #include ""services/viz/public/mojom/compositing/compositor_frame.mojom.h"" #include ""services/viz/public/mojom/compositing/filter_operation.mojom.h"" #include ""services/viz/public/mojom/compositing/filter_operations.mojom.h"" #include ""services/viz/public/mojom/compositing/returned_resource.mojom.h"" #include ""services/viz/public/mojom/compositing/selection.mojom.h"" #include ""services/viz/public/mojom/compositing/surface_info.mojom.h"" #include ""services/viz/public/mojom/compositing/surface_range.mojom.h"" #include ""services/viz/public/mojom/compositing/transferable_resource.mojom.h"" #include ""skia/public/mojom/bitmap_skbitmap_mojom_traits.h"" #include ""skia/public/mojom/tile_mode_mojom_traits.h"" #include ""testing/gtest/include/gtest/gtest.h"" #include ""third_party/skia/include/core/SkString.h"" #include ""ui/gfx/geometry/mojom/geometry_mojom_traits.h"" #include ""ui/gfx/hdr_metadata.h"" #include ""ui/gfx/mojom/buffer_types_mojom_traits.h"" #include ""ui/gfx/mojom/color_space_mojom_traits.h"" #include ""ui/gfx/mojom/selection_bound_mojom_traits.h"" #include ""ui/gfx/mojom/transform_mojom_traits.h"" #include ""ui/latency/mojom/latency_info_mojom_traits.h"" namespace viz { namespace { using StructTraitsTest = testing::Test; } // namespace TEST_F(StructTraitsTest, BeginFrameArgs) { const base::TimeTicks frame_time = base::TimeTicks::Now(); const base::TimeTicks deadline = base::TimeTicks::Now(); const base::TimeDelta interval = base::Milliseconds(1337); const BeginFrameArgs::BeginFrameArgsType type = BeginFrameArgs::NORMAL; const bool on_critical_path = true; const uint64_t source_id = 5; const uint64_t sequence_number = 10; const uint64_t frames_throttled_since_last = 20; const bool animate_only = true; BeginFrameArgs input; input.frame_id = BeginFrameId(source_id, sequence_number); input.frames_throttled_since_last = frames_throttled_since_last; input.frame_time = frame_time; input.deadline = deadline; input.interval = interval; input.type = type; input.on_critical_path = on_critical_path; input.animate_only = animate_only; BeginFrameArgs output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(source_id, output.frame_id.source_id); EXPECT_EQ(sequence_number, output.frame_id.sequence_number); EXPECT_EQ(frames_throttled_since_last, output.frames_throttled_since_last); EXPECT_EQ(frame_time, output.frame_time); EXPECT_EQ(deadline, output.deadline); EXPECT_EQ(interval, output.interval); EXPECT_EQ(type, output.type); EXPECT_EQ(on_critical_path, output.on_critical_path); EXPECT_EQ(animate_only, output.animate_only); } TEST_F(StructTraitsTest, BeginFrameAck) { const uint64_t source_id = 5; const uint64_t sequence_number = 10; const bool has_damage = true; BeginFrameAck input; input.frame_id = BeginFrameId(source_id, sequence_number); input.has_damage = has_damage; BeginFrameAck output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(source_id, output.frame_id.source_id); EXPECT_EQ(sequence_number, output.frame_id.sequence_number); EXPECT_TRUE(output.has_damage); } namespace { void ExpectEqual(const cc::FilterOperation& input, const cc::FilterOperation& output) { EXPECT_EQ(input.type(), output.type()); switch (input.type()) { case cc::FilterOperation::GRAYSCALE: case cc::FilterOperation::SEPIA: case cc::FilterOperation::SATURATE: case cc::FilterOperation::HUE_ROTATE: case cc::FilterOperation::INVERT: case cc::FilterOperation::BRIGHTNESS: case cc::FilterOperation::SATURATING_BRIGHTNESS: case cc::FilterOperation::CONTRAST: case cc::FilterOperation::OPACITY: case cc::FilterOperation::BLUR: EXPECT_EQ(input.amount(), output.amount()); break; case cc::FilterOperation::DROP_SHADOW: EXPECT_EQ(input.amount(), output.amount()); EXPECT_EQ(input.drop_shadow_offset(), output.drop_shadow_offset()); EXPECT_EQ(input.drop_shadow_color(), output.drop_shadow_color()); break; case cc::FilterOperation::COLOR_MATRIX: EXPECT_EQ(0, memcmp(input.matrix(), output.matrix(), 20)); break; case cc::FilterOperation::ZOOM: EXPECT_EQ(input.amount(), output.amount()); EXPECT_EQ(input.zoom_inset(), output.zoom_inset()); break; case cc::FilterOperation::REFERENCE: { ASSERT_EQ(!!input.image_filter(), !!output.image_filter()); if (input.image_filter()) { EXPECT_EQ(*input.image_filter(), *output.image_filter()); } break; } case cc::FilterOperation::ALPHA_THRESHOLD: NOTREACHED(); break; case cc::FilterOperation::STRETCH: EXPECT_EQ(input.amount(), output.amount()); EXPECT_EQ(input.outer_threshold(), output.outer_threshold()); break; } } } // namespace TEST_F(StructTraitsTest, FilterOperationBlur) { cc::FilterOperation input = cc::FilterOperation::CreateBlurFilter(20); cc::FilterOperation output; mojo::test::SerializeAndDeserialize(input, output); ExpectEqual(input, output); } TEST_F(StructTraitsTest, FilterOperationDropShadow) { cc::FilterOperation input = cc::FilterOperation::CreateDropShadowFilter( gfx::Point(4, 4), 4.0f, SkColorSetARGB(255, 40, 0, 0)); cc::FilterOperation output; mojo::test::SerializeAndDeserialize(input, output); ExpectEqual(input, output); } TEST_F(StructTraitsTest, FilterOperationReferenceFilter) { cc::FilterOperation input = cc::FilterOperation::CreateReferenceFilter( sk_make_sp( SkIntToScalar(3), SkIntToScalar(8), SkIntToScalar(4), SkIntToScalar(9), SK_ColorBLACK, cc::DropShadowPaintFilter::ShadowMode::kDrawShadowAndForeground, nullptr)); cc::FilterOperation output; mojo::test::SerializeAndDeserialize(input, output); ExpectEqual(input, output); } TEST_F(StructTraitsTest, FilterOperations) { cc::FilterOperations input; input.Append(cc::FilterOperation::CreateBlurFilter(0.f)); input.Append(cc::FilterOperation::CreateSaturateFilter(4.f)); input.Append(cc::FilterOperation::CreateZoomFilter(2.0f, 1)); cc::FilterOperations output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(input.size(), output.size()); for (size_t i = 0; i < input.size(); ++i) { ExpectEqual(input.at(i), output.at(i)); } } TEST_F(StructTraitsTest, LocalSurfaceId) { LocalSurfaceId input( 42, base::UnguessableToken::Deserialize(0x12345678, 0x9abcdef0)); LocalSurfaceId output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(input, output); } TEST_F(StructTraitsTest, CopyOutputRequest_BitmapRequest) { base::test::TaskEnvironment task_environment; const auto result_format = CopyOutputRequest::ResultFormat::RGBA; const auto result_destination = CopyOutputRequest::ResultDestination::kSystemMemory; const gfx::Rect area(5, 7, 44, 55); const auto source = base::UnguessableToken::Deserialize(0xdeadbeef, 0xdeadf00d); // Requesting 2:3 scale in X dimension, 5:4 in Y dimension. const gfx::Vector2d scale_from(2, 5); const gfx::Vector2d scale_to(3, 4); const gfx::Rect result_rect(7, 8, 132, 44); base::RunLoop run_loop; std::unique_ptr input(new CopyOutputRequest( result_format, result_destination, base::BindOnce( [](base::OnceClosure quit_closure, const gfx::Rect& expected_rect, std::unique_ptr result) { EXPECT_EQ(expected_rect, result->rect()); // Note: CopyOutputResult plumbing for bitmap requests is tested in // StructTraitsTest.CopyOutputResult_Bitmap. std::move(quit_closure).Run(); }, run_loop.QuitClosure(), result_rect))); input->SetScaleRatio(scale_from, scale_to); EXPECT_EQ(scale_from, input->scale_from()); EXPECT_EQ(scale_to, input->scale_to()); input->set_area(area); input->set_result_selection(result_rect); input->set_source(source); EXPECT_TRUE(input->is_scaled()); std::unique_ptr output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(result_format, output->result_format()); EXPECT_EQ(result_destination, output->result_destination()); EXPECT_TRUE(output->is_scaled()); EXPECT_EQ(scale_from, output->scale_from()); EXPECT_EQ(scale_to, output->scale_to()); EXPECT_TRUE(output->has_source()); EXPECT_EQ(source, output->source()); EXPECT_TRUE(output->has_area()); EXPECT_EQ(area, output->area()); EXPECT_TRUE(output->has_result_selection()); EXPECT_EQ(result_rect, output->result_selection()); SkBitmap bitmap; bitmap.allocPixels(SkImageInfo::MakeN32Premul( result_rect.width(), result_rect.height(), SkColorSpace::MakeSRGB())); output->SendResult(std::make_unique( result_rect, std::move(bitmap))); // If the CopyOutputRequest callback is called, this ends. Otherwise, the test // will time out and fail. run_loop.Run(); } TEST_F(StructTraitsTest, CopyOutputRequest_MessagePipeBroken) { base::test::TaskEnvironment task_environment; base::RunLoop run_loop; auto request = std::make_unique( CopyOutputRequest::ResultFormat::RGBA, CopyOutputRequest::ResultDestination::kSystemMemory, base::BindOnce( [](base::OnceClosure quit_closure, std::unique_ptr result) { EXPECT_TRUE(result->IsEmpty()); std::move(quit_closure).Run(); }, run_loop.QuitClosure())); auto result_sender = mojo::StructTraits< mojom::CopyOutputRequestDataView, std::unique_ptr>::result_sender(request); result_sender.reset(); // The callback must be called with an empty CopyOutputResult. If it's never // called, this will never end and the test times out. run_loop.Run(); } TEST_F(StructTraitsTest, CopyOutputRequest_TextureRequest) { base::test::TaskEnvironment task_environment; const auto result_format = CopyOutputRequest::ResultFormat::RGBA; const auto result_destination = CopyOutputRequest::ResultDestination::kNativeTextures; const int8_t mailbox_name[GL_MAILBOX_SIZE_CHROMIUM] = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 9, 7, 5, 3, 1, 3}; gpu::Mailbox mailbox; mailbox.SetName(mailbox_name); gpu::SyncToken sync_token; const gfx::Rect result_rect(10, 10); base::RunLoop run_loop_for_result; std::unique_ptr input(new CopyOutputRequest( result_format, result_destination, base::BindOnce( [](base::OnceClosure quit_closure, const gfx::Rect& expected_rect, std::unique_ptr result) { EXPECT_EQ(expected_rect, result->rect()); // Note: CopyOutputResult plumbing for texture requests is tested in // StructTraitsTest.CopyOutputResult_Texture. std::move(quit_closure).Run(); }, run_loop_for_result.QuitClosure(), result_rect))); EXPECT_FALSE(input->is_scaled()); std::unique_ptr output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(output->result_format(), result_format); EXPECT_EQ(output->result_destination(), result_destination); EXPECT_FALSE(output->is_scaled()); EXPECT_FALSE(output->has_source()); EXPECT_FALSE(output->has_area()); base::RunLoop run_loop_for_release; CopyOutputResult::ReleaseCallbacks release_callbacks; release_callbacks.push_back(base::BindOnce( [](base::OnceClosure quit_closure, const gpu::SyncToken& expected_sync_token, const gpu::SyncToken& sync_token, bool is_lost) { EXPECT_EQ(expected_sync_token, sync_token); EXPECT_FALSE(is_lost); std::move(quit_closure).Run(); }, run_loop_for_release.QuitClosure(), sync_token)); output->SendResult(std::make_unique( result_format, result_rect, CopyOutputResult::TextureResult(mailbox, sync_token, gfx::ColorSpace::CreateSRGB()), std::move(release_callbacks))); // Wait for the result to be delivered to the other side: The // CopyOutputRequest callback will be called, at which point // |run_loop_for_result| ends. Otherwise, the test will time out and fail. run_loop_for_result.Run(); // Now, wait for the the texture release callback on this side to be run: // The CopyOutputResult callback will be called, at which point // |run_loop_for_release| ends. Otherwise, the test will time out and fail. run_loop_for_release.Run(); } TEST_F(StructTraitsTest, CopyOutputRequest_CallbackRunsOnce) { base::test::TaskEnvironment task_environment; int n_called = 0; auto request = std::make_unique( CopyOutputRequest::ResultFormat::RGBA, CopyOutputRequest::ResultDestination::kSystemMemory, base::BindOnce( [](int* n_called, std::unique_ptr result) { ++*n_called; }, base::Unretained(&n_called))); auto result_sender_pending_remote = mojo::StructTraits< mojom::CopyOutputRequestDataView, std::unique_ptr>::result_sender(request); mojo::Remote result_sender_remote( std::move(result_sender_pending_remote)); for (int i = 0; i < 10; i++) result_sender_remote->SendResult(std::make_unique( request->result_format(), request->result_destination(), gfx::Rect(), false)); EXPECT_EQ(0, n_called); result_sender_remote.FlushForTesting(); EXPECT_EQ(1, n_called); } TEST_F(StructTraitsTest, ResourceSettings) { constexpr bool kArbitraryBool = true; ResourceSettings input; input.use_gpu_memory_buffer_resources = kArbitraryBool; ResourceSettings output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(input.use_gpu_memory_buffer_resources, output.use_gpu_memory_buffer_resources); } TEST_F(StructTraitsTest, Selection) { gfx::SelectionBound start; start.SetEdge(gfx::PointF(1234.5f, 67891.f), gfx::PointF(5432.1f, 1987.6f)); start.set_visible(true); start.set_type(gfx::SelectionBound::CENTER); gfx::SelectionBound end; end.SetEdge(gfx::PointF(1337.5f, 52124.f), gfx::PointF(1234.3f, 8765.6f)); end.set_visible(false); end.set_type(gfx::SelectionBound::RIGHT); Selection input; input.start = start; input.end = end; Selection output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(start, output.start); EXPECT_EQ(end, output.end); } TEST_F(StructTraitsTest, SharedQuadState) { const gfx::Transform quad_to_target_transform(1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f, 12.f, 13.f, 14.f, 15.f, 16.f); const gfx::Rect layer_rect(1234, 5678); const gfx::Rect visible_layer_rect(12, 34, 56, 78); const gfx::MaskFilterInfo mask_filter_info( gfx::RRectF(gfx::RectF(1.f, 2.f, 30.f, 40.f), 5)); const gfx::Rect clip_rect(123, 456, 789, 101112); bool are_contents_opaque = true; const float opacity = 0.9f; const SkBlendMode blend_mode = SkBlendMode::kSrcOver; const int sorting_context_id = 1337; bool is_fast_rounded_corner = true; SharedQuadState input_sqs; input_sqs.SetAll(quad_to_target_transform, layer_rect, visible_layer_rect, mask_filter_info, clip_rect, are_contents_opaque, opacity, blend_mode, sorting_context_id); input_sqs.is_fast_rounded_corner = is_fast_rounded_corner; SharedQuadState output_sqs; mojo::test::SerializeAndDeserialize(input_sqs, output_sqs); EXPECT_EQ(quad_to_target_transform, output_sqs.quad_to_target_transform); EXPECT_EQ(layer_rect, output_sqs.quad_layer_rect); EXPECT_EQ(visible_layer_rect, output_sqs.visible_quad_layer_rect); EXPECT_EQ(mask_filter_info.rounded_corner_bounds(), output_sqs.mask_filter_info.rounded_corner_bounds()); EXPECT_EQ(clip_rect, output_sqs.clip_rect); EXPECT_EQ(opacity, output_sqs.opacity); EXPECT_EQ(blend_mode, output_sqs.blend_mode); EXPECT_EQ(sorting_context_id, output_sqs.sorting_context_id); EXPECT_EQ(is_fast_rounded_corner, output_sqs.is_fast_rounded_corner); } // Note that this is a fairly trivial test of CompositorFrame serialization as // most of the heavy lifting has already been done by CompositorFrameMetadata, // CompositorRenderPass, and QuadListBasic unit tests. TEST_F(StructTraitsTest, CompositorFrame) { auto render_pass = CompositorRenderPass::Create(); render_pass->SetNew(CompositorRenderPassId{1}, gfx::Rect(5, 6), gfx::Rect(2, 3), gfx::Transform()); // SharedQuadState. const gfx::Transform sqs_quad_to_target_transform( 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f, 11.f, 12.f, 13.f, 14.f, 15.f, 16.f); const gfx::Rect sqs_layer_rect(1234, 5678); const gfx::Rect sqs_visible_layer_rect(12, 34, 56, 78); const gfx::MaskFilterInfo sqs_mask_filter_info( gfx::RRectF(gfx::RectF(3.f, 4.f, 50.f, 15.f), 3)); const gfx::Rect sqs_clip_rect(123, 456, 789, 101112); bool sqs_are_contents_opaque = false; const float sqs_opacity = 0.9f; const SkBlendMode sqs_blend_mode = SkBlendMode::kSrcOver; const int sqs_sorting_context_id = 1337; SharedQuadState* sqs = render_pass->CreateAndAppendSharedQuadState(); sqs->SetAll(sqs_quad_to_target_transform, sqs_layer_rect, sqs_visible_layer_rect, sqs_mask_filter_info, sqs_clip_rect, sqs_are_contents_opaque, sqs_opacity, sqs_blend_mode, sqs_sorting_context_id); // DebugBorderDrawQuad. const gfx::Rect rect1(1234, 4321, 1357, 7531); const SkColor color1 = SK_ColorRED; const int32_t width1 = 1337; DebugBorderDrawQuad* debug_quad = render_pass->CreateAndAppendDrawQuad(); debug_quad->SetNew(sqs, rect1, rect1, color1, width1); // SolidColorDrawQuad. const gfx::Rect rect2(2468, 8642, 4321, 1234); const uint32_t color2 = 0xffffffff; const bool force_anti_aliasing_off = true; SolidColorDrawQuad* solid_quad = render_pass->CreateAndAppendDrawQuad(); solid_quad->SetNew(sqs, rect2, rect2, color2, force_anti_aliasing_off); // TransferableResource constants. const ResourceId tr_id(1337); const ResourceFormat tr_format = ALPHA_8; const uint32_t tr_filter = 1234; const gfx::Size tr_size(1234, 5678); TransferableResource resource; resource.id = tr_id; resource.format = tr_format; resource.filter = tr_filter; resource.size = tr_size; // CompositorFrameMetadata constants. const float device_scale_factor = 2.6f; const gfx::Vector2dF root_scroll_offset(1234.5f, 6789.1f); const float page_scale_factor = 1337.5f; const gfx::SizeF scrollable_viewport_size(1337.7f, 1234.5f); const BeginFrameAck begin_frame_ack(5, 10, false); CompositorFrame input; input.metadata.device_scale_factor = device_scale_factor; input.metadata.root_scroll_offset = root_scroll_offset; input.metadata.page_scale_factor = page_scale_factor; input.metadata.scrollable_viewport_size = scrollable_viewport_size; input.render_pass_list.push_back(std::move(render_pass)); input.resource_list.push_back(resource); input.metadata.begin_frame_ack = begin_frame_ack; input.metadata.frame_token = 1; CompositorFrame output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(device_scale_factor, output.metadata.device_scale_factor); EXPECT_EQ(root_scroll_offset, output.metadata.root_scroll_offset); EXPECT_EQ(page_scale_factor, output.metadata.page_scale_factor); EXPECT_EQ(scrollable_viewport_size, output.metadata.scrollable_viewport_size); EXPECT_EQ(begin_frame_ack, output.metadata.begin_frame_ack); ASSERT_EQ(1u, output.resource_list.size()); TransferableResource out_resource = output.resource_list[0]; EXPECT_EQ(tr_id, out_resource.id); EXPECT_EQ(tr_format, out_resource.format); EXPECT_EQ(tr_filter, out_resource.filter); EXPECT_EQ(tr_size, out_resource.size); EXPECT_EQ(1u, output.render_pass_list.size()); const CompositorRenderPass* out_render_pass = output.render_pass_list[0].get(); ASSERT_EQ(2u, out_render_pass->quad_list.size()); ASSERT_EQ(1u, out_render_pass->shared_quad_state_list.size()); const SharedQuadState* out_sqs = out_render_pass->shared_quad_state_list.ElementAt(0); EXPECT_EQ(sqs_quad_to_target_transform, out_sqs->quad_to_target_transform); EXPECT_EQ(sqs_layer_rect, out_sqs->quad_layer_rect); EXPECT_EQ(sqs_visible_layer_rect, out_sqs->visible_quad_layer_rect); EXPECT_EQ(sqs_mask_filter_info, out_sqs->mask_filter_info); EXPECT_EQ(sqs_clip_rect, out_sqs->clip_rect); EXPECT_EQ(sqs_are_contents_opaque, out_sqs->are_contents_opaque); EXPECT_EQ(sqs_opacity, out_sqs->opacity); EXPECT_EQ(sqs_blend_mode, out_sqs->blend_mode); EXPECT_EQ(sqs_sorting_context_id, out_sqs->sorting_context_id); const DebugBorderDrawQuad* out_debug_border_draw_quad = DebugBorderDrawQuad::MaterialCast( out_render_pass->quad_list.ElementAt(0)); EXPECT_EQ(rect1, out_debug_border_draw_quad->rect); EXPECT_EQ(rect1, out_debug_border_draw_quad->visible_rect); EXPECT_EQ(color1, out_debug_border_draw_quad->color); EXPECT_EQ(width1, out_debug_border_draw_quad->width); const SolidColorDrawQuad* out_solid_color_draw_quad = SolidColorDrawQuad::MaterialCast(out_render_pass->quad_list.ElementAt(1)); EXPECT_EQ(rect2, out_solid_color_draw_quad->rect); EXPECT_EQ(rect2, out_solid_color_draw_quad->visible_rect); EXPECT_EQ(color2, out_solid_color_draw_quad->color); EXPECT_EQ(force_anti_aliasing_off, out_solid_color_draw_quad->force_anti_aliasing_off); } TEST_F(StructTraitsTest, CompositorFrameTransitionDirective) { auto frame = CompositorFrameBuilder() .AddDefaultRenderPass() .AddDefaultRenderPass() .AddDefaultRenderPass() .Build(); CompositorFrameTransitionDirective::SharedElement element; element.render_pass_id = frame.render_pass_list.front()->id; frame.metadata.transition_directives.push_back( CompositorFrameTransitionDirective( 1u, CompositorFrameTransitionDirective::Type::kSave, CompositorFrameTransitionDirective::Effect::kNone, CompositorFrameTransitionDirective::TransitionConfig(), {element})); // This ensures de-serialization succeeds if all passes are present. CompositorFrame output; ASSERT_TRUE(mojo::test::SerializeAndDeserialize( frame, output)); element.render_pass_id = CompositorRenderPassId( frame.render_pass_list.back()->id.GetUnsafeValue() + 1); frame.metadata.transition_directives.push_back( CompositorFrameTransitionDirective( 1u, CompositorFrameTransitionDirective::Type::kSave, CompositorFrameTransitionDirective::Effect::kNone, CompositorFrameTransitionDirective::TransitionConfig(), {element})); // This ensures de-serialization fails if a pass is missing. ASSERT_FALSE(mojo::test::SerializeAndDeserialize( frame, output)); } TEST_F(StructTraitsTest, SurfaceInfo) { const SurfaceId surface_id( FrameSinkId(1234, 4321), LocalSurfaceId(5678, base::UnguessableToken::Deserialize(143254, 144132))); constexpr float device_scale_factor = 1.234f; constexpr gfx::Size size(987, 123); SurfaceInfo input(surface_id, device_scale_factor, size); SurfaceInfo output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(input.id(), output.id()); EXPECT_EQ(input.size_in_pixels(), output.size_in_pixels()); EXPECT_EQ(input.device_scale_factor(), output.device_scale_factor()); } TEST_F(StructTraitsTest, ReturnedResource) { const ResourceId id(1337u); const gpu::CommandBufferNamespace command_buffer_namespace = gpu::IN_PROCESS; const gpu::CommandBufferId command_buffer_id( gpu::CommandBufferId::FromUnsafeValue(0xdeadbeef)); const uint64_t release_count = 0xdeadbeefdead; gpu::SyncToken sync_token(command_buffer_namespace, command_buffer_id, release_count); sync_token.SetVerifyFlush(); const int count = 1234; const bool lost = true; ReturnedResource input; input.id = id; input.sync_token = sync_token; input.count = count; input.lost = lost; ReturnedResource output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(id, output.id); EXPECT_EQ(sync_token, output.sync_token); EXPECT_EQ(count, output.count); EXPECT_EQ(lost, output.lost); } TEST_F(StructTraitsTest, CompositorFrameMetadata) { const float device_scale_factor = 2.6f; const gfx::Vector2dF root_scroll_offset(1234.5f, 6789.1f); const float page_scale_factor = 1337.5f; const gfx::SizeF scrollable_viewport_size(1337.7f, 1234.5f); const bool may_contain_video = true; const bool is_resourceless_software_draw_with_scroll_or_animation = true; const uint32_t root_background_color = 1337; ui::LatencyInfo latency_info; latency_info.set_trace_id(5); latency_info.AddLatencyNumber(ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT); std::vector latency_infos = {latency_info}; std::vector referenced_surfaces; SurfaceId id(FrameSinkId(1234, 4321), LocalSurfaceId(5678, base::UnguessableToken::Create())); referenced_surfaces.emplace_back(id); std::vector activation_dependencies; SurfaceId id2(FrameSinkId(4321, 1234), LocalSurfaceId(8765, base::UnguessableToken::Create())); activation_dependencies.push_back(id2); uint32_t frame_token = 0xdeadbeef; uint64_t begin_frame_ack_sequence_number = 0xdeadbeef; FrameDeadline frame_deadline(base::TimeTicks(), 4u, base::TimeDelta(), true); const float min_page_scale_factor = 3.5f; const float top_controls_visible_height = 12.f; CompositorFrameMetadata input; input.device_scale_factor = device_scale_factor; input.root_scroll_offset = root_scroll_offset; input.page_scale_factor = page_scale_factor; input.scrollable_viewport_size = scrollable_viewport_size; input.may_contain_video = may_contain_video; input.is_resourceless_software_draw_with_scroll_or_animation = is_resourceless_software_draw_with_scroll_or_animation; input.root_background_color = root_background_color; input.latency_info = latency_infos; input.referenced_surfaces = referenced_surfaces; input.activation_dependencies = activation_dependencies; input.deadline = frame_deadline; input.frame_token = frame_token; input.begin_frame_ack.frame_id.sequence_number = begin_frame_ack_sequence_number; input.min_page_scale_factor = min_page_scale_factor; input.top_controls_visible_height.emplace(top_controls_visible_height); CompositorFrameMetadata output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(device_scale_factor, output.device_scale_factor); EXPECT_EQ(root_scroll_offset, output.root_scroll_offset); EXPECT_EQ(page_scale_factor, output.page_scale_factor); EXPECT_EQ(scrollable_viewport_size, output.scrollable_viewport_size); EXPECT_EQ(may_contain_video, output.may_contain_video); EXPECT_EQ(is_resourceless_software_draw_with_scroll_or_animation, output.is_resourceless_software_draw_with_scroll_or_animation); EXPECT_EQ(root_background_color, output.root_background_color); EXPECT_EQ(latency_infos.size(), output.latency_info.size()); EXPECT_TRUE(output.latency_info[0].FindLatency( ui::INPUT_EVENT_LATENCY_BEGIN_RWH_COMPONENT, nullptr)); EXPECT_EQ(referenced_surfaces.size(), output.referenced_surfaces.size()); for (uint32_t i = 0; i < referenced_surfaces.size(); ++i) EXPECT_EQ(referenced_surfaces[i], output.referenced_surfaces[i]); EXPECT_EQ(activation_dependencies.size(), output.activation_dependencies.size()); for (uint32_t i = 0; i < activation_dependencies.size(); ++i) EXPECT_EQ(activation_dependencies[i], output.activation_dependencies[i]); EXPECT_EQ(frame_deadline, output.deadline); EXPECT_EQ(frame_token, output.frame_token); EXPECT_EQ(begin_frame_ack_sequence_number, output.begin_frame_ack.frame_id.sequence_number); EXPECT_EQ(min_page_scale_factor, output.min_page_scale_factor); EXPECT_EQ(*output.top_controls_visible_height, top_controls_visible_height); } TEST_F(StructTraitsTest, RenderPass) { // The CopyOutputRequest struct traits require a TaskRunner. base::test::TaskEnvironment task_environment; const CompositorRenderPassId render_pass_id{3u}; const gfx::Rect output_rect(45, 22, 120, 13); const gfx::Transform transform_to_root = gfx::Transform(1.0, 0.5, 0.5, -0.5, -1.0, 0.0); const gfx::Rect damage_rect(56, 123, 19, 43); cc::FilterOperations filters; filters.Append(cc::FilterOperation::CreateBlurFilter(0.f)); filters.Append(cc::FilterOperation::CreateZoomFilter(2.0f, 1)); cc::FilterOperations backdrop_filters; backdrop_filters.Append(cc::FilterOperation::CreateSaturateFilter(4.f)); backdrop_filters.Append(cc::FilterOperation::CreateZoomFilter(2.0f, 1)); backdrop_filters.Append(cc::FilterOperation::CreateSaturateFilter(2.f)); absl::optional backdrop_filter_bounds( {10, 20, 130, 140, 1, 2, 3, 4, 5, 6, 7, 8}); SubtreeCaptureId subtree_capture_id{22u}; const bool has_transparent_background = true; const bool cache_render_pass = true; const bool has_damage_from_contributing_content = true; const bool generate_mipmap = true; const bool has_per_quad_damage = true; auto input = CompositorRenderPass::Create(); input->SetAll(render_pass_id, output_rect, damage_rect, transform_to_root, filters, backdrop_filters, backdrop_filter_bounds, subtree_capture_id, output_rect.size(), SharedElementResourceId(), has_transparent_background, cache_render_pass, has_damage_from_contributing_content, generate_mipmap, has_per_quad_damage); input->copy_requests.push_back(CopyOutputRequest::CreateStubForTesting()); const gfx::Rect copy_output_area(24, 42, 75, 57); input->copy_requests.back()->set_area(copy_output_area); SharedQuadState* shared_state_1 = input->CreateAndAppendSharedQuadState(); shared_state_1->SetAll( gfx::Transform(16.1f, 15.3f, 14.3f, 13.7f, 12.2f, 11.4f, 10.4f, 9.8f, 8.1f, 7.3f, 6.3f, 5.7f, 4.8f, 3.4f, 2.4f, 1.2f), gfx::Rect(1, 2), gfx::Rect(1337, 5679, 9101112, 131415), gfx::MaskFilterInfo(gfx::RRectF(gfx::RectF(5.f, 6.f, 70.f, 89.f), 10.f)), gfx::Rect(1357, 2468, 121314, 1337), true, 2, SkBlendMode::kSrcOver, 1); SharedQuadState* shared_state_2 = input->CreateAndAppendSharedQuadState(); shared_state_2->SetAll( gfx::Transform(1.1f, 2.3f, 3.3f, 4.7f, 5.2f, 6.4f, 7.4f, 8.8f, 9.1f, 10.3f, 11.3f, 12.7f, 13.8f, 14.4f, 15.4f, 16.2f), gfx::Rect(1337, 1234), gfx::Rect(1234, 5678, 9101112, 13141516), gfx::MaskFilterInfo(gfx::RRectF(gfx::RectF(23.f, 45.f, 60.f, 70.f), 8.f)), gfx::Rect(1357, 2468, 121314, 1337), true, 2, SkBlendMode::kSrcOver, 1); // This quad uses the first shared quad state. The next two quads use the // second shared quad state. DebugBorderDrawQuad* debug_quad = input->CreateAndAppendDrawQuad(); const gfx::Rect debug_quad_rect(12, 56, 89, 10); debug_quad->SetNew(shared_state_1, debug_quad_rect, debug_quad_rect, SK_ColorBLUE, 1337); SolidColorDrawQuad* color_quad = input->CreateAndAppendDrawQuad(); const gfx::Rect color_quad_rect(123, 456, 789, 101); color_quad->SetNew(shared_state_2, color_quad_rect, color_quad_rect, SK_ColorRED, true); SurfaceDrawQuad* surface_quad = input->CreateAndAppendDrawQuad(); const gfx::Rect surface_quad_rect(1337, 2448, 1234, 5678); surface_quad->SetNew( shared_state_2, surface_quad_rect, surface_quad_rect, SurfaceRange( absl::nullopt, SurfaceId(FrameSinkId(1337, 1234), LocalSurfaceId(1234, base::UnguessableToken::Create()))), SK_ColorYELLOW, false); // Test non-default values. surface_quad->is_reflection = !surface_quad->is_reflection; surface_quad->allow_merge = !surface_quad->allow_merge; std::unique_ptr output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(input->quad_list.size(), output->quad_list.size()); EXPECT_EQ(input->shared_quad_state_list.size(), output->shared_quad_state_list.size()); EXPECT_EQ(render_pass_id, output->id); EXPECT_EQ(output_rect, output->output_rect); EXPECT_EQ(damage_rect, output->damage_rect); EXPECT_EQ(transform_to_root, output->transform_to_root_target); EXPECT_EQ(has_transparent_background, output->has_transparent_background); EXPECT_EQ(filters, output->filters); EXPECT_EQ(backdrop_filters, output->backdrop_filters); EXPECT_EQ(backdrop_filter_bounds, output->backdrop_filter_bounds); EXPECT_EQ(subtree_capture_id, output->subtree_capture_id); EXPECT_EQ(cache_render_pass, output->cache_render_pass); EXPECT_EQ(has_damage_from_contributing_content, output->has_damage_from_contributing_content); EXPECT_EQ(has_per_quad_damage, output->has_per_quad_damage); EXPECT_EQ(generate_mipmap, output->generate_mipmap); ASSERT_EQ(1u, output->copy_requests.size()); EXPECT_EQ(copy_output_area, output->copy_requests.front()->area()); SharedQuadState* out_sqs1 = output->shared_quad_state_list.ElementAt(0); EXPECT_EQ(shared_state_1->quad_to_target_transform, out_sqs1->quad_to_target_transform); EXPECT_EQ(shared_state_1->quad_layer_rect, out_sqs1->quad_layer_rect); EXPECT_EQ(shared_state_1->visible_quad_layer_rect, out_sqs1->visible_quad_layer_rect); EXPECT_EQ(shared_state_1->mask_filter_info, out_sqs1->mask_filter_info); EXPECT_EQ(shared_state_1->clip_rect, out_sqs1->clip_rect); EXPECT_EQ(shared_state_1->opacity, out_sqs1->opacity); EXPECT_EQ(shared_state_1->blend_mode, out_sqs1->blend_mode); EXPECT_EQ(shared_state_1->sorting_context_id, out_sqs1->sorting_context_id); SharedQuadState* out_sqs2 = output->shared_quad_state_list.ElementAt(1); EXPECT_EQ(shared_state_2->quad_to_target_transform, out_sqs2->quad_to_target_transform); EXPECT_EQ(shared_state_2->quad_layer_rect, out_sqs2->quad_layer_rect); EXPECT_EQ(shared_state_2->visible_quad_layer_rect, out_sqs2->visible_quad_layer_rect); EXPECT_EQ(shared_state_2->mask_filter_info, out_sqs2->mask_filter_info); EXPECT_EQ(shared_state_2->clip_rect, out_sqs2->clip_rect); EXPECT_EQ(shared_state_2->opacity, out_sqs2->opacity); EXPECT_EQ(shared_state_2->blend_mode, out_sqs2->blend_mode); EXPECT_EQ(shared_state_2->sorting_context_id, out_sqs2->sorting_context_id); const DebugBorderDrawQuad* out_debug_quad = DebugBorderDrawQuad::MaterialCast(output->quad_list.ElementAt(0)); EXPECT_EQ(out_debug_quad->shared_quad_state, out_sqs1); EXPECT_EQ(debug_quad->rect, out_debug_quad->rect); EXPECT_EQ(debug_quad->visible_rect, out_debug_quad->visible_rect); EXPECT_EQ(debug_quad->color, out_debug_quad->color); EXPECT_EQ(debug_quad->width, out_debug_quad->width); const SolidColorDrawQuad* out_color_quad = SolidColorDrawQuad::MaterialCast(output->quad_list.ElementAt(1)); EXPECT_EQ(out_color_quad->shared_quad_state, out_sqs2); EXPECT_EQ(color_quad->rect, out_color_quad->rect); EXPECT_EQ(color_quad->visible_rect, out_color_quad->visible_rect); EXPECT_EQ(color_quad->color, out_color_quad->color); EXPECT_EQ(color_quad->force_anti_aliasing_off, out_color_quad->force_anti_aliasing_off); const SurfaceDrawQuad* out_surface_quad = SurfaceDrawQuad::MaterialCast(output->quad_list.ElementAt(2)); EXPECT_EQ(out_surface_quad->shared_quad_state, out_sqs2); EXPECT_EQ(surface_quad->rect, out_surface_quad->rect); EXPECT_EQ(surface_quad->visible_rect, out_surface_quad->visible_rect); EXPECT_EQ(surface_quad->surface_range, out_surface_quad->surface_range); EXPECT_EQ(surface_quad->default_background_color, out_surface_quad->default_background_color); EXPECT_EQ(surface_quad->stretch_content_to_fill_bounds, out_surface_quad->stretch_content_to_fill_bounds); EXPECT_EQ(surface_quad->allow_merge, out_surface_quad->allow_merge); EXPECT_EQ(surface_quad->is_reflection, out_surface_quad->is_reflection); } TEST_F(StructTraitsTest, RenderPassWithEmptySharedQuadStateList) { const CompositorRenderPassId render_pass_id{3u}; const gfx::Rect output_rect(45, 22, 120, 13); const gfx::Rect damage_rect(56, 123, 19, 43); const gfx::Transform transform_to_root = gfx::Transform(1.0, 0.5, 0.5, -0.5, -1.0, 0.0); const absl::optional backdrop_filter_bounds; SubtreeCaptureId subtree_capture_id; const bool has_transparent_background = true; const bool cache_render_pass = false; const bool has_damage_from_contributing_content = false; const bool generate_mipmap = false; const bool has_per_quad_damage = false; auto input = CompositorRenderPass::Create(); input->SetAll(render_pass_id, output_rect, damage_rect, transform_to_root, cc::FilterOperations(), cc::FilterOperations(), backdrop_filter_bounds, subtree_capture_id, output_rect.size(), SharedElementResourceId(), has_transparent_background, cache_render_pass, has_damage_from_contributing_content, generate_mipmap, has_per_quad_damage); // Unlike the previous test, don't add any quads to the list; we need to // verify that the serialization code can deal with that. std::unique_ptr output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(input->quad_list.size(), output->quad_list.size()); EXPECT_EQ(input->shared_quad_state_list.size(), output->shared_quad_state_list.size()); EXPECT_EQ(render_pass_id, output->id); EXPECT_EQ(output_rect, output->output_rect); EXPECT_EQ(damage_rect, output->damage_rect); EXPECT_EQ(transform_to_root, output->transform_to_root_target); EXPECT_EQ(backdrop_filter_bounds, output->backdrop_filter_bounds); EXPECT_EQ(subtree_capture_id, output->subtree_capture_id); EXPECT_EQ(output_rect.size(), output->subtree_size); EXPECT_FALSE(output->subtree_capture_id.is_valid()); EXPECT_EQ(has_transparent_background, output->has_transparent_background); } TEST_F(StructTraitsTest, QuadListBasic) { auto render_pass = CompositorRenderPass::Create(); render_pass->SetNew(CompositorRenderPassId{1}, gfx::Rect(), gfx::Rect(), gfx::Transform()); SharedQuadState* sqs = render_pass->CreateAndAppendSharedQuadState(); const gfx::Rect rect1(1234, 4321, 1357, 7531); const SkColor color1 = SK_ColorRED; const int32_t width1 = 1337; DebugBorderDrawQuad* debug_quad = render_pass->CreateAndAppendDrawQuad(); debug_quad->SetNew(sqs, rect1, rect1, color1, width1); const gfx::Rect rect2(2468, 8642, 4321, 1234); const uint32_t color2 = 0xffffffff; const bool force_anti_aliasing_off = true; SolidColorDrawQuad* solid_quad = render_pass->CreateAndAppendDrawQuad(); solid_quad->SetNew(sqs, rect2, rect2, color2, force_anti_aliasing_off); const gfx::Rect rect3(1029, 3847, 5610, 2938); const SurfaceId primary_surface_id( FrameSinkId(1234, 4321), LocalSurfaceId(5678, base::UnguessableToken::Create())); const SurfaceId fallback_surface_id( FrameSinkId(2468, 1357), LocalSurfaceId(1234, base::UnguessableToken::Create())); SurfaceDrawQuad* primary_surface_quad = render_pass->CreateAndAppendDrawQuad(); primary_surface_quad->SetNew( sqs, rect3, rect3, SurfaceRange(fallback_surface_id, primary_surface_id), SK_ColorBLUE, false); const gfx::Rect rect4(1234, 5678, 91012, 13141); const bool needs_blending = true; const ResourceId resource_id4(1337); const CompositorRenderPassId render_pass_id{1234u}; const gfx::RectF mask_uv_rect(0, 0, 1337.1f, 1234.2f); const gfx::Size mask_texture_size(1234, 5678); gfx::Vector2dF filters_scale(1234.1f, 4321.2f); gfx::PointF filters_origin(8765.4f, 4567.8f); gfx::RectF tex_coord_rect(1.f, 1.f, 1234.f, 5678.f); const float backdrop_filter_quality = 1.0f; const bool intersects_damage_under = false; CompositorRenderPassDrawQuad* render_pass_quad = render_pass->CreateAndAppendDrawQuad(); render_pass_quad->SetAll(sqs, rect4, rect4, needs_blending, render_pass_id, resource_id4, mask_uv_rect, mask_texture_size, filters_scale, filters_origin, tex_coord_rect, force_anti_aliasing_off, backdrop_filter_quality, intersects_damage_under); const gfx::Rect rect5(123, 567, 91011, 13141); const ResourceId resource_id5(1337); const float vertex_opacity[4] = {1.f, 2.f, 3.f, 4.f}; const bool premultiplied_alpha = true; const gfx::PointF uv_top_left(12.1f, 34.2f); const gfx::PointF uv_bottom_right(56.3f, 78.4f); const SkColor background_color = SK_ColorGREEN; const bool y_flipped = true; const bool nearest_neighbor = true; const bool secure_output_only = true; const gfx::ProtectedVideoType protected_video_type = gfx::ProtectedVideoType::kClear; const gfx::Size resource_size_in_pixels5(1234, 5678); TextureDrawQuad* texture_draw_quad = render_pass->CreateAndAppendDrawQuad(); texture_draw_quad->SetAll(sqs, rect5, rect5, needs_blending, resource_id5, resource_size_in_pixels5, premultiplied_alpha, uv_top_left, uv_bottom_right, background_color, vertex_opacity, y_flipped, nearest_neighbor, secure_output_only, protected_video_type); const gfx::Rect rect6(321, 765, 11109, 151413); const bool needs_blending6 = false; const ResourceId resource_id6(1234); const gfx::Size resource_size_in_pixels(1234, 5678); StreamVideoDrawQuad* stream_video_draw_quad = render_pass->CreateAndAppendDrawQuad(); stream_video_draw_quad->SetNew(sqs, rect6, rect6, needs_blending6, resource_id6, resource_size_in_pixels, uv_top_left, uv_bottom_right); std::unique_ptr output; mojo::test::SerializeAndDeserialize(render_pass, output); ASSERT_EQ(render_pass->quad_list.size(), output->quad_list.size()); const DebugBorderDrawQuad* out_debug_border_draw_quad = DebugBorderDrawQuad::MaterialCast(output->quad_list.ElementAt(0)); EXPECT_EQ(rect1, out_debug_border_draw_quad->rect); EXPECT_EQ(rect1, out_debug_border_draw_quad->visible_rect); EXPECT_FALSE(out_debug_border_draw_quad->needs_blending); EXPECT_EQ(color1, out_debug_border_draw_quad->color); EXPECT_EQ(width1, out_debug_border_draw_quad->width); const SolidColorDrawQuad* out_solid_color_draw_quad = SolidColorDrawQuad::MaterialCast(output->quad_list.ElementAt(1)); EXPECT_EQ(rect2, out_solid_color_draw_quad->rect); EXPECT_EQ(rect2, out_solid_color_draw_quad->visible_rect); EXPECT_FALSE(out_solid_color_draw_quad->needs_blending); EXPECT_EQ(color2, out_solid_color_draw_quad->color); EXPECT_EQ(force_anti_aliasing_off, out_solid_color_draw_quad->force_anti_aliasing_off); const SurfaceDrawQuad* out_primary_surface_draw_quad = SurfaceDrawQuad::MaterialCast(output->quad_list.ElementAt(2)); EXPECT_EQ(rect3, out_primary_surface_draw_quad->rect); EXPECT_EQ(rect3, out_primary_surface_draw_quad->visible_rect); EXPECT_TRUE(out_primary_surface_draw_quad->needs_blending); EXPECT_EQ(primary_surface_id, out_primary_surface_draw_quad->surface_range.end()); EXPECT_EQ(SK_ColorBLUE, out_primary_surface_draw_quad->default_background_color); EXPECT_EQ(fallback_surface_id, out_primary_surface_draw_quad->surface_range.start()); const CompositorRenderPassDrawQuad* out_render_pass_draw_quad = CompositorRenderPassDrawQuad::MaterialCast( output->quad_list.ElementAt(3)); EXPECT_EQ(rect4, out_render_pass_draw_quad->rect); EXPECT_EQ(rect4, out_render_pass_draw_quad->visible_rect); EXPECT_EQ(render_pass_id, out_render_pass_draw_quad->render_pass_id); EXPECT_EQ(resource_id4, out_render_pass_draw_quad->mask_resource_id()); EXPECT_EQ(mask_uv_rect, out_render_pass_draw_quad->mask_uv_rect); EXPECT_EQ(mask_texture_size, out_render_pass_draw_quad->mask_texture_size); EXPECT_EQ(filters_scale, out_render_pass_draw_quad->filters_scale); EXPECT_EQ(filters_origin, out_render_pass_draw_quad->filters_origin); EXPECT_EQ(tex_coord_rect, out_render_pass_draw_quad->tex_coord_rect); EXPECT_EQ(force_anti_aliasing_off, out_render_pass_draw_quad->force_anti_aliasing_off); EXPECT_EQ(backdrop_filter_quality, out_render_pass_draw_quad->backdrop_filter_quality); EXPECT_EQ(intersects_damage_under, out_render_pass_draw_quad->intersects_damage_under); const TextureDrawQuad* out_texture_draw_quad = TextureDrawQuad::MaterialCast(output->quad_list.ElementAt(4)); EXPECT_EQ(rect5, out_texture_draw_quad->rect); EXPECT_EQ(rect5, out_texture_draw_quad->visible_rect); EXPECT_EQ(needs_blending, out_texture_draw_quad->needs_blending); EXPECT_EQ(resource_id5, out_texture_draw_quad->resource_id()); EXPECT_EQ(resource_size_in_pixels5, out_texture_draw_quad->resource_size_in_pixels()); EXPECT_EQ(premultiplied_alpha, out_texture_draw_quad->premultiplied_alpha); EXPECT_EQ(uv_top_left, out_texture_draw_quad->uv_top_left); EXPECT_EQ(uv_bottom_right, out_texture_draw_quad->uv_bottom_right); EXPECT_EQ(background_color, out_texture_draw_quad->background_color); EXPECT_EQ(vertex_opacity[0], out_texture_draw_quad->vertex_opacity[0]); EXPECT_EQ(vertex_opacity[1], out_texture_draw_quad->vertex_opacity[1]); EXPECT_EQ(vertex_opacity[2], out_texture_draw_quad->vertex_opacity[2]); EXPECT_EQ(vertex_opacity[3], out_texture_draw_quad->vertex_opacity[3]); EXPECT_EQ(y_flipped, out_texture_draw_quad->y_flipped); EXPECT_EQ(nearest_neighbor, out_texture_draw_quad->nearest_neighbor); EXPECT_EQ(secure_output_only, out_texture_draw_quad->secure_output_only); const StreamVideoDrawQuad* out_stream_video_draw_quad = StreamVideoDrawQuad::MaterialCast(output->quad_list.ElementAt(5)); EXPECT_EQ(rect6, out_stream_video_draw_quad->rect); EXPECT_EQ(rect6, out_stream_video_draw_quad->visible_rect); EXPECT_EQ(needs_blending6, out_stream_video_draw_quad->needs_blending); EXPECT_EQ(resource_id6, out_stream_video_draw_quad->resource_id()); EXPECT_EQ(resource_size_in_pixels, out_stream_video_draw_quad->resource_size_in_pixels()); EXPECT_EQ(uv_top_left, out_stream_video_draw_quad->uv_top_left); EXPECT_EQ(uv_bottom_right, out_stream_video_draw_quad->uv_bottom_right); } TEST_F(StructTraitsTest, SurfaceId) { static constexpr FrameSinkId frame_sink_id(1337, 1234); static LocalSurfaceId local_surface_id(0xfbadbeef, base::UnguessableToken::Create()); SurfaceId input(frame_sink_id, local_surface_id); SurfaceId output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(frame_sink_id, output.frame_sink_id()); EXPECT_EQ(local_surface_id, output.local_surface_id()); } TEST_F(StructTraitsTest, TransferableResource) { const ResourceId id(1337); const ResourceFormat format = ALPHA_8; const uint32_t filter = 1234; const gfx::Size size(1234, 5678); const int8_t mailbox_name[GL_MAILBOX_SIZE_CHROMIUM] = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 9, 7, 5, 3, 1, 2}; const gpu::CommandBufferNamespace command_buffer_namespace = gpu::IN_PROCESS; const gpu::CommandBufferId command_buffer_id( gpu::CommandBufferId::FromUnsafeValue(0xdeadbeef)); const uint64_t release_count = 0xdeadbeefdeadL; const uint32_t texture_target = 1337; const bool read_lock_fences_enabled = true; const bool is_software = false; const bool is_overlay_candidate = true; gpu::MailboxHolder mailbox_holder; mailbox_holder.mailbox.SetName(mailbox_name); mailbox_holder.sync_token = gpu::SyncToken(command_buffer_namespace, command_buffer_id, release_count); mailbox_holder.sync_token.SetVerifyFlush(); mailbox_holder.texture_target = texture_target; TransferableResource input; input.id = id; input.format = format; input.filter = filter; input.size = size; input.mailbox_holder = mailbox_holder; input.read_lock_fences_enabled = read_lock_fences_enabled; input.is_software = is_software; input.is_overlay_candidate = is_overlay_candidate; TransferableResource output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_EQ(id, output.id); EXPECT_EQ(format, output.format); EXPECT_EQ(filter, output.filter); EXPECT_EQ(size, output.size); EXPECT_EQ(mailbox_holder.mailbox, output.mailbox_holder.mailbox); EXPECT_EQ(mailbox_holder.sync_token, output.mailbox_holder.sync_token); EXPECT_EQ(mailbox_holder.texture_target, output.mailbox_holder.texture_target); EXPECT_EQ(read_lock_fences_enabled, output.read_lock_fences_enabled); EXPECT_EQ(is_software, output.is_software); EXPECT_EQ(is_overlay_candidate, output.is_overlay_candidate); } TEST_F(StructTraitsTest, YUVDrawQuad) { auto render_pass = CompositorRenderPass::Create(); render_pass->SetNew(CompositorRenderPassId{1}, gfx::Rect(), gfx::Rect(), gfx::Transform()); const DrawQuad::Material material = DrawQuad::Material::kYuvVideoContent; const gfx::Rect rect(1234, 4321, 1357, 7531); const gfx::Rect visible_rect(1337, 7331, 561, 293); const bool needs_blending = true; const gfx::RectF ya_tex_coord_rect(1234.1f, 5678.2f, 9101112.3f, 13141516.4f); const gfx::RectF uv_tex_coord_rect(1234.1f, 4321.2f, 1357.3f, 7531.4f); const gfx::Size ya_tex_size(1234, 5678); const gfx::Size uv_tex_size(4321, 8765); const ResourceId y_plane_resource_id(1337); const ResourceId u_plane_resource_id(1234); const ResourceId v_plane_resource_id(2468); const ResourceId a_plane_resource_id(7890); const gfx::ColorSpace video_color_space = gfx::ColorSpace::CreateJpeg(); const float resource_offset = 1337.5f; const float resource_multiplier = 1234.6f; const uint32_t bits_per_channel = 13; const gfx::ProtectedVideoType protected_video_type = gfx::ProtectedVideoType::kSoftwareProtected; gfx::HDRMetadata hdr_metadata = gfx::HDRMetadata(); hdr_metadata.max_content_light_level = 1000; hdr_metadata.max_frame_average_light_level = 100; SharedQuadState* sqs = render_pass->CreateAndAppendSharedQuadState(); YUVVideoDrawQuad* quad = render_pass->CreateAndAppendDrawQuad(); quad->SetAll(sqs, rect, visible_rect, needs_blending, ya_tex_coord_rect, uv_tex_coord_rect, ya_tex_size, uv_tex_size, y_plane_resource_id, u_plane_resource_id, v_plane_resource_id, a_plane_resource_id, video_color_space, resource_offset, resource_multiplier, bits_per_channel, protected_video_type, hdr_metadata); std::unique_ptr output; mojo::test::SerializeAndDeserialize(render_pass, output); ASSERT_EQ(render_pass->quad_list.size(), output->quad_list.size()); ASSERT_EQ(material, output->quad_list.ElementAt(0)->material); const YUVVideoDrawQuad* out_quad = YUVVideoDrawQuad::MaterialCast(output->quad_list.ElementAt(0)); EXPECT_EQ(rect, out_quad->rect); EXPECT_EQ(visible_rect, out_quad->visible_rect); EXPECT_EQ(needs_blending, out_quad->needs_blending); EXPECT_EQ(ya_tex_coord_rect, out_quad->ya_tex_coord_rect); EXPECT_EQ(uv_tex_coord_rect, out_quad->uv_tex_coord_rect); EXPECT_EQ(ya_tex_size, out_quad->ya_tex_size); EXPECT_EQ(uv_tex_size, out_quad->uv_tex_size); EXPECT_EQ(y_plane_resource_id, out_quad->y_plane_resource_id()); EXPECT_EQ(u_plane_resource_id, out_quad->u_plane_resource_id()); EXPECT_EQ(v_plane_resource_id, out_quad->v_plane_resource_id()); EXPECT_EQ(a_plane_resource_id, out_quad->a_plane_resource_id()); EXPECT_EQ(resource_offset, out_quad->resource_offset); EXPECT_EQ(resource_multiplier, out_quad->resource_multiplier); EXPECT_EQ(bits_per_channel, out_quad->bits_per_channel); EXPECT_EQ(protected_video_type, out_quad->protected_video_type); EXPECT_EQ(hdr_metadata, out_quad->hdr_metadata); } TEST_F(StructTraitsTest, CopyOutputResult_EmptyBitmap) { auto input = std::make_unique( CopyOutputRequest::ResultFormat::RGBA, CopyOutputRequest::ResultDestination::kSystemMemory, gfx::Rect(), false); std::unique_ptr output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_TRUE(output->IsEmpty()); EXPECT_EQ(output->format(), CopyOutputResult::Format::RGBA); EXPECT_EQ(output->destination(), CopyOutputResult::Destination::kSystemMemory); EXPECT_TRUE(output->rect().IsEmpty()); auto scoped_bitmap = output->ScopedAccessSkBitmap(); auto bitmap = scoped_bitmap.bitmap(); EXPECT_FALSE(bitmap.readyToDraw()); EXPECT_EQ(output->GetTextureResult(), nullptr); } TEST_F(StructTraitsTest, CopyOutputResult_EmptyTexture) { base::test::TaskEnvironment task_environment; auto input = std::make_unique( CopyOutputRequest::ResultFormat::RGBA, CopyOutputRequest::ResultDestination::kNativeTextures, gfx::Rect(), false); EXPECT_TRUE(input->IsEmpty()); std::unique_ptr output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_TRUE(output->IsEmpty()); EXPECT_EQ(output->format(), CopyOutputResult::Format::RGBA); EXPECT_EQ(output->destination(), CopyOutputResult::Destination::kNativeTextures); EXPECT_TRUE(output->rect().IsEmpty()); EXPECT_EQ(output->GetTextureResult(), nullptr); } TEST_F(StructTraitsTest, CopyOutputResult_Bitmap) { const gfx::Rect result_rect(42, 43, 7, 8); SkBitmap bitmap; const sk_sp adobe_rgb = SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kAdobeRGB); bitmap.allocPixels(SkImageInfo::MakeN32Premul(7, 8, adobe_rgb)); bitmap.eraseARGB(123, 213, 77, 33); std::unique_ptr input = std::make_unique(result_rect, std::move(bitmap)); std::unique_ptr output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_FALSE(output->IsEmpty()); EXPECT_EQ(output->format(), CopyOutputResult::Format::RGBA); EXPECT_EQ(output->destination(), CopyOutputResult::Destination::kSystemMemory); EXPECT_EQ(output->rect(), result_rect); EXPECT_EQ(output->GetTextureResult(), nullptr); auto scoped_bitmap = output->ScopedAccessSkBitmap(); auto out_bitmap = scoped_bitmap.bitmap(); EXPECT_TRUE(out_bitmap.readyToDraw()); EXPECT_EQ(out_bitmap.width(), result_rect.width()); EXPECT_EQ(out_bitmap.height(), result_rect.height()); // Check that the pixels are the same as the input and the color spaces are // equivalent. SkBitmap expected_bitmap; expected_bitmap.allocPixels(SkImageInfo::MakeN32Premul(7, 8, adobe_rgb)); expected_bitmap.eraseARGB(123, 213, 77, 33); EXPECT_EQ(expected_bitmap.computeByteSize(), out_bitmap.computeByteSize()); EXPECT_EQ(0, std::memcmp(expected_bitmap.getPixels(), out_bitmap.getPixels(), expected_bitmap.computeByteSize())); EXPECT_TRUE(SkColorSpace::Equals(expected_bitmap.colorSpace(), out_bitmap.colorSpace())); } TEST_F(StructTraitsTest, CopyOutputResult_Texture) { base::test::TaskEnvironment task_environment; const gfx::Rect result_rect(12, 34, 56, 78); const gfx::ColorSpace result_color_space = gfx::ColorSpace::CreateDisplayP3D65(); const int8_t mailbox_name[GL_MAILBOX_SIZE_CHROMIUM] = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 9, 7, 5, 3, 1, 3}; gpu::SyncToken sync_token(gpu::CommandBufferNamespace::GPU_IO, gpu::CommandBufferId::FromUnsafeValue(0x123), 71234838); sync_token.SetVerifyFlush(); base::RunLoop run_loop; CopyOutputResult::ReleaseCallbacks release_callbacks; release_callbacks.push_back(base::BindOnce( [](base::OnceClosure quit_closure, const gpu::SyncToken& expected_sync_token, const gpu::SyncToken& sync_token, bool is_lost) { EXPECT_EQ(expected_sync_token, sync_token); EXPECT_TRUE(is_lost); std::move(quit_closure).Run(); }, run_loop.QuitClosure(), sync_token)); gpu::Mailbox mailbox; mailbox.SetName(mailbox_name); std::unique_ptr input = std::make_unique( CopyOutputResult::Format::RGBA, result_rect, CopyOutputResult::TextureResult(mailbox, sync_token, result_color_space), std::move(release_callbacks)); std::unique_ptr output; mojo::test::SerializeAndDeserialize(input, output); EXPECT_FALSE(output->IsEmpty()); EXPECT_EQ(output->format(), CopyOutputResult::Format::RGBA); EXPECT_EQ(output->destination(), CopyOutputResult::Destination::kNativeTextures); EXPECT_EQ(output->rect(), result_rect); ASSERT_NE(output->GetTextureResult(), nullptr); EXPECT_EQ(output->GetTextureResult()->planes[0].mailbox, mailbox); EXPECT_EQ(output->GetTextureResult()->planes[0].sync_token, sync_token); EXPECT_EQ(output->GetTextureResult()->color_space, result_color_space); CopyOutputResult::ReleaseCallbacks out_callbacks = output->TakeTextureOwnership(); EXPECT_EQ(1u, out_callbacks.size()); for (auto& cb : out_callbacks) { std::move(cb).Run(sync_token, true /* is_lost */); } // If the CopyOutputResult callback is called (which is the intended // behaviour), this will exit. Otherwise, this test will time out and fail. run_loop.Run(); } } // namespace viz ",16289,True,3125.250473872214,median "// Copyright (c) 2009-2018 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include ""MojDbKindTest.h"" #include ""db/MojDb.h"" #include ""db/MojDbKind.h"" #include ""db/MojDbReq.h"" #include ""db/MojDbStorageEngine.h"" #include ""MojDbTestStorageEngine.h"" #include ""db/MojDbServiceDefs.h"" #include ""core/MojJson.h"" namespace { MojString sandboxFileName(const MojChar *name) { MojString path; MojErr err = path.format(""%s/%s"", MojDbTestDir, name); assert(err == MojErrNone); return path; } } static const MojChar* const MojKindDumpTestFileName = _T(""kind_dumptest.json""); static const MojChar* const MojTestKindId = _T(""KindTest:1""); static const MojChar* const MojTestObjStr = _T(""{\\""_kind\\"":\\""KindTest:1\\"",\\""foo\\"":1,\\""bar\\"":2}""); static const MojChar* const MojTestObj2Str = _T(""{\\""_kind\\"":\\""KindTest:1\\"",\\""foo\\"":2,\\""bar\\"":4}""); static const MojChar* const MojTestKindStr = _T(""{\\""id\\"":\\""KindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\""}""); static const MojChar* const MojTestIndexesFooStr = _T(""{\\""id\\"":\\""KindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""foo\\"",\\""props\\"":[{\\""name\\"":\\""foo\\""}]}]}""); static const MojChar* const MojTestIndexesBarStr = _T(""{\\""id\\"":\\""KindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""bar\\"",\\""props\\"":[{\\""name\\"":\\""bar\\""}]}]}""); static const MojChar* const MojTestIndexesFooBarStr = _T(""{\\""id\\"":\\""KindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""foo\\"",\\""props\\"":[{\\""name\\"":\\""foo\\""}]},{\\""name\\"":\\""bar\\"",\\""props\\"":[{\\""name\\"":\\""bar\\""}]}]}""); static const MojChar* const MojTestIndexesBarFooStr = _T(""{\\""id\\"":\\""KindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""bar\\"",\\""props\\"":[{\\""name\\"":\\""bar\\""}]},{\\""name\\"":\\""foo\\"",\\""props\\"":[{\\""name\\"":\\""foo\\""}]}]}""); static const MojChar* const MojTestIndexesFooBazStr = _T(""{\\""id\\"":\\""KindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""foo\\"",\\""props\\"":[{\\""name\\"":\\""foo\\""}]},{\\""name\\"":\\""baz\\"",\\""props\\"":[{\\""name\\"":\\""baz\\""}]}]}""); static const MojChar* const MojTestChildKindStr = _T(""{\\""id\\"":\\""ChildKindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""extends\\"":[\\""ParentKindTest:1\\""]}""); static const MojChar* const MojTestChildObjStr = _T(""{\\""_kind\\"":\\""ChildKindTest:1\\"",\\""_id\\"":\\""myChild\\"",\\""foo\\"":1,\\""bar\\"":2}""); static const MojChar* const MojTestParentKindStr = _T(""{\\""id\\"":\\""ParentKindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""extends\\"":[\\""GrandparentKindTest:1\\""]}""); static const MojChar* const MojTestParentObjStr = _T(""{\\""_kind\\"":\\""ParentKindTest:1\\"",\\""_id\\"":\\""myParent\\"",\\""foo\\"":3,\\""bar\\"":4}""); static const MojChar* const MojTestGrandparentKindStr = _T(""{\\""id\\"":\\""GrandparentKindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\""}""); static const MojChar* const MojTestContactKindStrBadId = _T(""{\\""id\\"":\\""ContactTest:1\\"","") _T(""\\""owner\\"":\\""com.palm.contacts\\""}""); static const MojChar* const MojTestContactKindStrGoodId = _T(""{\\""id\\"":\\""com.palm.contacts.contact:1\\"","") _T(""\\""owner\\"":\\""com.palm.contacts\\""}""); static const MojChar* const MojTestContact2KindStrGoodId = _T(""{\\""id\\"":\\""com.palm.contacts.contact.addresses:1\\"","") _T(""\\""owner\\"":\\""com.palm.contacts\\""}""); static const MojChar* const MojTestContact2KindStrBadId = _T(""{\\""id\\"":\\""com.palm.contacts:1\\"","") _T(""\\""owner\\"":\\""com.palm.contacts\\""}""); static const MojChar* const MojTestChildContactKind = _T(""{\\""id\\"":\\""com.palm.contacts.person:1\\"","") _T(""\\""owner\\"":\\""com.palm.contacts\\"","") _T(""\\""extends\\"":[\\""GrandparentKindTest:1\\""]}""); static const MojChar* const ExtendsValue = _T(""[\\""GrandparentKindTest:1\\""]""); static const MojChar* const KindId = _T(""com.palm.contacts.person:1""); static const MojChar* const TestChildContactObject = _T(""{\\""_kind\\"":\\""com.palm.contacts.person:1\\"",\\""foo\\"":1,\\""bar\\"":2}""); static const MojChar* const MojTestObjectKindStr = _T(""{\\""id\\"":\\""Object:1\\"","") _T(""\\""owner\\"":\\""com.palm.contacts\\""}""); static const MojChar* const MojTestObjectKindStr2 = _T(""{\\""id\\"":\\""Object:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\""}""); static const MojChar* const TestPermissionObject = _T(""{\\""_kind\\"":\\""Permission:1\\"",\\""type\\"":1,\\""caller\\"":2}""); static const MojChar* const MojTestInvalidKindStr = _T(""{\\""id\\"":\\""\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\""}""); static const MojChar* const MojTestInvalidKind2Str = _T(""{\\""id\\"":\\""InvalidKindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":\\""randomStr\\""}""); static const MojChar* const MojTestInvalidKind3Str = _T(""{\\""id\\"":\\""InvalidKindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""randomStr\\"",\\""props\\"":\\""randomStr\\""}]}""); static const MojChar* const MojTestKindIdTooLong = _T(""{\\""id\\"":"") _T(""\\""KindTest2KindTest3KindTest4KindTest5KindTest6KindTest7"") _T(""KindTest8KindTest9KindTest10KindTest11KindTest12KindTest13"") _T(""KindTest14KindTest15KindTest16KindTest17KindTest18KindTest19"") _T(""KindTest20KindTest21KindTest22KindTest23KindTest24KindTest25"") _T(""KindTest26KindTest27KindTest28KindTest29KindTest30KindTest31"") _T(""KindTest32KindTest33KindTest34KindTest35KindTest36KindTest:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""props\\"":[{\\""name\\"":\\""foo\\""}]}]}""); static const MojChar* const MojTestKindIndexNameTooLong = _T(""{\\""id\\"":"") _T(""\\""InvalidKindTest2:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""KindTest2KindTest3KindTest4Kind"") _T(""Test5KindTest6KindTest7KindTest8KindTest9KindTest10KindTest11"") _T(""KindTest12KindTest13KindTest14KindTest15KindTest16KindTest17"") _T(""KindTest18KindTest19KindTest20KindTest21KindTest22KindTest23"") _T(""KindTest24KindTest25KindTest26KindTest27KindTest28KindTest29"") _T(""KindTest30KindTest31\\"",\\""props\\"":[{\\""name\\"":\\""foo\\""}]}]}""); static const MojChar* const MojTestKindIndexNameRepeat = _T(""{\\""id\\"":\\""InvalidKindTest3:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""random\\"",\\""props\\"":[{\\""name\\"":\\""_id\\""}],\\""incDel\\"":true},"") _T(""{\\""name\\"":\\""random\\"",\\""props\\"":\\""randomStr\\""}]}""); static const MojChar* const MojTestKindIndexNameRepeat2 = _T(""{\\""id\\"":\\""InvalidKindTest3:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""random\\"",\\""props\\"":[{\\""name\\"":\\""_id\\""}],\\""incDel\\"":true},"") _T(""{\\""name\\"":\\""RANDOM\\"",\\""props\\"":\\""randomStr\\""}]}""); static const MojChar* const MojTestKindIndexNameId = _T(""{\\""id\\"":\\""InvalidKindTest3:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""_id\\"",\\""props\\"":[{\\""name\\"":\\""_id\\""}],\\""incDel\\"":true}]}""); static const MojChar* const MojTestKindIndexNameInvalidChars = _T(""{\\""id\\"":\\""InvalidKindTest3:1\\"","") _T(""\\""owner\\"":\\""mojodb.admin\\"","") _T(""\\""indexes\\"":[{\\""name\\"":\\""123*abc\\"",\\""props\\"":[{\\""name\\"":\\""_id\\""}],\\""incDel\\"":true}]}""); MojDbKindTest::MojDbKindTest() : MojTestCase(_T(""MojDbKind"")) { } MojErr MojDbKindTest::run() { MojErr err = testIds(); MojTestErrCheck(err); err = testUpdate(); MojTestErrCheck(err); err = testUpdateWithObjects(); MojTestErrCheck(err); //err = testPermissions(); MojTestErrCheck(err); err = testPutKind(); MojTestErrCheck(err); err = testDelKind(); MojTestErrCheck(err); err = testReparent(); MojTestErrCheck(err); /*err = testPutKindWithPermissions(); MojTestErrCheck(err); err = testDelKindWithPermissions(); MojTestErrCheck(err); err = testPutGetPermissions(); MojTestErrCheck(err); err = testPutBuiltInKinds(); MojTestErrCheck(err); err = testInvalidKinds(); MojTestErrCheck(err); err = testObjectPermissions(); MojTestErrCheck(err);*/ err = testFindTokenizedIndex(); MojTestErrCheck(err); return MojErrNone; } MojErr MojDbKindTest::testIds() { MojDbKind t(NULL, NULL); MojObject obj; MojString str; MojErr err = str.assign(_T(""TestKind:15"")); MojTestErrCheck(err); err = t.init(str); MojTestErrCheck(err); MojTestAssert(t.id() == _T(""TestKind:15"")); MojTestAssert(t.name() == _T(""TestKind"")); MojTestAssert(t.version() == 15); MojDbKind t3(NULL, NULL); err = str.assign(_T(""TestKind15"")); MojTestErrCheck(err); err = t3.init(str); MojTestErrExpected(err, MojErrDbMalformedId); MojDbKind t4(NULL, NULL); err = str.assign(_T(""TestKind:9999999999"")); MojTestErrCheck(err); err = t4.init(str); MojTestErrExpected(err, MojErrDbMalformedId); return MojErrNone; } MojErr MojDbKindTest::testUpdate() { MojDb db; MojErr err = db.open(MojDbTestDir); MojTestErrCheck(err); // put obj w/o kind MojObject obj; err = obj.fromJson(MojTestObjStr); MojTestErrCheck(err); #ifdef LMDB_ENGINE_SUPPORT MojDbReq req; err = db.put(obj, MojDbFlagNone, req); req.end(); #else err = db.put(obj); #endif MojTestErrExpected(err, MojErrDbKindNotRegistered); // put kind MojObject kind; err = kind.fromJson(MojTestKindStr); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrCheck(err); // put obj w/ kind err = db.put(obj); MojTestErrCheck(err); // del kind MojObject kindId; err = kind.getRequired(MojDbServiceDefs::IdKey, kindId); MojTestErrCheck(err); bool found = false; err = db.delKind(kindId, found); MojTestErrCheck(err); MojTestAssert(found); // put obj after del kind err = obj.fromJson(MojTestObjStr); MojTestErrCheck(err); err = db.put(obj); MojTestErrExpected(err, MojErrDbKindNotRegistered); // re-put kind err = kind.fromJson(MojTestKindStr); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrCheck(err); // put obj w/ kind err = db.put(obj); MojTestErrCheck(err); // query no indexes MojDbQuery fooQuery; err = fooQuery.from(_T(""KindTest:1"")); MojTestErrCheck(err); err = fooQuery.where(_T(""foo""), MojDbQuery::OpEq, 8); MojTestErrCheck(err); MojDbCursor cursor; err = db.find(fooQuery, cursor); MojTestErrExpected(err, MojErrDbNoIndexForQuery); // add index on foo MojObject indexes; err = indexes.fromJson(MojTestIndexesFooStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); // query on foo w/ index err = db.find(fooQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); // delete kind err = db.delKind(kindId, found); MojTestErrCheck(err); MojTestAssert(found); // put kind back err = indexes.fromJson(MojTestIndexesFooStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); // query w/ re-added kind err = db.find(fooQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); // del kind MojObject indexesId; err = indexes.getRequired(MojDbServiceDefs::IdKey, indexesId); MojTestErrCheck(err); found = false; err = db.delKind(indexesId, found); MojTestErrCheck(err); MojTestAssert(found); // query after kind deleted err = db.find(fooQuery, cursor); MojTestErrExpected(err, MojErrDbKindNotRegistered); // re-put indexes err = indexes.fromJson(MojTestIndexesFooStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); // query after re-put indexes err = db.find(fooQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); // replace foo index with bar index err = indexes.fromJson(MojTestIndexesBarStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); // query for foo w/ no foo index err = db.find(fooQuery, cursor); MojTestErrExpected(err, MojErrDbNoIndexForQuery); // query for bar w/ index MojDbQuery barQuery; err = barQuery.from(_T(""KindTest:1"")); MojTestErrCheck(err); err = barQuery.where(_T(""bar""), MojDbQuery::OpEq, 24); MojTestErrCheck(err); err = db.find(barQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); // add foo index err = indexes.fromJson(MojTestIndexesFooBarStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); // query for foo and bar w/ indexes err = db.find(fooQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); err = db.find(barQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); // switch order of indexes in array err = indexes.fromJson(MojTestIndexesBarFooStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); // query for foo and bar w/ indexes err = db.find(fooQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); err = db.find(barQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); // replace bar index w/ baz index err = indexes.fromJson(MojTestIndexesFooBazStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); // query for bar w/o index err = db.find(barQuery, cursor); MojTestErrExpected(err, MojErrDbNoIndexForQuery); // query for foo and baz w/ indexes err = db.find(fooQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojDbQuery bazQuery; err = bazQuery.from(_T(""KindTest:1"")); MojTestErrCheck(err); err = bazQuery.where(_T(""baz""), MojDbQuery::OpEq, 24); MojTestErrCheck(err); err = db.find(bazQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); err = db.close(); MojTestErrCheck(err); return MojErrNone; } MojErr MojDbKindTest::testUpdateWithObjects() { MojDb db; MojErr err = db.open(MojDbTestDir); MojTestErrCheck(err); // put kind MojObject kind; err = kind.fromJson(MojTestKindStr); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrCheck(err); // put obj w/ kind MojObject obj; err = obj.fromJson(MojTestObjStr); MojTestErrCheck(err); err = db.put(obj); MojTestErrCheck(err); // query no indexes MojDbQuery fooQuery; err = fooQuery.from(_T(""KindTest:1"")); MojTestErrCheck(err); err = fooQuery.where(_T(""foo""), MojDbQuery::OpLessThan, 8); MojTestErrCheck(err); MojDbCursor cursor; err = db.find(fooQuery, cursor); MojTestErrExpected(err, MojErrDbNoIndexForQuery); // add index on foo MojObject indexes; err = indexes.fromJson(MojTestIndexesFooStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); // query on foo w/ index err = db.find(fooQuery, cursor); MojTestErrCheck(err); MojUInt32 count = 0; for (;;) { bool found = false; MojObject obj; MojErr err = cursor.get(obj, found); MojTestErrCheck(err); if (!found) break; ++count; MojInt64 foo; err = obj.getRequired(_T(""foo""), foo); MojTestErrCheck(err); MojInt64 bar; err = obj.getRequired(_T(""bar""), bar); MojTestErrCheck(err); MojTestAssert(foo == count); MojTestAssert(bar == count*2); } MojTestAssert(count == 1); err = cursor.close(); MojTestErrCheck(err); // put another obj w/ kind MojObject obj2; err = obj2.fromJson(MojTestObj2Str); MojTestErrCheck(err); err = db.put(obj2); MojTestErrCheck(err); // add index on bar MojObject foobarIndex; err = foobarIndex.fromJson(MojTestIndexesFooBarStr); MojTestErrCheck(err); err = db.putKind(foobarIndex); MojTestErrCheck(err); // query on bar w/ index MojDbQuery barQuery; err = barQuery.from(_T(""KindTest:1"")); MojTestErrCheck(err); err = barQuery.where(_T(""bar""), MojDbQuery::OpLessThan, 8); MojTestErrCheck(err); err = db.find(barQuery, cursor); MojTestErrCheck(err); count = 0; for (;;) { bool found = false; MojObject obj; MojErr err = cursor.get(obj, found); MojTestErrCheck(err); if (!found) break; ++count; MojInt64 foo; err = obj.getRequired(_T(""foo""), foo); MojTestErrCheck(err); MojInt64 bar; err = obj.getRequired(_T(""bar""), bar); MojTestErrCheck(err); MojTestAssert(foo == count); MojTestAssert(bar == count*2); } MojTestAssert(count == 2); err = cursor.close(); MojTestErrCheck(err); err = db.close(); MojTestErrCheck(err); return MojErrNone; } MojErr MojDbKindTest::testPermissions() { /* create this scenario: * GrandparentKind - allows com.palm.* and denies * * ParentKind - allows com.palm.contacts * - denies com.palm.mail * ChildKind- doesn't specify any permissions */ /* MojDbKind childKind; MojDbKind parentKind; MojDbKind grandParentKind; MojString childName; MojErr err = childName.assign(_T(""Child:1"")); MojTestErrCheck(err); err = childKind.init(childName, NULL, NULL); MojTestErrCheck(err); MojString parentName; err = parentName.assign(_T(""Parent:1"")); MojTestErrCheck(err); err = parentKind.init(parentName, NULL, NULL); MojTestErrCheck(err); MojString grandparentName; err = grandparentName.assign(_T(""Grandparent:1"")); MojTestErrCheck(err); err = grandParentKind.init(grandparentName, NULL, NULL); MojTestErrCheck(err); MojUInt32 allowMask = 0; MojUInt32 denyMask = 0; MojFlagSet(allowMask, OpCreate, true); MojFlagSet(allowMask, OpRead, true); MojFlagSet(denyMask, OpUpdate, true); err = grandParentKind.setPermission(allowMask, denyMask, _T(""com.palm.*"")); MojTestErrCheck(err); allowMask = 0; denyMask = 0; MojFlagSet(denyMask, OpCreate, true); MojFlagSet(denyMask, OpRead, true); MojFlagSet(denyMask, OpUpdate, true); MojFlagSet(denyMask, OpDelete, true); err = grandParentKind.setPermission(allowMask, denyMask, _T(""*"")); MojTestErrCheck(err); allowMask = 0; denyMask = 0; MojFlagSet(allowMask, OpRead, true); MojFlagSet(allowMask, OpUpdate, true); MojFlagSet(allowMask, OpDelete, true); err = parentKind.setPermission(allowMask, denyMask, _T(""com.palm.contacts"")); MojTestErrCheck(err); allowMask = 0; denyMask = 0; MojFlagSet(denyMask, OpCreate, true); MojFlagSet(denyMask, OpRead, true); MojFlagSet(denyMask, OpDelete, true); err = parentKind.setPermission(allowMask, denyMask, _T(""com.palm.mail"")); MojTestErrCheck(err); err = childKind.addSuper(&parentKind); MojTestErrCheck(err); err = parentKind.addSuper(&grandParentKind); MojTestErrCheck(err); MojDbReq info(false); err = info.domain(_T(""com.palm.contacts"")); MojTestErrCheck(err); //test com.palm.contacts permissions on GrandparentKind err = grandParentKind.checkPermission(info, OpCreate, NULL); MojTestErrCheck(err); err = grandParentKind.checkPermission(info, OpRead, NULL); MojTestErrCheck(err); err = grandParentKind.checkPermission(info, OpUpdate, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); err = grandParentKind.checkPermission(info, OpDelete, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); //test com.palm.contacts permissions on ParentKind err = parentKind.checkPermission(info, OpCreate, NULL); MojTestErrCheck(err); err = parentKind.checkPermission(info, OpRead, NULL); MojTestErrCheck(err); err = parentKind.checkPermission(info, OpUpdate, NULL); MojTestErrCheck(err); err = parentKind.checkPermission(info, OpDelete, NULL); MojTestErrCheck(err); //test com.palm.contacts permissions on ChildKind err = childKind.checkPermission(info, OpCreate, NULL); MojTestErrCheck(err); err = childKind.checkPermission(info, OpRead, NULL); MojTestErrCheck(err); err = childKind.checkPermission(info, OpUpdate, NULL); MojTestErrCheck(err); err = childKind.checkPermission(info, OpDelete, NULL); MojTestErrCheck(err); MojDbReq mailInfo(false); err = mailInfo.domain(_T(""com.palm.mail"")); MojTestErrCheck(err); //test com.palm.mail permissions on GrandparentKind err = grandParentKind.checkPermission(mailInfo, OpCreate, NULL); MojTestErrCheck(err); err = grandParentKind.checkPermission(mailInfo, OpRead, NULL); MojTestErrCheck(err); err = grandParentKind.checkPermission(mailInfo, OpUpdate, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); err = grandParentKind.checkPermission(mailInfo, OpDelete, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); //test com.palm.contacts permissions on ParentKind err = parentKind.checkPermission(mailInfo, OpCreate, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); err = parentKind.checkPermission(mailInfo, OpRead, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); err = parentKind.checkPermission(mailInfo, OpUpdate, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); err = parentKind.checkPermission(mailInfo, OpDelete, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); //test com.palm.contacts permissions on ChildKind err = childKind.checkPermission(mailInfo, OpCreate, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); err = childKind.checkPermission(mailInfo, OpRead, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); err = childKind.checkPermission(mailInfo, OpUpdate, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); err = childKind.checkPermission(mailInfo, OpDelete, NULL); MojTestErrExpected(err, MojErrDbAccessDenied); */ return MojErrNone; } MojErr MojDbKindTest::testPutKind() { //setup the test storage engine MojErr err; MojRefCountedPtr engine; err = MojDbStorageEngine::createDefaultEngine(engine); MojTestErrCheck(err); MojAllocCheck(engine.get()); MojRefCountedPtr testEngine(new MojDbTestStorageEngine(engine.get())); MojAllocCheck(testEngine.get()); err = testEngine->open(MojDbTestDir); MojTestErrCheck(err); MojDb db; err = db.open(MojDbTestDir, testEngine.get()); MojTestErrCheck(err); MojObject kind; err = kind.fromJson(MojTestKindStr); MojTestErrCheck(err); // del kind so we start fresh MojObject kindId; err = kind.getRequired(MojDbServiceDefs::IdKey, kindId); MojTestErrCheck(err); bool found = false; err = db.delKind(kindId, found); MojTestErrCheck(err); MojTestAssert(found); // put kind err = db.putKind(kind); MojTestErrCheck(err); // put obj w/ kind MojObject obj; err = obj.fromJson(MojTestObjStr); MojTestErrCheck(err); err = db.put(obj); MojTestErrCheck(err); // query no indexes MojDbQuery fooQuery; err = fooQuery.from(_T(""KindTest:1"")); MojTestErrCheck(err); err = fooQuery.where(_T(""foo""), MojDbQuery::OpLessThan, 8); MojTestErrCheck(err); MojDbCursor cursor; err = db.find(fooQuery, cursor); MojTestErrExpected(err, MojErrDbNoIndexForQuery); // add index on foo MojObject indexes; err = indexes.fromJson(MojTestIndexesFooStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); // query on foo w/ index err = db.find(fooQuery, cursor); MojTestErrCheck(err); int count = 0; for (;;) { bool found = false; MojObject obj; MojErr err = cursor.get(obj, found); MojTestErrCheck(err); if (!found) break; ++count; MojInt64 foo; err = obj.getRequired(_T(""foo""), foo); MojTestErrCheck(err); MojInt64 bar; err = obj.getRequired(_T(""bar""), bar); MojTestErrCheck(err); MojTestAssert(foo == count); MojTestAssert(bar == count*2); } MojTestAssert(count == 1); err = cursor.close(); MojTestErrCheck(err); MojDbTestStorageEngine* engineImpl = static_cast(db.storageEngine()); err = engineImpl->setNextError(_T(""txn.commit""), MojErrDbDeadlock); MojTestErrCheck(err); //add an index on bar MojObject barIndex; err = barIndex.fromJson(MojTestIndexesBarStr); MojTestErrCheck(err); err = db.putKind(barIndex); // this transaction commit should fail MojTestErrExpected(err, MojErrDbDeadlock); //shouldn't be able to query on bar, but should still be able to query on foo MojDbQuery barQuery; err = barQuery.from(_T(""KindTest:1"")); MojTestErrCheck(err); err = barQuery.where(_T(""bar""), MojDbQuery::OpLessThan, 8); MojTestErrCheck(err); err = db.find(barQuery, cursor); MojTestErrExpected(err, MojErrDbNoIndexForQuery); err = db.find(fooQuery, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); err = db.close(); MojTestErrCheck(err); return MojErrNone; } MojErr MojDbKindTest::testDelKind() { //setup the test storage engine MojErr err; MojRefCountedPtr engine; err = MojDbStorageEngine::createDefaultEngine(engine); MojTestErrCheck(err); MojAllocCheck(engine.get()); MojRefCountedPtr testEngine(new MojDbTestStorageEngine(engine.get())); MojAllocCheck(testEngine.get()); err = testEngine->open(MojDbTestDir); MojErrCheck(err); MojDb db; err = db.open(MojDbTestDir, testEngine.get()); MojTestErrCheck(err); MojObject kind; err = kind.fromJson(MojTestKindStr); MojTestErrCheck(err); // del everything so we start fresh MojObject id; err = kind.getRequired(MojDbServiceDefs::IdKey, id); MojTestErrCheck(err); bool found = false; err = db.delKind(id, found); MojTestErrCheck(err); MojTestAssert(found); // put kind err = db.putKind(kind); MojTestErrCheck(err); // put obj w/ kind MojObject obj; err = obj.fromJson(MojTestObjStr); MojTestErrCheck(err); err = db.put(obj); MojTestErrCheck(err); // add index on foo MojObject indexes; err = indexes.fromJson(MojTestIndexesFooStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); // query on foo w/ index MojDbCursor cursor; MojDbQuery fooQuery; err = fooQuery.from(_T(""KindTest:1"")); MojTestErrCheck(err); err = fooQuery.where(_T(""foo""), MojDbQuery::OpLessThan, 8); MojTestErrCheck(err); err = db.find(fooQuery, cursor); MojTestErrCheck(err); MojUInt32 count = 0; for (;;) { found = false; MojObject obj; MojErr err = cursor.get(obj, found); MojTestErrCheck(err); if (!found) break; ++count; } MojTestAssert(count == 1); err = cursor.close(); MojTestErrCheck(err); // del kind - make sure everything is gone MojObject kindId; err = kind.getRequired(MojDbServiceDefs::IdKey, kindId); MojTestErrCheck(err); found = false; err = db.delKind(kindId, found); MojTestErrCheck(err); MojTestAssert(found); //try to delete all objects again, but nothing should be deleted MojDbQuery query; if (db.isRootKindEnabled()) { err = query.from(MojDbKindEngine::RootKindId); MojTestErrCheck(err); MojUInt32 delCount = 0; err = db.del(query, delCount); MojTestErrCheck(err); MojTestAssert(delCount == 0); } else { // No RootKind, check dump count whether all object is deleted correctly err = db.dump(sandboxFileName(MojKindDumpTestFileName), count); MojTestErrCheck(err); MojTestAssert(count == 0); } //try to put an object of this kind err = obj.fromJson(MojTestObjStr); MojTestErrCheck(err); err = db.put(obj); MojTestErrExpected(err, MojErrDbKindNotRegistered); //put the kind back err = indexes.fromJson(MojTestIndexesFooStr); MojTestErrCheck(err); err = db.putKind(indexes); MojTestErrCheck(err); //now try to delete the kind with an error on transaction commit MojDbTestStorageEngine* engineImpl = static_cast(db.storageEngine()); err = engineImpl->setNextError(_T(""txn.commit""), MojErrDbDeadlock); MojTestErrCheck(err); found = false; err = db.delKind(kindId, found); //the transaction commit should fail MojTestErrExpected(err, MojErrDbDeadlock); MojTestAssert(!found); //now putting an object of this kind should still work err = db.put(obj); MojTestErrCheck(err); //and querying for it should also work err = db.find(fooQuery, cursor); MojTestErrCheck(err); count = 0; for (;;) { bool found = false; MojObject obj; MojErr err = cursor.get(obj, found); MojTestErrCheck(err); if (!found) break; ++count; MojInt64 foo; err = obj.getRequired(_T(""foo""), foo); MojTestErrCheck(err); MojInt64 bar; err = obj.getRequired(_T(""bar""), bar); MojTestErrCheck(err); MojTestAssert(foo == count); MojTestAssert(bar == count*2); } MojTestAssert(count == 1); err = cursor.close(); MojTestErrCheck(err); err = db.close(); MojTestErrCheck(err); return MojErrNone; } MojErr MojDbKindTest::testReparent() { MojDb db; MojErr err = db.open(MojDbTestDir); MojTestErrCheck(err); // create Kind1 with index on foo MojObject kind; err = kind.fromJson(_T(""{\\""id\\"":\\""KindA:1\\"",\\""owner\\"":\\""foo\\"",\\""indexes\\"":[{\\""name\\"":\\""foo\\"",\\""props\\"":[{\\""name\\"":\\""foo\\""}]}]}"")); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrCheck(err); // create KindB err = kind.fromJson(_T(""{\\""id\\"":\\""KindB:1\\"",\\""owner\\"":\\""foo\\""}"")); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrCheck(err); // create object of KindB with foo prop MojObject obj; err = obj.fromJson(_T(""{\\""_id\\"":1000,\\""_kind\\"":\\""KindB:1\\"",\\""foo\\"":1}"")); MojTestErrCheck(err); err = db.put(obj); MojTestErrCheck(err); // make KindB extend kindA err = kind.fromJson(_T(""{\\""id\\"":\\""KindB:1\\"",\\""owner\\"":\\""foo\\"",\\""extends\\"":[\\""KindA:1\\""]}"")); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrCheck(err); // update foo prop on KindB object err = obj.put(_T(""foo""), 2); MojTestErrCheck(err); err = db.put(obj); MojTestErrCheck(err); // query on KindA MojDbQuery query; err = query.from(_T(""KindA:1"")); MojTestErrCheck(err); err = query.where(_T(""foo""), MojDbQuery::OpGreaterThan, 0); MojTestErrCheck(err); MojDbCursor cursor; err = db.find(query, cursor); MojTestErrCheck(err); MojUInt32 count = 0; err = cursor.count(count); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(count == 1); // unparent KindB from KindA err = kind.fromJson(_T(""{\\""id\\"":\\""KindB:1\\"",\\""owner\\"":\\""foo\\""}"")); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrCheck(err); // query on KindA err = db.find(query, cursor); MojTestErrCheck(err); count = 0; err = cursor.count(count); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojTestAssert(count == 0); err = db.close(); MojTestErrCheck(err); return MojErrNone; } MojErr MojDbKindTest::testPutKindWithPermissions() { /* MojDb db; MojObject conf; MojObject dbObj; MojErr err = dbObj.putBool(_T(""accessControl""), true); MojTestErrCheck(err); err = conf.put(_T(""db""), dbObj); MojTestErrCheck(err); err = db.configure(conf); MojTestErrCheck(err); err = db.open(MojDbTestDir); MojTestErrCheck(err); // del everything so we start fresh MojDbQuery query; err = query.from(MojDbKindEngine::RootKindId); MojTestErrCheck(err); MojUInt32 delCount; err = db.del(query, delCount); MojTestErrCheck(err); MojTestAssert(delCount > 0); MojDbReq contactInfo(false); err = contactInfo.domain(_T(""com.palm.contacts"")); MojTestErrCheck(err); contactInfo.beginBatch(); MojObject kind; err = kind.fromJson(MojTestContactKindStrBadId); MojTestErrCheck(err); // put kind - kindId is not valid relative to caller err = db.putKind(kind, MojDbFlagNone, contactInfo); MojTestErrExpected(err, MojErrDbMalformedId); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); // put kind - owner invalid err = kind.putString(MojDbServiceDefs::OwnerKey, _T("""")); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrExpected(err, MojErrDbInvalidOwner); // put same kind with admin privileges - anything goes err = kind.putString(MojDbServiceDefs::OwnerKey, _T(""com.palm.contacts"")); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrCheck(err); // put same kind - try to change owner err = kind.putString(MojDbServiceDefs::OwnerKey, _T(""com.palm.calendar"")); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrCheck(err); MojDbReq calInfo(false); err = calInfo.domain(_T(""com.palm.calendar"")); MojTestErrCheck(err); calInfo.beginBatch(); // put kind - caller is invalid relative to kindId MojObject kind2; err = kind2.fromJson(MojTestContactKindStrGoodId); MojTestErrCheck(err); err = db.putKind(kind2, MojDbFlagNone, calInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = calInfo.abort(); MojTestErrCheck(err); err = calInfo.endBatch(); MojTestErrCheck(err); // put same kind with correct caller (kindId's prefix and caller's prefix match) contactInfo.beginBatch(); err = db.putKind(kind2, MojDbFlagNone, contactInfo); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); // put kind - kindId starts with caller string but doesn't have a '.' after caller contactInfo.beginBatch(); MojObject kind3; err = kind3.fromJson(MojTestContact2KindStrBadId); MojTestErrCheck(err); err = db.putKind(kind3, MojDbFlagNone, contactInfo); MojTestErrExpected(err, MojErrDbMalformedId); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); // put kind - kindId starts with caller and has multiple levels after that contactInfo.beginBatch(); MojObject kind4; err = kind4.fromJson(MojTestContact2KindStrGoodId); MojTestErrCheck(err); err = db.putKind(kind4, MojDbFlagNone, contactInfo); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); //have mojodb.admin put the grandfather kind MojObject grandfather; err = grandfather.fromJson(MojTestGrandparentKindStr); MojTestErrCheck(err); err = db.putKind(grandfather); MojTestErrCheck(err); //now have contacts try to put the contact child kind contactInfo.beginBatch(); MojObject contactChild; err = contactChild.fromJson(MojTestChildContactKind); MojTestErrCheck(err); err = db.putKind(contactChild, MojDbFlagNone, contactInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); //have mojodb.admin put the contact child kind err = db.putKind(contactChild); MojTestErrCheck(err); // try to update kind4 to extend Grandparent kind contactInfo.beginBatch(); MojObject extends; err = extends.fromJson(ExtendsValue); MojTestErrCheck(err); err = kind4.put(_T(""extends""), extends); MojTestErrCheck(err); err = db.putKind(kind4, MojDbFlagNone, contactInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); // try to put a kind with an invalid id MojObject invalidKind; err = invalidKind.fromJson(MojTestInvalidKindStr); MojTestErrCheck(err); err = db.putKind(invalidKind); MojTestErrExpected(err, MojErrDbMalformedId); return MojErrNone; } MojErr MojDbKindTest::testDelKindWithPermissions() { MojDb db; MojObject conf; MojObject dbObj; MojErr err = dbObj.putBool(_T(""accessControl""), true); MojTestErrCheck(err); err = conf.put(_T(""db""), dbObj); MojTestErrCheck(err); err = db.configure(conf); MojTestErrCheck(err); err = db.open(MojDbTestDir); MojTestErrCheck(err); MojDbReq contactInfo(false); err = contactInfo.domain(_T(""com.palm.contacts"")); MojTestErrCheck(err); MojDbReq calInfo(false); err = calInfo.domain(_T(""com.palm.calendar"")); MojTestErrCheck(err); //when you delete a kind, the caller must be the owner of the kind OR mojodb.admin MojObject contactKind; err = contactKind.fromJson(MojTestContactKindStrGoodId); MojTestErrCheck(err); // try deleting using calendar as caller - should fail calInfo.beginBatch(); MojObject id; err = contactKind.getRequired(MojDbServiceDefs::IdKey, id); MojTestErrCheck(err); bool found = false; err = db.delKind(id, found, MojDbFlagNone, calInfo); MojTestErrExpected(err, MojErrDbAccessDenied); MojTestAssert(!found); err = calInfo.abort(); MojTestErrCheck(err); err = calInfo.endBatch(); MojTestErrCheck(err); // delete with contacts as caller contactInfo.beginBatch(); err = db.delKind(id, found, MojDbFlagNone, contactInfo); MojTestErrCheck(err); MojTestAssert(found); err = contactInfo.endBatch(); MojTestErrCheck(err); // delete a contact owned kind with mojodb.admin as caller MojObject contactKind2; err = contactKind2.fromJson(MojTestContact2KindStrGoodId); MojTestErrCheck(err); err = contactKind2.getRequired(MojDbServiceDefs::IdKey, id); MojTestErrCheck(err); err = db.delKind(id, found); MojTestErrCheck(err); MojTestAssert(found); // delete a mojodb.admin owned kind with contacts as caller MojObject grandfather; err = grandfather.fromJson(MojTestGrandparentKindStr); MojTestErrCheck(err); contactInfo.beginBatch(); err = grandfather.getRequired(MojDbServiceDefs::IdKey, id); MojTestErrCheck(err); err = db.delKind(id, found, MojDbFlagNone, contactInfo); MojTestErrExpected(err, MojErrDbAccessDenied); MojTestAssert(!found); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); // delete it with mojodb.admin as caller err = db.delKind(id, found); MojTestErrCheck(err); MojTestAssert(found); return MojErrNone; } MojErr MojDbKindTest::testPutGetPermissions() { MojDb db; MojObject conf; MojObject dbObj; MojErr err = dbObj.putBool(_T(""accessControl""), true); MojTestErrCheck(err); err = conf.put(_T(""db""), dbObj); MojTestErrCheck(err); err = db.configure(conf); MojTestErrCheck(err); err = db.open(MojDbTestDir); MojTestErrCheck(err); MojDbReq contactInfo(false); err = contactInfo.domain(_T(""com.palm.contacts"")); MojTestErrCheck(err); MojDbReq calInfo(false); err = calInfo.domain(_T(""com.palm.calendar"")); MojTestErrCheck(err); //when you read permissions on a kind, the caller must be the owner of the kind OR mojodb.admin MojObject contactKind; err = contactKind.fromJson(MojTestContactKindStrGoodId); MojTestErrCheck(err); // try reading permissions using calendar as caller - should fail MojString permissionType; err = permissionType.assign(MojDbServiceDefs::DbKindValue); MojTestErrCheck(err); MojString kindId; err = kindId.assign(KindId); MojTestErrCheck(err); MojDbCursor cursor; calInfo.beginBatch(); err = db.getPermissions(permissionType, kindId, cursor, calInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = cursor.close(); MojTestErrCheck(err); err = calInfo.abort(); MojTestErrCheck(err); err = calInfo.endBatch(); MojTestErrCheck(err); // read permissions with contacts as caller contactInfo.beginBatch(); err = db.getPermissions(permissionType, kindId, cursor, contactInfo); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); // read permissions with admin caller err = db.getPermissions(permissionType, kindId, cursor); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojObject permission; err = permission.putString(MojDbServiceDefs::TypeKey, MojDbServiceDefs::DbKindValue); MojTestErrCheck(err); err = permission.putString(MojDbServiceDefs::CallerKey, _T(""com.palm.calendar"")); MojTestErrCheck(err); err = permission.putString(MojDbServiceDefs::ObjectKey, KindId); MojTestErrCheck(err); MojObject operations; err = operations.putString(MojDbServiceDefs::CreateKey, MojDbServiceDefs::AllowValue); MojTestErrCheck(err); err = permission.put(MojDbServiceDefs::OperationsKey, operations); MojTestErrCheck(err); //try to put a child contact object from calendar calInfo.beginBatch(); MojObject obj; err = obj.fromJson(TestChildContactObject); MojTestErrCheck(err); err = db.put(obj, MojDbFlagNone, calInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = calInfo.abort(); MojTestErrCheck(err); err = calInfo.endBatch(); MojTestErrCheck(err); calInfo.beginBatch(); err = db.putPermissions(&permission, &permission + 1, calInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = calInfo.abort(); MojTestErrCheck(err); err = calInfo.endBatch(); MojTestErrCheck(err); contactInfo.beginBatch(); err = db.putPermissions(&permission, &permission + 1, contactInfo); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); //now that permissions have been set, create an object of that kind from calendar calInfo.beginBatch(); err = db.put(obj, MojDbFlagNone, calInfo); MojTestErrCheck(err); err = calInfo.endBatch(); MojTestErrCheck(err); // try to put permissions on a kind that doesn't exist MojObject permission2; err = permission2.putString(MojDbServiceDefs::TypeKey, MojDbServiceDefs::DbKindValue); MojTestErrCheck(err); err = permission2.putString(MojDbServiceDefs::CallerKey, _T(""com.palm.calendar"")); MojTestErrCheck(err); err = permission2.putString(MojDbServiceDefs::ObjectKey, _T(""invalidId"")); MojTestErrCheck(err); MojObject operations2; err = operations2.putString(MojDbServiceDefs::CreateKey, MojDbServiceDefs::AllowValue); MojTestErrCheck(err); err = permission2.put(MojDbServiceDefs::OperationsKey, operations2); MojTestErrCheck(err); contactInfo.beginBatch(); err = db.putPermissions(&permission2, &permission2 + 1, contactInfo); MojTestErrExpected(err, MojErrDbMalformedId); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); MojObject invalidOperationKey; err = invalidOperationKey.putString(_T(""fakeKey""), MojDbServiceDefs::AllowValue); MojTestErrCheck(err); err = permission.put(MojDbServiceDefs::OperationsKey, invalidOperationKey); MojTestErrCheck(err); contactInfo.beginBatch(); err = db.putPermissions(&permission, &permission + 1, contactInfo); MojTestErrExpected(err, MojErrDbInvalidOperation); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); MojObject invalidOperationValue; err = invalidOperationValue.putString(MojDbServiceDefs::CreateKey, _T(""fakeValue"")); MojTestErrCheck(err); err = permission.put(MojDbServiceDefs::OperationsKey, invalidOperationValue); MojTestErrCheck(err); contactInfo.beginBatch(); err = db.putPermissions(&permission, &permission + 1, contactInfo); MojTestErrExpected(err, MojErrDbInvalidOperation); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); */ return MojErrNone; } MojErr MojDbKindTest::testPutBuiltInKinds() { MojDb db; MojObject conf; MojObject dbObj; MojErr err = dbObj.putBool(_T(""accessControl""), true); MojTestErrCheck(err); err = conf.put(_T(""db""), dbObj); MojTestErrCheck(err); err = db.configure(conf); MojTestErrCheck(err); err = db.open(MojDbTestDir); MojTestErrCheck(err); MojDbReq contactInfo(false); err = contactInfo.domain(_T(""com.palm.contacts"")); MojTestErrCheck(err); MojObject rootKind; err = rootKind.fromJson(MojTestObjectKindStr); MojTestErrCheck(err); contactInfo.beginBatch(); err = db.putKind(rootKind, MojDbFlagNone, contactInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); MojObject rootKind2; err = rootKind2.fromJson(MojTestObjectKindStr2); MojTestErrCheck(err); contactInfo.beginBatch(); err = db.putKind(rootKind2, MojDbFlagNone, contactInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); //try putting kind with admin privileges err = db.putKind(rootKind2, MojDbFlagNone); MojTestErrExpected(err, MojErrDbAccessDenied); MojObject permission; err = permission.fromJson(TestPermissionObject); MojTestErrCheck(err); contactInfo.beginBatch(); err = db.put(permission, MojDbFlagNone, contactInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); MojDbQuery query; err = query.from(_T(""Permission:1"")); MojTestErrCheck(err); MojDbCursor cursor; contactInfo.beginBatch(); err = db.find(query, cursor, contactInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = cursor.close(); MojTestErrCheck(err); err = contactInfo.abort(); MojTestErrCheck(err); err = contactInfo.endBatch(); MojTestErrCheck(err); return MojErrNone; } MojErr MojDbKindTest::testInvalidKinds() { MojDb db; MojErr err = db.open(MojDbTestDir); MojTestErrCheck(err); // put kind MojObject kind; err = kind.fromJson(MojTestInvalidKind2Str); MojTestErrCheck(err); err = db.putKind(kind); // this doesn't throw an error for now - schema validation will catch this. // adding this test just to make sure we don't crash MojTestErrCheck(err); // put another kind err = kind.fromJson(MojTestInvalidKind3Str); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrExpected(err, MojErrDbInvalidIndex); // put kind err = kind.fromJson(MojTestKindIdTooLong); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrExpected(err, MojErrDbMalformedId); // invalid index names err = kind.fromJson(MojTestKindIndexNameTooLong); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrExpected(err, MojErrDbInvalidIndexName); err = kind.fromJson(MojTestKindIndexNameRepeat); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrExpected(err, MojErrDbInvalidIndexName); err = kind.fromJson(MojTestKindIndexNameRepeat2); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrExpected(err, MojErrDbInvalidIndexName); err = kind.fromJson(MojTestKindIndexNameId); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrExpected(err, MojErrDbInvalidIndexName); err = kind.fromJson(MojTestKindIndexNameInvalidChars); MojTestErrCheck(err); err = db.putKind(kind); MojTestErrExpected(err, MojErrDbInvalidIndexName); return MojErrNone; } MojErr MojDbKindTest::testObjectPermissions() { /* create this scenario: * GrandparentKind - allows com.palm.* and denies * * ParentKind - allows com.palm.contacts * - denies com.palm.mail * ChildKind- doesn't specify any permissions */ MojDb db; MojObject conf; MojObject dbObj; MojErr err = dbObj.putBool(_T(""accessControl""), true); MojTestErrCheck(err); err = conf.put(_T(""db""), dbObj); MojTestErrCheck(err); err = db.configure(conf); MojTestErrCheck(err); err = db.open(MojDbTestDir); MojTestErrCheck(err); // del everything so we start fresh MojDbQuery query; if (db.isRootKindEnabled()) { err = query.from(MojDbKindEngine::RootKindId); MojTestErrCheck(err); MojUInt32 delCount; err = db.del(query, delCount); MojTestErrCheck(err); MojTestAssert(delCount > 0); } else { MojUInt32 count; // No RootKind, check dump count whether all object is deleted correctly err = db.dump(sandboxFileName(MojKindDumpTestFileName), count); MojTestErrCheck(err); MojTestAssert(count == 0); } MojDbReq adminInfo(true); adminInfo.beginBatch(); MojObject kind; err = kind.fromJson(MojTestGrandparentKindStr); MojTestErrCheck(err); err = db.putKind(kind, MojDbFlagNone, adminInfo); MojTestErrCheck(err); err = kind.fromJson(MojTestParentKindStr); MojTestErrCheck(err); err = db.putKind(kind, MojDbFlagNone, adminInfo); MojTestErrCheck(err); err = kind.fromJson(MojTestChildKindStr); MojTestErrCheck(err); err = db.putKind(kind, MojDbFlagNone, adminInfo); MojTestErrCheck(err); err = adminInfo.endBatch(); MojTestErrCheck(err); adminInfo.beginBatch(); MojObject permission; err = permission.putString(MojDbServiceDefs::TypeKey, MojDbKind::PermissionType); MojTestErrCheck(err); err = permission.putString(MojDbServiceDefs::CallerKey, _T(""com.palm.contacts"")); MojTestErrCheck(err); err = permission.putString(MojDbServiceDefs::ObjectKey, _T(""ParentKindTest:1"")); MojTestErrCheck(err); MojObject operation; err = operation.putString(MojDbServiceDefs::ReadKey, MojDbServiceDefs::AllowValue); MojTestErrCheck(err); err = permission.put(MojDbServiceDefs::OperationsKey, operation); MojTestErrCheck(err); MojObject permissionsArray; err = permissionsArray.push(permission); MojTestErrCheck(err); MojObject permission2; err = permission2.putString(MojDbServiceDefs::TypeKey, MojDbKind::PermissionType); MojTestErrCheck(err); err = permission2.putString(MojDbServiceDefs::CallerKey, _T(""com.palm.calendar"")); MojTestErrCheck(err); err = permission2.putString(MojDbServiceDefs::ObjectKey, _T(""ChildKindTest:1"")); MojTestErrCheck(err); err = permission2.put(MojDbServiceDefs::OperationsKey, operation); MojTestErrCheck(err); err = permissionsArray.push(permission2); MojTestErrCheck(err); MojObject permission3; err = permission3.putString(MojDbServiceDefs::TypeKey, MojDbKind::PermissionType); MojTestErrCheck(err); err = permission3.putString(MojDbServiceDefs::CallerKey, _T(""com.palm.messaging"")); MojTestErrCheck(err); err = permission3.putString(MojDbServiceDefs::ObjectKey, _T(""ParentKindTest:1"")); MojTestErrCheck(err); err = operation.putString(MojDbServiceDefs::UpdateKey, MojDbServiceDefs::AllowValue); MojTestErrCheck(err); err = operation.putString(MojDbServiceDefs::DeleteKey, MojDbServiceDefs::AllowValue); MojTestErrCheck(err); err = permission3.put(MojDbServiceDefs::OperationsKey, operation); MojTestErrCheck(err); err = permissionsArray.push(permission3); MojTestErrCheck(err); MojObject permission4; err = permission4.putString(MojDbServiceDefs::TypeKey, MojDbKind::PermissionType); MojTestErrCheck(err); err = permission4.putString(MojDbServiceDefs::CallerKey, _T(""com.palm.messaging"")); MojTestErrCheck(err); err = permission4.putString(MojDbServiceDefs::ObjectKey, _T(""ChildKindTest:1"")); MojTestErrCheck(err); MojObject operation2; err = operation2.putString(MojDbServiceDefs::ReadKey, MojDbServiceDefs::DenyValue); MojTestErrCheck(err); err = operation2.putString(MojDbServiceDefs::UpdateKey, MojDbServiceDefs::DenyValue); MojTestErrCheck(err); err = operation2.putString(MojDbServiceDefs::DeleteKey, MojDbServiceDefs::DenyValue); MojTestErrCheck(err); err = permission4.put(MojDbServiceDefs::OperationsKey, operation2); MojTestErrCheck(err); err = permissionsArray.push(permission4); MojTestErrCheck(err); MojObject::ArrayIterator begin; err = permissionsArray.arrayBegin(begin); MojErrCheck(err); MojObject::ConstArrayIterator end = permissionsArray.arrayEnd(); err = db.putPermissions(begin, end, adminInfo); MojTestErrCheck(err); adminInfo.endBatch(); MojTestErrCheck(err); MojObject parent; err = parent.fromJson(MojTestParentObjStr); MojTestErrCheck(err); MojObject child; err = child.fromJson(MojTestChildObjStr); MojTestErrCheck(err); MojObject objects; err = objects.push(parent); MojTestErrCheck(err); err = objects.push(child); MojTestErrCheck(err); adminInfo.beginBatch(); MojObject::ArrayIterator objBegin; err = objects.arrayBegin(objBegin); err = db.put(objBegin, objects.arrayEnd(), MojDbFlagNone, adminInfo); MojTestErrCheck(err); err = adminInfo.endBatch(); MojTestErrCheck(err); MojDbReq calInfo(false); err = calInfo.domain(_T(""com.palm.calendar"")); MojTestErrCheck(err); MojDbReq contactsInfo(false); err = contactsInfo.domain(_T(""com.palm.contacts"")); MojTestErrCheck(err); MojString parentId; err = parentId.assign(_T(""myParent"")); MojTestErrCheck(err); MojString childId; err = childId.assign(_T(""myChild"")); MojTestErrCheck(err); // cal can read child MojObject childFromDB; bool found; err = db.get(childId, childFromDB, found, calInfo); MojTestErrCheck(err); MojTestAssert(found); err = childFromDB.del(MojDb::RevKey, found); MojTestErrCheck(err); MojTestAssert(child == childFromDB); // contacts can read child since it can read the parent err = db.get(childId, childFromDB, found, contactsInfo); MojTestErrCheck(err); MojTestAssert(found); err = childFromDB.del(MojDb::RevKey, found); MojTestErrCheck(err); MojTestAssert(child == childFromDB); // contacts can read parent MojObject parentFromDB; err = db.get(parentId, parentFromDB, found, contactsInfo); MojTestErrCheck(err); MojTestAssert(found); err = parentFromDB.del(MojDb::RevKey, found); MojTestErrCheck(err); MojTestAssert(parent == parentFromDB); // cal cannot read parent err = db.get(parentId, parentFromDB, found, calInfo); MojTestErrExpected(err, MojErrDbAccessDenied); // random can't read either MojDbReq randomInfo(false); err = randomInfo.domain(_T(""random"")); MojTestErrCheck(err); err = db.get(childId, childFromDB, found, randomInfo); MojTestErrExpected(err, MojErrDbAccessDenied); err = db.get(parentId, parentFromDB, found, randomInfo); MojTestErrExpected(err, MojErrDbAccessDenied); // messaging can read parent but not child MojDbReq messagingInfo(false); err = messagingInfo.domain(_T(""com.palm.messaging"")); MojTestErrCheck(err); err = db.get(parentId, parentFromDB, found, messagingInfo); MojTestErrCheck(err); MojTestAssert(found); err = parentFromDB.del(MojDb::RevKey, found); MojTestErrCheck(err); MojTestAssert(parent == parentFromDB); err = db.get(childId, childFromDB, found, messagingInfo); MojTestErrExpected(err, MojErrDbAccessDenied); MojDbQuery q; err = q.from(_T(""ParentKindTest:1"")); MojTestErrCheck(err); MojDbCursor cursor; err = db.find(q, cursor, messagingInfo); MojTestErrCheck(err); MojJsonWriter writer; err = writer.beginArray(); MojTestErrCheck(err); err = cursor.visit(writer); MojTestErrCheck(err); err = writer.endArray(); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); MojObject results; err = results.fromJson(writer.json()); MojTestErrCheck(err); MojUInt32 count = 0; for (MojObject::ConstArrayIterator i = results.arrayBegin(); i != results.arrayEnd(); ++i) { count++; } MojTestAssert(count == 1); MojObject props; err = props.put(_T(""foo""), 5); MojTestErrCheck(err); count = 0; err = db.merge(q, props, count, MojDbFlagNone, messagingInfo); MojTestErrCheck(err); MojTestAssert(count == 1); count = 0; err = db.del(q, count, MojDbFlagNone, messagingInfo); MojTestErrCheck(err); MojTestAssert(count == 1); count = 0; err = db.find(q, cursor, messagingInfo); MojTestErrCheck(err); err = writer.reset(); MojTestErrCheck(err); err = writer.beginArray(); MojTestErrCheck(err); err = cursor.visit(writer); MojTestErrCheck(err); err = writer.endArray(); MojTestErrCheck(err); err = cursor.close(); MojTestErrCheck(err); err = results.fromJson(writer.json()); MojTestErrCheck(err); for (MojObject::ConstArrayIterator i = results.arrayBegin(); i != results.arrayEnd(); ++i) { count++; } MojTestAssert(count == 0); return MojErrNone; } MojErr MojDbKindTest::testFindTokenizedIndex() { const MojChar* const MojTestTokenizedIndexKind = R""({ ""id"": ""KindTest:1"", ""owner"": ""mojodb.admin"", ""indexes"": [{ ""name"": ""foobar"", ""props"": [{ ""name"": ""foo"" }, { ""name"": ""bar"", ""tokenize"": ""all"" }] }] })""; const MojChar* const MojTestData1 = R""({ ""_kind"": ""KindTest:1"", ""foo"" : ""FOO"", ""bar"" : ""KOR,USA,GBR"", ""value"": { ""color"": ""50"" } })""; const MojChar* const MojTestData2 = R""({ ""_kind"": ""KindTest:1"", ""foo"" : ""FOO"", ""bar"" : ""KOR"", ""value"": { ""color"": ""51"" } })""; const MojChar* const MojTestData3 = R""({ ""_kind"": ""KindTest:1"", ""foo"" : ""FOO"", ""bar"" : """", ""value"": { ""color"": ""52"" } })""; const MojChar* const MojTestData4 = R""({ ""_kind"": ""KindTest:1"", ""foo"" : ""FOO"", ""bar"" : """", ""value"": { ""color"": ""53"" } })""; MojDb db; MojErr err = db.open(MojDbTestDir); MojTestErrCheck(err); MojObject kindObj; err = kindObj.fromJson(MojTestTokenizedIndexKind); MojTestErrCheck(err); err = db.putKind(kindObj); MojTestErrCheck(err); MojObject obj1; err = obj1.fromJson(MojTestData1); MojTestErrCheck(err); err = db.put(obj1); MojTestErrCheck(err); MojObject obj2; err = obj2.fromJson(MojTestData2); MojTestErrCheck(err); err = db.put(obj2); MojTestErrCheck(err); MojObject obj3; err = obj3.fromJson(MojTestData3); MojTestErrCheck(err); err = db.put(obj3); MojTestErrCheck(err); MojObject obj4; err = obj4.fromJson(MojTestData4); MojTestErrCheck(err); err = db.put(obj4); MojTestErrCheck(err); MojDbQuery query; err = query.from(_T(""KindTest:1"")); MojTestErrCheck(err); MojString foo; err = foo.assign(""FOO""); MojTestErrCheck(err); err = query.where(_T(""foo""), MojDbQuery::OpEq, foo); MojTestErrCheck(err); MojUInt32 count = 0; MojDbCursor cursor; err = db.find(query, cursor); MojTestErrCheck(err); err = cursor.count(count); MojTestErrCheck(err); MojTestAssert(count == 2); // Data1, Data2 err = cursor.close(); MojTestErrCheck(err); err = db.find(query, cursor); MojTestErrCheck(err); MojJsonWriter writer; err = writer.beginArray(); MojTestErrCheck(err); err = cursor.visit(writer); MojTestErrCheck(err); err = writer.endArray(); MojTestErrCheck(err); MojObject results; err = results.fromJson(writer.json()); MojTestErrCheck(err); count = 0; for (MojObject::ConstArrayIterator i = results.arrayBegin(); i != results.arrayEnd(); ++i) { count++; } MojTestAssert(count == 2); // Data1, Data2 err = cursor.close(); MojTestErrCheck(err); err = db.close(); MojTestErrCheck(err); return MojErrNone; } void MojDbKindTest::cleanup() { (void) MojRmDirRecursive(MojDbTestDir); } ",16134,True,3397.6427324210813,median "// tag::HeaderFullDisplayName[] = ssas.usp_PERSIST_model_json_311_tables_columns_T - P // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--adocuspsteps: :ExistsProperty--antorareferencedlist: :ExistsProperty--antorareferencinglist: :ExistsProperty--exampleusage: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--referencedobjectlist: :ExistsProperty--uspgenerator_usp_id: :ExistsProperty--sql_modules_definition: :ExistsProperty--AntoraParameterList: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] 26064FC7-110B-EC11-8516-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] ssas.usp_PERSIST_model_json_311_tables_columns_T // end::RepoObject_FullDisplayName2[] == SysObject_type // tag::SysObject_type[] P // end::SysObject_type[] == SysObject_type_name // tag::SysObject_type_name[] stored procedure // end::SysObject_type_name[] == SysObject_id // tag::SysObject_id[] 1703013148 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-12-17 19:13:08 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] // end::AntoraIndexList[] == AntoraMeasureDetails // tag::AntoraMeasureDetails[] // end::AntoraMeasureDetails[] == AntoraMeasureDescriptions == AntoraParameterList // tag::AntoraParameterList[] * @execution_instance_guid (uniqueidentifier) * @ssis_execution_id (bigint) * @sub_execution_id (int) * @parent_execution_log_id (bigint) // end::AntoraParameterList[] == AntoraXrefCulturesList // tag::AntoraXrefCulturesList[] * xref:dhw:sqldb:ssas.usp_persist_model_json_311_tables_columns_t.adoc[] - // end::AntoraXrefCulturesList[] == cultures_count // tag::cultures_count[] 1 // end::cultures_count[] == Other tags source: property.RepoObjectProperty_cross As rop_cross === additional_reference_csv // tag::additional_reference_csv[] // end::additional_reference_csv[] === AdocUspSteps // tag::adocuspsteps[] .Steps in [ssas].[usp_PERSIST_model_json_311_tables_columns_T] [cols=""d,15a,d""] |=== |Number|Name (Action, Source, Target)|Parent |500 | *delete persistence target missing in source* * D * [ssas].[model_json_311_tables_columns] * [ssas].[model_json_311_tables_columns_T] .Statement [%collapsible] ===== [source,sql,numbered] ---- DELETE T FROM [ssas].[model_json_311_tables_columns_T] AS T WHERE NOT EXISTS (SELECT 1 FROM [ssas].[model_json_311_tables_columns] AS S WHERE T.[databasename] = S.[databasename] AND T.[tables_name] = S.[tables_name] AND T.[tables_columns_name] = S.[tables_columns_name] ) ---- ===== | |600 | *update changed* * U * [ssas].[model_json_311_tables_columns] * [ssas].[model_json_311_tables_columns_T] .Statement [%collapsible] ===== [source,sql,numbered] ---- UPDATE T SET T.[databasename] = S.[databasename] , T.[tables_name] = S.[tables_name] , T.[tables_columns_name] = S.[tables_columns_name] , T.[RepoObject_guid] = S.[RepoObject_guid] , T.[tables_columns_dataType] = S.[tables_columns_dataType] , T.[tables_columns_description] = S.[tables_columns_description] , T.[tables_columns_description_ja] = S.[tables_columns_description_ja] , T.[tables_columns_displayFolder] = S.[tables_columns_displayFolder] , T.[tables_columns_expression] = S.[tables_columns_expression] , T.[tables_columns_expression_ja] = S.[tables_columns_expression_ja] , T.[tables_columns_formatString] = S.[tables_columns_formatString] , T.[tables_columns_isDataTypeInferred] = S.[tables_columns_isDataTypeInferred] , T.[tables_columns_isHidden] = S.[tables_columns_isHidden] , T.[tables_columns_isKey] = S.[tables_columns_isKey] , T.[tables_columns_isNameInferred] = S.[tables_columns_isNameInferred] , T.[tables_columns_isNullable] = S.[tables_columns_isNullable] , T.[tables_columns_isUnique] = S.[tables_columns_isUnique] , T.[tables_columns_keepUniqueRows] = S.[tables_columns_keepUniqueRows] , T.[tables_columns_sortByColumn] = S.[tables_columns_sortByColumn] , T.[tables_columns_sourceColumn] = S.[tables_columns_sourceColumn] , T.[tables_columns_sourceProviderType] = S.[tables_columns_sourceProviderType] , T.[tables_columns_summarizeBy] = S.[tables_columns_summarizeBy] , T.[tables_columns_type] = S.[tables_columns_type] FROM [ssas].[model_json_311_tables_columns_T] AS T INNER JOIN [ssas].[model_json_311_tables_columns] AS S ON T.[databasename] = S.[databasename] AND T.[tables_name] = S.[tables_name] AND T.[tables_columns_name] = S.[tables_columns_name] WHERE T.[RepoObject_guid] <> S.[RepoObject_guid] OR T.[tables_columns_dataType] <> S.[tables_columns_dataType] OR (S.[tables_columns_dataType] IS NULL AND NOT T.[tables_columns_dataType] IS NULL) OR (NOT S.[tables_columns_dataType] IS NULL AND T.[tables_columns_dataType] IS NULL) OR T.[tables_columns_description] <> S.[tables_columns_description] OR (S.[tables_columns_description] IS NULL AND NOT T.[tables_columns_description] IS NULL) OR (NOT S.[tables_columns_description] IS NULL AND T.[tables_columns_description] IS NULL) OR T.[tables_columns_description_ja] <> S.[tables_columns_description_ja] OR (S.[tables_columns_description_ja] IS NULL AND NOT T.[tables_columns_description_ja] IS NULL) OR (NOT S.[tables_columns_description_ja] IS NULL AND T.[tables_columns_description_ja] IS NULL) OR T.[tables_columns_displayFolder] <> S.[tables_columns_displayFolder] OR (S.[tables_columns_displayFolder] IS NULL AND NOT T.[tables_columns_displayFolder] IS NULL) OR (NOT S.[tables_columns_displayFolder] IS NULL AND T.[tables_columns_displayFolder] IS NULL) OR T.[tables_columns_expression] <> S.[tables_columns_expression] OR (S.[tables_columns_expression] IS NULL AND NOT T.[tables_columns_expression] IS NULL) OR (NOT S.[tables_columns_expression] IS NULL AND T.[tables_columns_expression] IS NULL) OR T.[tables_columns_expression_ja] <> S.[tables_columns_expression_ja] OR (S.[tables_columns_expression_ja] IS NULL AND NOT T.[tables_columns_expression_ja] IS NULL) OR (NOT S.[tables_columns_expression_ja] IS NULL AND T.[tables_columns_expression_ja] IS NULL) OR T.[tables_columns_formatString] <> S.[tables_columns_formatString] OR (S.[tables_columns_formatString] IS NULL AND NOT T.[tables_columns_formatString] IS NULL) OR (NOT S.[tables_columns_formatString] IS NULL AND T.[tables_columns_formatString] IS NULL) OR T.[tables_columns_isDataTypeInferred] <> S.[tables_columns_isDataTypeInferred] OR (S.[tables_columns_isDataTypeInferred] IS NULL AND NOT T.[tables_columns_isDataTypeInferred] IS NULL) OR (NOT S.[tables_columns_isDataTypeInferred] IS NULL AND T.[tables_columns_isDataTypeInferred] IS NULL) OR T.[tables_columns_isHidden] <> S.[tables_columns_isHidden] OR (S.[tables_columns_isHidden] IS NULL AND NOT T.[tables_columns_isHidden] IS NULL) OR (NOT S.[tables_columns_isHidden] IS NULL AND T.[tables_columns_isHidden] IS NULL) OR T.[tables_columns_isKey] <> S.[tables_columns_isKey] OR (S.[tables_columns_isKey] IS NULL AND NOT T.[tables_columns_isKey] IS NULL) OR (NOT S.[tables_columns_isKey] IS NULL AND T.[tables_columns_isKey] IS NULL) OR T.[tables_columns_isNameInferred] <> S.[tables_columns_isNameInferred] OR (S.[tables_columns_isNameInferred] IS NULL AND NOT T.[tables_columns_isNameInferred] IS NULL) OR (NOT S.[tables_columns_isNameInferred] IS NULL AND T.[tables_columns_isNameInferred] IS NULL) OR T.[tables_columns_isNullable] <> S.[tables_columns_isNullable] OR (S.[tables_columns_isNullable] IS NULL AND NOT T.[tables_columns_isNullable] IS NULL) OR (NOT S.[tables_columns_isNullable] IS NULL AND T.[tables_columns_isNullable] IS NULL) OR T.[tables_columns_isUnique] <> S.[tables_columns_isUnique] OR (S.[tables_columns_isUnique] IS NULL AND NOT T.[tables_columns_isUnique] IS NULL) OR (NOT S.[tables_columns_isUnique] IS NULL AND T.[tables_columns_isUnique] IS NULL) OR T.[tables_columns_keepUniqueRows] <> S.[tables_columns_keepUniqueRows] OR (S.[tables_columns_keepUniqueRows] IS NULL AND NOT T.[tables_columns_keepUniqueRows] IS NULL) OR (NOT S.[tables_columns_keepUniqueRows] IS NULL AND T.[tables_columns_keepUniqueRows] IS NULL) OR T.[tables_columns_sortByColumn] <> S.[tables_columns_sortByColumn] OR (S.[tables_columns_sortByColumn] IS NULL AND NOT T.[tables_columns_sortByColumn] IS NULL) OR (NOT S.[tables_columns_sortByColumn] IS NULL AND T.[tables_columns_sortByColumn] IS NULL) OR T.[tables_columns_sourceColumn] <> S.[tables_columns_sourceColumn] OR (S.[tables_columns_sourceColumn] IS NULL AND NOT T.[tables_columns_sourceColumn] IS NULL) OR (NOT S.[tables_columns_sourceColumn] IS NULL AND T.[tables_columns_sourceColumn] IS NULL) OR T.[tables_columns_sourceProviderType] <> S.[tables_columns_sourceProviderType] OR (S.[tables_columns_sourceProviderType] IS NULL AND NOT T.[tables_columns_sourceProviderType] IS NULL) OR (NOT S.[tables_columns_sourceProviderType] IS NULL AND T.[tables_columns_sourceProviderType] IS NULL) OR T.[tables_columns_summarizeBy] <> S.[tables_columns_summarizeBy] OR (S.[tables_columns_summarizeBy] IS NULL AND NOT T.[tables_columns_summarizeBy] IS NULL) OR (NOT S.[tables_columns_summarizeBy] IS NULL AND T.[tables_columns_summarizeBy] IS NULL) OR T.[tables_columns_type] <> S.[tables_columns_type] OR (S.[tables_columns_type] IS NULL AND NOT T.[tables_columns_type] IS NULL) OR (NOT S.[tables_columns_type] IS NULL AND T.[tables_columns_type] IS NULL) ---- ===== | |700 | *insert missing* * I * [ssas].[model_json_311_tables_columns] * [ssas].[model_json_311_tables_columns_T] .Statement [%collapsible] ===== [source,sql,numbered] ---- INSERT INTO [ssas].[model_json_311_tables_columns_T] ( [databasename] , [tables_name] , [tables_columns_name] , [RepoObject_guid] , [tables_columns_dataType] , [tables_columns_description] , [tables_columns_description_ja] , [tables_columns_displayFolder] , [tables_columns_expression] , [tables_columns_expression_ja] , [tables_columns_formatString] , [tables_columns_isDataTypeInferred] , [tables_columns_isHidden] , [tables_columns_isKey] , [tables_columns_isNameInferred] , [tables_columns_isNullable] , [tables_columns_isUnique] , [tables_columns_keepUniqueRows] , [tables_columns_sortByColumn] , [tables_columns_sourceColumn] , [tables_columns_sourceProviderType] , [tables_columns_summarizeBy] , [tables_columns_type] ) SELECT [databasename] , [tables_name] , [tables_columns_name] , [RepoObject_guid] , [tables_columns_dataType] , [tables_columns_description] , [tables_columns_description_ja] , [tables_columns_displayFolder] , [tables_columns_expression] , [tables_columns_expression_ja] , [tables_columns_formatString] , [tables_columns_isDataTypeInferred] , [tables_columns_isHidden] , [tables_columns_isKey] , [tables_columns_isNameInferred] , [tables_columns_isNullable] , [tables_columns_isUnique] , [tables_columns_keepUniqueRows] , [tables_columns_sortByColumn] , [tables_columns_sourceColumn] , [tables_columns_sourceProviderType] , [tables_columns_summarizeBy] , [tables_columns_type] FROM [ssas].[model_json_311_tables_columns] AS S WHERE NOT EXISTS (SELECT 1 FROM [ssas].[model_json_311_tables_columns_T] AS T WHERE T.[databasename] = S.[databasename] AND T.[tables_name] = S.[tables_name] AND T.[tables_columns_name] = S.[tables_columns_name] ) ---- ===== | |=== // end::adocuspsteps[] === AntoraReferencedList // tag::antorareferencedlist[] * xref:dhw:sqldb:logs.usp_executionlog_insert.adoc[] * xref:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[] * xref:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:repo.usp_sync_guid_ssas.adoc[] // end::antorareferencinglist[] === Description // tag::description[] // end::description[] === exampleUsage // tag::exampleusage[] EXEC [ssas].[usp_PERSIST_model_json_311_tables_columns_T] // end::exampleusage[] === exampleUsage_2 // tag::exampleusage_2[] // end::exampleusage_2[] === exampleUsage_3 // tag::exampleusage_3[] // end::exampleusage_3[] === exampleUsage_4 // tag::exampleusage_4[] // end::exampleusage_4[] === exampleUsage_5 // tag::exampleusage_5[] // end::exampleusage_5[] === exampleWrong_Usage // tag::examplewrong_usage[] // end::examplewrong_usage[] === has_execution_plan_issue // tag::has_execution_plan_issue[] // end::has_execution_plan_issue[] === has_get_referenced_issue // tag::has_get_referenced_issue[] // end::has_get_referenced_issue[] === has_history // tag::has_history[] // end::has_history[] === has_history_columns // tag::has_history_columns[] // end::has_history_columns[] === InheritanceType // tag::inheritancetype[] // end::inheritancetype[] === is_persistence // tag::is_persistence[] // end::is_persistence[] === is_persistence_check_duplicate_per_pk // tag::is_persistence_check_duplicate_per_pk[] // end::is_persistence_check_duplicate_per_pk[] === is_persistence_check_for_empty_source // tag::is_persistence_check_for_empty_source[] // end::is_persistence_check_for_empty_source[] === is_persistence_delete_changed // tag::is_persistence_delete_changed[] // end::is_persistence_delete_changed[] === is_persistence_delete_missing // tag::is_persistence_delete_missing[] // end::is_persistence_delete_missing[] === is_persistence_insert // tag::is_persistence_insert[] // end::is_persistence_insert[] === is_persistence_truncate // tag::is_persistence_truncate[] // end::is_persistence_truncate[] === is_persistence_update_changed // tag::is_persistence_update_changed[] // end::is_persistence_update_changed[] === is_repo_managed // tag::is_repo_managed[] 0 // end::is_repo_managed[] === is_ssas // tag::is_ssas[] 0 // end::is_ssas[] === microsoft_database_tools_support // tag::microsoft_database_tools_support[] // end::microsoft_database_tools_support[] === MS_Description // tag::ms_description[] // end::ms_description[] === persistence_source_RepoObject_fullname // tag::persistence_source_repoobject_fullname[] // end::persistence_source_repoobject_fullname[] === persistence_source_RepoObject_fullname2 // tag::persistence_source_repoobject_fullname2[] // end::persistence_source_repoobject_fullname2[] === persistence_source_RepoObject_guid // tag::persistence_source_repoobject_guid[] // end::persistence_source_repoobject_guid[] === persistence_source_RepoObject_xref // tag::persistence_source_repoobject_xref[] // end::persistence_source_repoobject_xref[] === pk_index_guid // tag::pk_index_guid[] // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] * [logs].[usp_ExecutionLog_insert] * [ssas].[model_json_311_tables_columns] * [ssas].[model_json_311_tables_columns_T] // end::referencedobjectlist[] === usp_persistence_RepoObject_guid // tag::usp_persistence_repoobject_guid[] // end::usp_persistence_repoobject_guid[] === UspExamples // tag::uspexamples[] // end::uspexamples[] === uspgenerator_usp_id // tag::uspgenerator_usp_id[] 84 // end::uspgenerator_usp_id[] === UspParameters // tag::uspparameters[] // end::uspparameters[] == Boolean Attributes source: property.RepoObjectProperty WHERE property_int = 1 // tag::boolean_attributes[] // end::boolean_attributes[] == PlantUML diagrams === PlantUML Entity // tag::puml_entity[] [plantuml, entity-{docname}, svg, subs=macros] .... 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:ssas.usp_persist_model_json_311_tables_columns_t.adoc[]"" as ssas.usp_PERSIST_model_json_311_tables_columns_T << P >> { -- } .... // end::puml_entity[] === PlantUML Entity 1 1 FK // tag::puml_entity_1_1_fk[] [plantuml, entity_1_1_fk-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_fk[] === PlantUML 1 1 ObjectRef // tag::puml_entity_1_1_objectref[] [plantuml, entity_1_1_objectref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:logs.usp_executionlog_insert.adoc[]"" as logs.usp_ExecutionLog_insert << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_sync_guid_ssas.adoc[]"" as repo.usp_sync_guid_ssas << P >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[]"" as ssas.model_json_311_tables_columns << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[]"" as ssas.model_json_311_tables_columns_T << U >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.usp_persist_model_json_311_tables_columns_t.adoc[]"" as ssas.usp_PERSIST_model_json_311_tables_columns_T << P >> { -- } logs.usp_ExecutionLog_insert <.. ssas.usp_PERSIST_model_json_311_tables_columns_T ssas.model_json_311_tables_columns <.. ssas.usp_PERSIST_model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. ssas.usp_PERSIST_model_json_311_tables_columns_T ssas.usp_PERSIST_model_json_311_tables_columns_T <.. repo.usp_sync_guid_ssas footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_objectref[] === PlantUML 30 0 ObjectRef // tag::puml_entity_30_0_objectref[] [plantuml, entity_30_0_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:logs.executionlog.adoc[]"" as logs.ExecutionLog << U >> { - **id** : (bigint) -- } entity ""puml-link:dhw:sqldb:logs.usp_executionlog_insert.adoc[]"" as logs.usp_ExecutionLog_insert << P >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json.adoc[]"" as ssas.model_json << U >> { - **databasename** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_10.adoc[]"" as ssas.model_json_10 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_20.adoc[]"" as ssas.model_json_20 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables.adoc[]"" as ssas.model_json_31_tables << V >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables_t.adoc[]"" as ssas.model_json_31_tables_T << U >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[]"" as ssas.model_json_311_tables_columns << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[]"" as ssas.model_json_311_tables_columns_T << U >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.usp_persist_model_json_311_tables_columns_t.adoc[]"" as ssas.usp_PERSIST_model_json_311_tables_columns_T << P >> { -- } logs.ExecutionLog <.. logs.usp_ExecutionLog_insert logs.usp_ExecutionLog_insert <.. ssas.usp_PERSIST_model_json_311_tables_columns_T ssas.model_json <.. ssas.model_json_10 ssas.model_json_10 <.. ssas.model_json_20 ssas.model_json_20 <.. ssas.model_json_31_tables ssas.model_json_31_tables <.. ssas.model_json_31_tables_T ssas.model_json_31_tables_T <.. ssas.model_json_311_tables_columns ssas.model_json_311_tables_columns <.. ssas.usp_PERSIST_model_json_311_tables_columns_T ssas.model_json_311_tables_columns <.. ssas.model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. ssas.usp_PERSIST_model_json_311_tables_columns_T footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_30_0_objectref[] === PlantUML 0 30 ObjectRef // tag::puml_entity_0_30_objectref[] [plantuml, entity_0_30_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:repo.usp_main.adoc[]"" as repo.usp_main << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_sync_guid_ssas.adoc[]"" as repo.usp_sync_guid_ssas << P >> { -- } entity ""puml-link:dhw:sqldb:ssas.usp_persist_model_json_311_tables_columns_t.adoc[]"" as ssas.usp_PERSIST_model_json_311_tables_columns_T << P >> { -- } repo.usp_sync_guid_ssas <.. repo.usp_main ssas.usp_PERSIST_model_json_311_tables_columns_T <.. repo.usp_sync_guid_ssas footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_0_30_objectref[] === PlantUML 1 1 ColumnRef // tag::puml_entity_1_1_colref[] [plantuml, entity_1_1_colref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<

> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:logs.usp_executionlog_insert.adoc[]"" as logs.usp_ExecutionLog_insert << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_sync_guid_ssas.adoc[]"" as repo.usp_sync_guid_ssas << P >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[]"" as ssas.model_json_311_tables_columns << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) - RepoObject_guid : (uniqueidentifier) tables_columns_dataType : (nvarchar(500)) tables_columns_description : (nvarchar(max)) tables_columns_description_ja : (nvarchar(max)) tables_columns_displayFolder : (nvarchar(500)) tables_columns_expression : (nvarchar(max)) tables_columns_expression_ja : (nvarchar(max)) tables_columns_formatString : (nvarchar(500)) tables_columns_isDataTypeInferred : (bit) tables_columns_isHidden : (bit) tables_columns_isKey : (bit) tables_columns_isNameInferred : (bit) tables_columns_isNullable : (bit) tables_columns_isUnique : (bit) tables_columns_keepUniqueRows : (bit) tables_columns_sortByColumn : (nvarchar(500)) tables_columns_sourceColumn : (nvarchar(500)) tables_columns_sourceProviderType : (nvarchar(500)) tables_columns_summarizeBy : (nvarchar(500)) tables_columns_type : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[]"" as ssas.model_json_311_tables_columns_T << U >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) - RepoObject_guid : (uniqueidentifier) - RepoObjectColumn_guid : (uniqueidentifier) tables_columns_dataType : (nvarchar(500)) tables_columns_description : (nvarchar(max)) tables_columns_description_ja : (nvarchar(max)) tables_columns_displayFolder : (nvarchar(500)) tables_columns_expression : (nvarchar(max)) tables_columns_expression_ja : (nvarchar(max)) tables_columns_formatString : (nvarchar(500)) tables_columns_isDataTypeInferred : (bit) tables_columns_isHidden : (bit) tables_columns_isKey : (bit) tables_columns_isNameInferred : (bit) tables_columns_isNullable : (bit) tables_columns_isUnique : (bit) tables_columns_keepUniqueRows : (bit) tables_columns_sortByColumn : (nvarchar(500)) tables_columns_sourceColumn : (nvarchar(500)) tables_columns_sourceProviderType : (nvarchar(500)) tables_columns_summarizeBy : (nvarchar(500)) tables_columns_type : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.usp_persist_model_json_311_tables_columns_t.adoc[]"" as ssas.usp_PERSIST_model_json_311_tables_columns_T << P >> { -- } logs.usp_ExecutionLog_insert <.. ssas.usp_PERSIST_model_json_311_tables_columns_T ssas.model_json_311_tables_columns <.. ssas.usp_PERSIST_model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. ssas.usp_PERSIST_model_json_311_tables_columns_T ssas.usp_PERSIST_model_json_311_tables_columns_T <.. repo.usp_sync_guid_ssas footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_colref[] == sql_modules_definition // tag::sql_modules_definition[] [%collapsible] ======= [source,sql,numbered,indent=0] ---- /* code of this procedure is managed in the dhw repository. Do not modify manually. Use [uspgenerator].[GeneratorUsp], [uspgenerator].[GeneratorUspParameter], [uspgenerator].[GeneratorUspStep], [uspgenerator].[GeneratorUsp_SqlUsp] */ CREATE PROCEDURE [ssas].[usp_PERSIST_model_json_311_tables_columns_T] ----keep the code between logging parameters and ""START"" unchanged! ---- parameters, used for logging; you don't need to care about them, but you can use them, wenn calling from SSIS or in your workflow to log the context of the procedure call @execution_instance_guid UNIQUEIDENTIFIER = NULL --SSIS system variable ExecutionInstanceGUID could be used, any other unique guid is also fine. If NULL, then NEWID() is used to create one , @ssis_execution_id BIGINT = NULL --only SSIS system variable ServerExecutionID should be used, or any other consistent number system, do not mix different number systems , @sub_execution_id INT = NULL --in case you log some sub_executions, for example in SSIS loops or sub packages , @parent_execution_log_id BIGINT = NULL --in case a sup procedure is called, the @current_execution_log_id of the parent procedure should be propagated here. It allowes call stack analyzing AS BEGIN DECLARE -- @current_execution_log_id BIGINT --this variable should be filled only once per procedure call, it contains the first logging call for the step 'start'. , @current_execution_guid UNIQUEIDENTIFIER = NEWID() --a unique guid for any procedure call. It should be propagated to sub procedures using ""@parent_execution_log_id = @current_execution_log_id"" , @source_object NVARCHAR(261) = NULL --use it like '[schema].[object]', this allows data flow vizualizatiuon (include square brackets) , @target_object NVARCHAR(261) = NULL --use it like '[schema].[object]', this allows data flow vizualizatiuon (include square brackets) , @proc_id INT = @@procid , @proc_schema_name NVARCHAR(128) = OBJECT_SCHEMA_NAME(@@procid) --schema ande name of the current procedure should be automatically logged , @proc_name NVARCHAR(128) = OBJECT_NAME(@@procid) --schema ande name of the current procedure should be automatically logged , @event_info NVARCHAR(MAX) , @step_id INT = 0 , @step_name NVARCHAR(1000) = NULL , @rows INT --[event_info] get's only the information about the ""outer"" calling process --wenn the procedure calls sub procedures, the [event_info] will not change SET @event_info = ( SELECT TOP 1 [event_info] FROM sys.dm_exec_input_buffer(@@spid, CURRENT_REQUEST_ID()) ORDER BY [event_info] ) IF @execution_instance_guid IS NULL SET @execution_instance_guid = NEWID(); -- --SET @rows = @@ROWCOUNT; SET @step_id = @step_id + 1 SET @step_name = 'start' SET @source_object = NULL SET @target_object = NULL EXEC logs.usp_ExecutionLog_insert --these parameters should be the same for all logging execution @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info --the following parameters are individual for each call , @step_id = @step_id --@step_id should be incremented before each call , @step_name = @step_name --assign individual step names for each call --only the ""start"" step should return the log id into @current_execution_log_id --all other calls should not overwrite @current_execution_log_id , @execution_log_id = @current_execution_log_id OUTPUT ----you can log the content of your own parameters, do this only in the start-step ----data type is sql_variant -- PRINT '[ssas].[usp_PERSIST_model_json_311_tables_columns_T]' --keep the code between logging parameters and ""START"" unchanged! -- ----START -- ----- start here with your own code -- /*{""ReportUspStep"":[{""Number"":500,""Name"":""delete persistence target missing in source"",""has_logging"":1,""is_condition"":0,""is_inactive"":0,""is_SubProcedure"":0,""log_source_object"":""[ssas].[model_json_311_tables_columns]"",""log_target_object"":""[ssas].[model_json_311_tables_columns_T]"",""log_flag_InsertUpdateDelete"":""D""}]}*/ PRINT CONCAT('usp_id;Number;Parent_Number: ',84,';',500,';',NULL); DELETE T FROM [ssas].[model_json_311_tables_columns_T] AS T WHERE NOT EXISTS (SELECT 1 FROM [ssas].[model_json_311_tables_columns] AS S WHERE T.[databasename] = S.[databasename] AND T.[tables_name] = S.[tables_name] AND T.[tables_columns_name] = S.[tables_columns_name] ) -- Logging START -- SET @rows = @@ROWCOUNT SET @step_id = @step_id + 1 SET @step_name = 'delete persistence target missing in source' SET @source_object = '[ssas].[model_json_311_tables_columns]' SET @target_object = '[ssas].[model_json_311_tables_columns_T]' EXEC logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object , @deleted = @rows -- Logging END -- /*{""ReportUspStep"":[{""Number"":600,""Name"":""update changed"",""has_logging"":1,""is_condition"":0,""is_inactive"":0,""is_SubProcedure"":0,""log_source_object"":""[ssas].[model_json_311_tables_columns]"",""log_target_object"":""[ssas].[model_json_311_tables_columns_T]"",""log_flag_InsertUpdateDelete"":""U""}]}*/ PRINT CONCAT('usp_id;Number;Parent_Number: ',84,';',600,';',NULL); UPDATE T SET T.[databasename] = S.[databasename] , T.[tables_name] = S.[tables_name] , T.[tables_columns_name] = S.[tables_columns_name] , T.[RepoObject_guid] = S.[RepoObject_guid] , T.[tables_columns_dataType] = S.[tables_columns_dataType] , T.[tables_columns_description] = S.[tables_columns_description] , T.[tables_columns_description_ja] = S.[tables_columns_description_ja] , T.[tables_columns_displayFolder] = S.[tables_columns_displayFolder] , T.[tables_columns_expression] = S.[tables_columns_expression] , T.[tables_columns_expression_ja] = S.[tables_columns_expression_ja] , T.[tables_columns_formatString] = S.[tables_columns_formatString] , T.[tables_columns_isDataTypeInferred] = S.[tables_columns_isDataTypeInferred] , T.[tables_columns_isHidden] = S.[tables_columns_isHidden] , T.[tables_columns_isKey] = S.[tables_columns_isKey] , T.[tables_columns_isNameInferred] = S.[tables_columns_isNameInferred] , T.[tables_columns_isNullable] = S.[tables_columns_isNullable] , T.[tables_columns_isUnique] = S.[tables_columns_isUnique] , T.[tables_columns_keepUniqueRows] = S.[tables_columns_keepUniqueRows] , T.[tables_columns_sortByColumn] = S.[tables_columns_sortByColumn] , T.[tables_columns_sourceColumn] = S.[tables_columns_sourceColumn] , T.[tables_columns_sourceProviderType] = S.[tables_columns_sourceProviderType] , T.[tables_columns_summarizeBy] = S.[tables_columns_summarizeBy] , T.[tables_columns_type] = S.[tables_columns_type] FROM [ssas].[model_json_311_tables_columns_T] AS T INNER JOIN [ssas].[model_json_311_tables_columns] AS S ON T.[databasename] = S.[databasename] AND T.[tables_name] = S.[tables_name] AND T.[tables_columns_name] = S.[tables_columns_name] WHERE T.[RepoObject_guid] <> S.[RepoObject_guid] OR T.[tables_columns_dataType] <> S.[tables_columns_dataType] OR (S.[tables_columns_dataType] IS NULL AND NOT T.[tables_columns_dataType] IS NULL) OR (NOT S.[tables_columns_dataType] IS NULL AND T.[tables_columns_dataType] IS NULL) OR T.[tables_columns_description] <> S.[tables_columns_description] OR (S.[tables_columns_description] IS NULL AND NOT T.[tables_columns_description] IS NULL) OR (NOT S.[tables_columns_description] IS NULL AND T.[tables_columns_description] IS NULL) OR T.[tables_columns_description_ja] <> S.[tables_columns_description_ja] OR (S.[tables_columns_description_ja] IS NULL AND NOT T.[tables_columns_description_ja] IS NULL) OR (NOT S.[tables_columns_description_ja] IS NULL AND T.[tables_columns_description_ja] IS NULL) OR T.[tables_columns_displayFolder] <> S.[tables_columns_displayFolder] OR (S.[tables_columns_displayFolder] IS NULL AND NOT T.[tables_columns_displayFolder] IS NULL) OR (NOT S.[tables_columns_displayFolder] IS NULL AND T.[tables_columns_displayFolder] IS NULL) OR T.[tables_columns_expression] <> S.[tables_columns_expression] OR (S.[tables_columns_expression] IS NULL AND NOT T.[tables_columns_expression] IS NULL) OR (NOT S.[tables_columns_expression] IS NULL AND T.[tables_columns_expression] IS NULL) OR T.[tables_columns_expression_ja] <> S.[tables_columns_expression_ja] OR (S.[tables_columns_expression_ja] IS NULL AND NOT T.[tables_columns_expression_ja] IS NULL) OR (NOT S.[tables_columns_expression_ja] IS NULL AND T.[tables_columns_expression_ja] IS NULL) OR T.[tables_columns_formatString] <> S.[tables_columns_formatString] OR (S.[tables_columns_formatString] IS NULL AND NOT T.[tables_columns_formatString] IS NULL) OR (NOT S.[tables_columns_formatString] IS NULL AND T.[tables_columns_formatString] IS NULL) OR T.[tables_columns_isDataTypeInferred] <> S.[tables_columns_isDataTypeInferred] OR (S.[tables_columns_isDataTypeInferred] IS NULL AND NOT T.[tables_columns_isDataTypeInferred] IS NULL) OR (NOT S.[tables_columns_isDataTypeInferred] IS NULL AND T.[tables_columns_isDataTypeInferred] IS NULL) OR T.[tables_columns_isHidden] <> S.[tables_columns_isHidden] OR (S.[tables_columns_isHidden] IS NULL AND NOT T.[tables_columns_isHidden] IS NULL) OR (NOT S.[tables_columns_isHidden] IS NULL AND T.[tables_columns_isHidden] IS NULL) OR T.[tables_columns_isKey] <> S.[tables_columns_isKey] OR (S.[tables_columns_isKey] IS NULL AND NOT T.[tables_columns_isKey] IS NULL) OR (NOT S.[tables_columns_isKey] IS NULL AND T.[tables_columns_isKey] IS NULL) OR T.[tables_columns_isNameInferred] <> S.[tables_columns_isNameInferred] OR (S.[tables_columns_isNameInferred] IS NULL AND NOT T.[tables_columns_isNameInferred] IS NULL) OR (NOT S.[tables_columns_isNameInferred] IS NULL AND T.[tables_columns_isNameInferred] IS NULL) OR T.[tables_columns_isNullable] <> S.[tables_columns_isNullable] OR (S.[tables_columns_isNullable] IS NULL AND NOT T.[tables_columns_isNullable] IS NULL) OR (NOT S.[tables_columns_isNullable] IS NULL AND T.[tables_columns_isNullable] IS NULL) OR T.[tables_columns_isUnique] <> S.[tables_columns_isUnique] OR (S.[tables_columns_isUnique] IS NULL AND NOT T.[tables_columns_isUnique] IS NULL) OR (NOT S.[tables_columns_isUnique] IS NULL AND T.[tables_columns_isUnique] IS NULL) OR T.[tables_columns_keepUniqueRows] <> S.[tables_columns_keepUniqueRows] OR (S.[tables_columns_keepUniqueRows] IS NULL AND NOT T.[tables_columns_keepUniqueRows] IS NULL) OR (NOT S.[tables_columns_keepUniqueRows] IS NULL AND T.[tables_columns_keepUniqueRows] IS NULL) OR T.[tables_columns_sortByColumn] <> S.[tables_columns_sortByColumn] OR (S.[tables_columns_sortByColumn] IS NULL AND NOT T.[tables_columns_sortByColumn] IS NULL) OR (NOT S.[tables_columns_sortByColumn] IS NULL AND T.[tables_columns_sortByColumn] IS NULL) OR T.[tables_columns_sourceColumn] <> S.[tables_columns_sourceColumn] OR (S.[tables_columns_sourceColumn] IS NULL AND NOT T.[tables_columns_sourceColumn] IS NULL) OR (NOT S.[tables_columns_sourceColumn] IS NULL AND T.[tables_columns_sourceColumn] IS NULL) OR T.[tables_columns_sourceProviderType] <> S.[tables_columns_sourceProviderType] OR (S.[tables_columns_sourceProviderType] IS NULL AND NOT T.[tables_columns_sourceProviderType] IS NULL) OR (NOT S.[tables_columns_sourceProviderType] IS NULL AND T.[tables_columns_sourceProviderType] IS NULL) OR T.[tables_columns_summarizeBy] <> S.[tables_columns_summarizeBy] OR (S.[tables_columns_summarizeBy] IS NULL AND NOT T.[tables_columns_summarizeBy] IS NULL) OR (NOT S.[tables_columns_summarizeBy] IS NULL AND T.[tables_columns_summarizeBy] IS NULL) OR T.[tables_columns_type] <> S.[tables_columns_type] OR (S.[tables_columns_type] IS NULL AND NOT T.[tables_columns_type] IS NULL) OR (NOT S.[tables_columns_type] IS NULL AND T.[tables_columns_type] IS NULL) -- Logging START -- SET @rows = @@ROWCOUNT SET @step_id = @step_id + 1 SET @step_name = 'update changed' SET @source_object = '[ssas].[model_json_311_tables_columns]' SET @target_object = '[ssas].[model_json_311_tables_columns_T]' EXEC logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object , @updated = @rows -- Logging END -- /*{""ReportUspStep"":[{""Number"":700,""Name"":""insert missing"",""has_logging"":1,""is_condition"":0,""is_inactive"":0,""is_SubProcedure"":0,""log_source_object"":""[ssas].[model_json_311_tables_columns]"",""log_target_object"":""[ssas].[model_json_311_tables_columns_T]"",""log_flag_InsertUpdateDelete"":""I""}]}*/ PRINT CONCAT('usp_id;Number;Parent_Number: ',84,';',700,';',NULL); INSERT INTO [ssas].[model_json_311_tables_columns_T] ( [databasename] , [tables_name] , [tables_columns_name] , [RepoObject_guid] , [tables_columns_dataType] , [tables_columns_description] , [tables_columns_description_ja] , [tables_columns_displayFolder] , [tables_columns_expression] , [tables_columns_expression_ja] , [tables_columns_formatString] , [tables_columns_isDataTypeInferred] , [tables_columns_isHidden] , [tables_columns_isKey] , [tables_columns_isNameInferred] , [tables_columns_isNullable] , [tables_columns_isUnique] , [tables_columns_keepUniqueRows] , [tables_columns_sortByColumn] , [tables_columns_sourceColumn] , [tables_columns_sourceProviderType] , [tables_columns_summarizeBy] , [tables_columns_type] ) SELECT [databasename] , [tables_name] , [tables_columns_name] , [RepoObject_guid] , [tables_columns_dataType] , [tables_columns_description] , [tables_columns_description_ja] , [tables_columns_displayFolder] , [tables_columns_expression] , [tables_columns_expression_ja] , [tables_columns_formatString] , [tables_columns_isDataTypeInferred] , [tables_columns_isHidden] , [tables_columns_isKey] , [tables_columns_isNameInferred] , [tables_columns_isNullable] , [tables_columns_isUnique] , [tables_columns_keepUniqueRows] , [tables_columns_sortByColumn] , [tables_columns_sourceColumn] , [tables_columns_sourceProviderType] , [tables_columns_summarizeBy] , [tables_columns_type] FROM [ssas].[model_json_311_tables_columns] AS S WHERE NOT EXISTS (SELECT 1 FROM [ssas].[model_json_311_tables_columns_T] AS T WHERE T.[databasename] = S.[databasename] AND T.[tables_name] = S.[tables_name] AND T.[tables_columns_name] = S.[tables_columns_name] ) -- Logging START -- SET @rows = @@ROWCOUNT SET @step_id = @step_id + 1 SET @step_name = 'insert missing' SET @source_object = '[ssas].[model_json_311_tables_columns]' SET @target_object = '[ssas].[model_json_311_tables_columns_T]' EXEC logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object , @inserted = @rows -- Logging END -- -- --finish your own code here --keep the code between ""END"" and the end of the procedure unchanged! -- --END -- --SET @rows = @@ROWCOUNT SET @step_id = @step_id + 1 SET @step_name = 'end' SET @source_object = NULL SET @target_object = NULL EXEC logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object END ---- ======= // end::sql_modules_definition[] ",12407,True,2592.2791825359805,median "= AsciidoctorJ: Java bindings for Asciidoctor Alex Soto ; Dan Allen // Settings: :compat-mode!: :page-layout: base :toc: macro :toclevels: 2 ifdef::awestruct[:toclevels: 1] :experimental: //:table-caption!: :source-language: java :language: {source-language} ifdef::env-github[:badges:] // Aliases: :dagger: † // URIs: ifdef::awestruct[:uri-docs: link:/docs] ifndef::awestruct[:uri-docs: http://asciidoctor.org/docs] :uri-asciidoctor: {uri-docs}/what-is-asciidoctor :uri-repo: https://github.com/asciidoctor/asciidoctorj :uri-issues: {uri-repo}/issues :uri-discuss: http://discuss.asciidoctor.org :artifact-version: 2.1.0 :uri-maven-artifact-query: http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.asciidoctor%22%20AND%20a%3A%22asciidoctorj%22%20AND%20v%3A%22{artifact-version}%22 :uri-maven-artifact-detail: http://search.maven.org/#artifactdetails%7Corg.asciidoctor%7Casciidoctorj%7C{artifact-version}%7Cjar :uri-maven-artifact-file: http://search.maven.org/remotecontent?filepath=org/asciidoctor/asciidoctorj/{artifact-version}/asciidoctorj-{artifact-version} :uri-maven-artifact-api-query: http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.asciidoctor%22%20AND%20a%3A%22asciidoctorj-api%22%20AND%20v%3A%22{artifact-version}%22 :uri-maven-artifact-api-detail: http://search.maven.org/#artifactdetails%7Corg.asciidoctor%7Casciidoctorj-api%7C{artifact-version}%7Cjar :uri-maven-artifact-api-file: http://search.maven.org/remotecontent?filepath=org/asciidoctor/asciidoctorj-api/{artifact-version}/asciidoctorj-api-{artifact-version} :uri-bintray-artifact-query: https://bintray.com/asciidoctor/maven/asciidoctorj/view/general :uri-bintray-artifact-detail: https://bintray.com/asciidoctor/maven/asciidoctorj/{artifact-version}/view :uri-bintray-artifact-file: http://dl.bintray.com/asciidoctor/maven/org/asciidoctor/asciidoctorj/{artifact-version}/asciidoctorj-{artifact-version} :uri-bintray-artifact-api-query: https://bintray.com/asciidoctor/maven/asciidoctorj-api/view/general :uri-bintray-artifact-api-detail: https://bintray.com/asciidoctor/maven/asciidoctorj-api/{artifact-version}/view :uri-bintray-artifact-api-file: http://dl.bintray.com/asciidoctor/maven/org/asciidoctor/asciidoctorj-api/{artifact-version}/asciidoctorj-api-{artifact-version} :uri-jruby-startup: http://github.com/jruby/jruby/wiki/Improving-startup-time :uri-maven-guide: {uri-docs}/install-and-use-asciidoctor-maven-plugin :uri-gradle-guide: {uri-docs}/install-and-use-asciidoctor-gradle-plugin :uri-tilt: https://github.com/rtomayko/tilt :uri-font-awesome: http://fortawesome.github.io/Font-Awesome :uri-gradle: https://gradle.org :uri-chocolatey: https://chocolatey.org {uri-repo}[AsciidoctorJ] is the official library for running {uri-asciidoctor}[Asciidoctor] on the JVM. Using AsciidoctorJ, you can convert AsciiDoc content or analyze the structure of a parsed AsciiDoc document from Java and other JVM languages. ifdef::badges[] image:https://img.shields.io/travis/asciidoctor/asciidoctorj/master.svg[Build Status (Travis CI), link=https://travis-ci.org/asciidoctor/asciidoctorj] image:https://ci.appveyor.com/api/projects/status/syxrlv047esal4n0/branch/master?svg=true[Build Status (AppVeyor), link=https://ci.appveyor.com/project/asciidoctor/asciidoctorj] image:https://img.shields.io/badge/javadoc.io-1.6.0-blue.svg[Javadoc, link=http://www.javadoc.io/doc/org.asciidoctor/asciidoctorj/1.6.0-alpha.1] endif::[] ifdef::awestruct,env-browser[] toc::[] endif::[] == Distribution AsciidoctorJ is published to Maven Central and Bintray. The artifact information can be found in the tables below. [cols=""2,2,^2,4""] .Artifact information for AsciidoctorJ in jCenter (Bintray) |=== |Group Id |Artifact Id |Version |Download |org.asciidoctor |{uri-bintray-artifact-query}[asciidoctorj] |{uri-bintray-artifact-detail}[{artifact-version}] |{uri-bintray-artifact-file}.pom[pom] {uri-bintray-artifact-file}.jar[jar] {uri-bintray-artifact-file}-javadoc.jar[javadoc (jar)] {uri-bintray-artifact-file}-sources.jar[sources (jar)] {uri-bintray-artifact-file}-bin.zip[distribution (zip)] |org.asciidoctor |{uri-bintray-artifact-api-query}[asciidoctorj-api] |{uri-bintray-artifact-api-detail}[{artifact-version}] |{uri-bintray-artifact-api-file}.pom[pom] {uri-bintray-artifact-api-file}.jar[jar] {uri-bintray-artifact-api-file}-javadoc.jar[javadoc (jar)] {uri-bintray-artifact-api-file}-sources.jar[sources (jar)] |org.asciidoctor |asciidoctorj-epub3 |1.5.0-alpha.9 |{empty} |org.asciidoctor |asciidoctorj-pdf |1.5.0-alpha.18 |{empty} |=== [cols=""2,2,^2,4""] .Artifact information for AsciidoctorJ in Maven Central |=== |Group Id |Artifact Id |Version |Download |org.asciidoctor |{uri-maven-artifact-query}[asciidoctorj] |{uri-maven-artifact-detail}[{artifact-version}] |{uri-maven-artifact-file}.pom[pom] {uri-maven-artifact-file}.jar[jar] {uri-maven-artifact-file}-javadoc.jar[javadoc (jar)] {uri-maven-artifact-file}-sources.jar[sources (jar)] {uri-maven-artifact-file}-bin.zip[distribution (zip)] |org.asciidoctor |{uri-maven-artifact-api-query}[asciidoctorj-api] |{uri-maven-artifact-api-detail}[{artifact-version}] |{uri-maven-artifact-api-file}.pom[pom] {uri-maven-artifact-api-file}.jar[jar] {uri-maven-artifact-api-file}-javadoc.jar[javadoc (jar)] {uri-maven-artifact-api-file}-sources.jar[sources (jar)] |org.asciidoctor |asciidoctorj-epub3 |1.5.0-alpha.9 |{empty} |org.asciidoctor |asciidoctorj-pdf |1.5.0-alpha.18 |{empty} |=== CAUTION: The artifactId changed to `asciidoctorj` starting in 1.5.0. == Installation To start using AsciidoctorJ, you need to add the required dependency to the dependency management system of your choice, Maven, Gradle or Apache Ivy. If you don't use a Dependency Management system please check the dependency graph and add all jars in it to your classpath. // SW: Need functional tests for a java maven project and a java gradle project [source,xml] [subs=""specialcharacters,attributes,callouts""] .Declaring the dependency in a Maven build file (i.e., pom.xml) ---- org.asciidoctor asciidoctorj {artifact-version} ---- [source,groovy] [subs=""specialcharacters,attributes,callouts""] .Declaring the dependency in a Gradle build file (e.g., build.gradle) ---- dependencies { compile 'org.asciidoctor:asciidoctorj:{artifact-version}' } ---- [source,scala] [subs=""specialcharacters,attributes,callouts""] .Declaring the dependency in an SBT build file (e.g., build.sbt) ---- libraryDependencies += ""org.asciidoctor"" % ""asciidoctorj"" % ""{artifact-version}"" // <1> ---- <1> Specifying the version of AsciidoctorJ implicitly selects the version of Asciidoctor [source,clojure] [subs=""specialcharacters,attributes,callouts""] .Declaring the dependency in a Leiningen build file (e.g., project.clj) ---- :dependencies [[org.asciidoctor/asciidoctorj ""{artifact-version}""]] ---- // DA: Should we mention how to download if you just want to use the asciidoctorj command? [TIP] ==== In addition to using AsciidoctorJ directly, you can invoke it as part of your build using the Maven or Gradle plugin. - {uri-maven-guide}[How to Install and Use the Asciidoctor Maven Plugin] - {uri-gradle-guide}[How to Install and Use the Asciidoctor Gradle Plugin] ==== [NOTE] The versions of Asciidoctor and AsciidoctorJ no longer align since version 1.6.0 of AsciidoctorJ. Please check the corresponding release notes to find out which version of Asciidoctor is packaged if you are embedding the library. If you use the distribution you can call `asciidoctorj --version` to get the version of Asciidoctor that is embedded in AsciidoctorJ. === Windows Installation A {uri-chocolatey}[Chocolatey] package is available which installs the asciidoctorj-{artifact-version}-bin.zip Bintray artifact along with a binary shim in %ChocolateyInstall%\\bin which lets you run AsciidoctorJ from the command line. ---- C:\\> choco install asciidoctorj C:\\> where asciidoctorj C:\\ProgramData\\chocolatey\\bin\\asciidoctorj.exe C:\\> asciidoctorj -b pdf README.adoc ---- == Converting documents The main entry point for AsciidoctorJ is the `Asciidoctor` Java interface. This interface provides four methods for converting AsciiDoc content. * `convert` * `convertFile` * `convertFiles` * `convertDirectory` You'll learn about these methods in the <>. IMPORTANT: Prior to Asciidoctor 1.5.0, the term `render` was used in these method names instead of `convert` (i.e., `render`, `renderFile`, `renderFiles` and `renderDirectory`). AsciidoctorJ continues to support the old method names for backwards compatibility. [cols=""1m,1m,2""] .Convert methods on the `Asciidoctor` interface |=== |Method Name |Return Type| Description |convert |String |Parses AsciiDoc content read from a string or stream and converts it to the format specified by the `backend` option. |convertFile |String |Parses AsciiDoc content read from a file and converts it to the format specified by the `backend` option. |convertFiles |String[] |Parses a collection of AsciiDoc files and converts them to the format specified by the `backend` option. |convertDirectory |String[] |Parses all AsciiDoc files found in the specified directory (using the provided strategy) and converts them to the format specified by the `backend` option. |=== // What is the 'provided strategy', need a link NOTE: All the methods listed in Table 3 are overloaded to accommodate various input types and options. You retrieve an instance of the `Asciidoctor` interface from the factory method provided. [source] .Creating an Asciidoctor instance from Asciidoctor.Factory ---- import static org.asciidoctor.Asciidoctor.Factory.create; import org.asciidoctor.Asciidoctor; Asciidoctor asciidoctor = create(); ---- Once you retrieve an instance of the `Asciidoctor` interface, you can use it to convert AsciiDoc content. Here's an example of using AsciidoctorJ to convert an AsciiDoc string. NOTE: The following `convertFile` or `convertFiles` methods will only return a converted `String` object or array if you disable writing to a file, which is enabled by default. To disable writing to a file, create a new `Options` object, disable the option to create a new file with `option.setToFile(false)`, and then pass the object as a parameter to `convertFile` or `convertFiles`. [source] .Converting an AsciiDoc string ---- //... import java.util.HashMap; //... String html = asciidoctor.convert( ""Writing AsciiDoc is _easy_!"", new HashMap()); System.out.println(html); ---- The `convertFile` method will convert the contents of an AsciiDoc file. [source] .Converting an AsciiDoc file ---- //... import java.util.HashMap; //... String html = asciidoctor.convertFile( new File(""sample.adoc""), new HashMap()); System.out.println(html); ---- The `convertFiles` method will convert a collection of AsciiDoc files: [source] .Converting a collection of AsciiDoc files ---- //... import java.util.Arrays; //... String[] result = asciidoctor.convertFiles( Arrays.asList(new File(""sample.adoc"")), new HashMap()); for (String html : result) { System.out.println(html); } ---- WARNING: If the converted content is written to files, the `convertFiles` method will return a String Array (i.e., `String[]`) with the names of all the converted documents. Another method provided by the `Asciidoctor` interface is `convertDirectory`. This method converts all of the files with AsciiDoc extensions (`.adoc` _(preferred)_, `.ad`, `.asciidoc`, `.asc`) that are present within a specified folder and following given strategy. An instance of the `DirectoryWalker` interface, which provides a strategy for locating files to process, must be passed as the first parameter of the `convertDirectory` method. Currently `Asciidoctor` provides two built-in implementations of the `DirectoryWalker` interface: [cols=""1m,2""] .Built-in `DirectoryWalker` implementations |=== |Class |Description |AsciiDocDirectoryWalker |Converts all files of given folder and all its subfolders. Ignores files starting with underscore (_). |GlobDirectoryWalker |Converts all files of given folder following a glob expression. |=== If the converted content is not written into files, `convertDirectory` will return an array listing all the documents converted. // SW: Maybe provide an example of this array output? [source] .Converting all AsciiDoc files in a directory ---- //... import org.asciidoctor.AsciiDocDirectoryWalker; //... String[] result = asciidoctor.convertDirectory( new AsciiDocDirectoryWalker(""src/asciidoc""), new HashMap()); for (String html : result) { System.out.println(html); } ---- Another way to convert AsciiDoc content is by calling the `convert` method and providing a standard Java `java.io.Reader` and `java.io.Writer`. The `Reader` interface is used as the source, and the converted content is written to the `Writer` interface. [source] .Converting content read from a java.io.Reader to a java.io.Writer ---- //... import java.io.FileReader; import java.io.StringWriter; //... FileReader reader = new FileReader(new File(""sample.adoc"")); StringWriter writer = new StringWriter(); asciidoctor.convert(reader, writer, options().asMap()); StringBuffer htmlBuffer = writer.getBuffer(); System.out.println(htmlBuffer.toString()); ---- === Safe mode and file system access Asciidoctor provides security levels that control the read and write access of attributes, the include directive, macros, and scripts while a document is processing. Each level includes the restrictions enabled in the prior security level. When Asciidoctor (and AsciidoctorJ) is used as _API_, it uses `SECURE` safe mode by default. This mode is the most restrictive one and in summary it disallows the document from attempting to read files from the file system and including their contents into the document. We recommend you to set `SAFE` safe mode when rendering AsciiDoc documents using AsciidoctorJ to have almost all Asciidoctor features such as _icons_, _include directive_ or retrieving content from _URIs_ enabled. Safe mode is set as option when a document is rendered. For example: [source, java] ---- import static org.asciidoctor.OptionsBuilder.options; Map options = options().safe(SafeMode.SAFE) .asMap(); String outfile = asciidoctor.convertFile(new File(""sample.adoc""), options); ---- We are going to explain in more detail options in <>. You can read more about safe modes in http://asciidoctor.org/docs/user-manual/#running-asciidoctor-securely === Conversion options Asciidoctor supports numerous options, such as: `in_place`:: Converts the output to a file adjacent to the input file. `template_dirs`:: Specifies a directory of {uri-tilt}[Tilt]-compatible templates to be used instead of the default built-in templates `attributes`:: A Hash (key-value pairs) of attributes to configure various aspects of the AsciiDoc processor The second parameter of the `convert` method is `java.util.Map`. The options listed above can be set in `java.util.Map`. [source] .Using the `in_place` option and the `backend` attribute ---- Map attributes = new HashMap(); attributes.put(""backend"", ""docbook""); // <1> Map options = new HashMap(); options.put(""attributes"", attributes); // <2> options.put(""in_place"", true); // <3> String outfile = asciidoctor.convertFile(new File(""sample.adoc""), options); ---- <1> Defines the `backend` attribute as `docbook` in the attributes map <2> Registers the attributes map as the `attributes` option in the options map <3> Defines the `in_place` option in the options map Another way for setting options is by using `org.asciidoctor.Options` class. `Options` is a simple Java class which contains methods for setting required options. Note that related with `org.asciidoctor.Options` class, there is `org.asciidoctor.Attributes` class, which can be used for setting attributes. The `convert` method is overloaded so `org.asciidoctor.Options` can be passed instead of a `java.util.Map`. [source] .Using the in_place option and the backend attribute ---- Attributes attributes = new Attributes(); attributes.setBackend(""docbook""); // <1> Options options = new Options(); options.setAttributes(attributes); // <2> options.setInPlace(true); // <3> String outfile = asciidoctor.convertFile(new File(""sample.adoc""), options); ---- <1> Defines the `backend` attribute as `docbook` in the attributes class <2> Registers the attributes class as the `attributes` option in the options class <3> Defines the `in_place` option in the options class AsciidoctorJ also provides two builder classes to create these maps and classes in a more readable form. `AttributesBuilder`:: Used to define attributes with a fluent API `OptionsBuilder`:: Used to define options with a fluent API The code below results in the same output as the previous example but uses the builder classes. [source] .Setting attributes and options with the builder classes ---- import static org.asciidoctor.AttributesBuilder.attributes; import static org.asciidoctor.OptionsBuilder.options; //... Map attributes = attributes().backend(""docbook"") // <1> .asMap(); Map options = options().inPlace(true) .attributes(attributes) // <2> .asMap(); // <3> String outfile = asciidoctor.convertFile(new File(""sample.adoc""), options); ---- <1> Defines the `backend` attribute as `docbook` using fluent API. <2> Registers the attributes map as `attributes`. <3> Converts options to `java.util.Map` instance. [source] .Setting attributes and options with the builder classes ---- import static org.asciidoctor.AttributesBuilder.attributes; import static org.asciidoctor.OptionsBuilder.options; //... Attributes attributes = attributes().backend(""docbook"").get(); // <1> Options options = options().inPlace(true).attributes(attributes).get(); // <2> String outfile = asciidoctor.convertFile(new File(""sample.adoc""), options); // <3> ---- <1> Defines and returns an `Attributes` class instead of `java.util.Map` by calling `get()` method instead of `asMap()`. <2> Defines and returns an `Options` class instead of `java.util.Map` by calling `get()` method instead of `asMap()`. <3> Converts the document passing `Options` class. TIP: All methods used to convert content are overloaded with `OptionsBuilder` parameter, so it is no longer required to call `get` nor `asMap` methods. WARNING: The `icons` attribute requires a `String` to set the value used to “draw” icons. At this time, you can use two constants `org.asciidoctor.Attributes.IMAGE_ICONS` for using the same approach as AsciiDoc, that is using `img` tags, or `org.asciidoctor.Attributes.FONT_ICONS` for using icons from {uri-font-awesome}[Font Awesome^]. Attributes can be specified as `String` or `Array` instead of pair key/value by using `org.asciidoctor.Attributes.setAttributes(String)` or [x-]`org.asciidoctor.Attributes.setAttributes(String...)` and `AttributesBuilder` methods. [source] .Passing attributes as a string ---- //... Attributes attributes = attributes().attributes(""toc numbered"").get(); Options options = options().attributes(attributes).get(); ---- Passing attributes as a string is equivalent to passing individual attributes. [source] .Passing individual attributes ---- //... Attributes attributes = attributes().tableOfContents(true).sectionNumbers(true).get(); Options options = options().attributes(attributes).get(); ---- You can also use an array. [source] .Passing attributes as an array ---- //... String[] attributesArray = new String[]{""toc"", ""source-highlighter=coderay""}; Attributes attributes = attributes().attributes(attributesArray).sectionNumbers(true).get(); Options options = options().attributes(attributes).get(); ---- Passing attributes as an array is equivalent to passing individual attribute. [source] .Passing individual attributes ---- //... Attributes attributes = attributes().tableOfContents(true).sectionNumbers(true).sourceHighlighter(""coderay"").get(); Options options = options().attributes(attributes).get(); ---- == Locating files A utility class `AsciiDocDirectoryWalker` is available for searching the AsciiDoc files present in a root folder and its subfolders. `AsciiDocDirectoryWalker` locates all files that end with `.adoc`, `.ad`, `.asciidoc` or `.asc`. Also it ignores all files starting with underscore (`_`). [source] .Locating AsciiDoc files with `AsciiDocDirectoryWalker` ---- import java.util.List; import org.asciidoctor.AsciiDocDirectoryWalker; DirectoryWalker directoryWalker = new AsciiDocDirectoryWalker(""docs""); // <1> List asciidocFiles = directoryWalker.scan(); // <2> ---- <1> Defines which parent directory is used for searching. <2> Returns a list of all AsciiDoc files found in root folder and its subfolders. A utility class `GlobDirectoryWalker` is available for searching the AsciiDoc files present in a root folder and scanning using a `Glob` expression. `GlobDirectoryWalker` locates all files that end with `.adoc`, `.ad`, `.asciidoc` or `.asc`. [source] .Locating AsciiDoc files with `GlobDirectoryWalker` ---- import java.util.List; import org.asciidoctor.GlobDirectoryWalker; DirectoryWalker directoryWalker = new GlobDirectoryWalker(""docs"", ""**/*.adoc""); // <1> List asciidocFiles = directoryWalker.scan(); // <2> ---- <1> Defines which parent directory is used for searching and the glob expression. <2> Returns a list of all AsciiDoc files matching given glob expression. == Reading the document tree Instead of converting an AsciiDoc document, you may want to parse the document to read information it contains or navigate the document's structure. AsciidoctorJ let's you do this! AsciidoctorJ provides a model of the abstract syntax tree of the document. These objects are directly linked to the internal representation. To load a document, use the `load` or `loadFile` methods. [source] ---- import org.asciidoctor.ast.Document; //... Document document = asciidoctor.load(DOCUMENT, new HashMap()); // <1> assertThat(document.doctitle(), is(""Document Title"")); // <2> ---- <1> Document from an String is loaded into `Document` object. <2> Title of the document is retrieved. But also all blocks that conforms the document can be retrieved. Currently there are support for three kinds of blocks. `Blocks` itself, `Section` for sections of the document and `StructuralNode` which is the base type where all kind of blocks (including those not mapped as Java class) are mapped. [source] ---- import org.asciidoctor.ast.Document; import org.asciidoctor.ast.Section; //... Document document = asciidoctor.load(DOCUMENT, new HashMap()); // <1> Section section = (Section) document.blocks().get(1); // <2> assertThat(section.index(), is(0)); // <3> assertThat(section.sectname(), is(""sect1"")); assertThat(section.special(), is(false)); ---- <1> Document from an String is loaded into `Document` object. <2> All blocks are get and because in this example the first block is a Section block, we cast it directly. <3> Concrete methods for sections can be called. Blocks can also be retrieved from query using `findBy` method. [source] ---- Document document = asciidoctor.load(DOCUMENT, new HashMap()); Map selector = new HashMap<>(); // <1> selector.put(""context"", "":image""); // <2> List findBy = document.findBy(selector); assertThat(findBy, hasSize(2)); //<3> ---- <1> To make queries you need to use a `map` approach. Currently this is because of the Asciidoctor API but it will change in near future. <2> In this example all blocks with context as image is returned. Notice that the colon (`:`) must be added in the value part. <3> Document used as example contains two images. == Extension API [NOTE] If you are migrating existing extensions to a newer version of AsciidoctorJ please read the <> One of the major improvements to Asciidoctor recently is the extensions API. AsciidoctorJ brings this extension API to the JVM environment. {uri-repo}[AsciidoctorJ] allows us to write extensions in Java instead of Ruby. Asciidoctor provides seven types of extension points. Each extension point has an abstract class in Java that maps to the extension API in Ruby. [cols=""1m,2""] .AsciidoctorJ extension APIs |=== |Name |Class |Preprocessor |org.asciidoctor.extension.Preprocessor |Treeprocessor |org.asciidoctor.extension.Treeprocessor |Postprocessor |org.asciidoctor.extension.Postprocessor |Block processor |org.asciidoctor.extension.BlockProcessor |Block macro processor |org.asciidoctor.extension.BlockMacroProcessor |Inline macro processor |org.asciidoctor.extension.InlineMacroProcessor |Include processor |org.asciidoctor.extension.IncludeProcessor |=== You can read more about the Extension API in the <>. === Ruby extensions You can even register extensions written in Ruby using AsciidoctorJ. To register a _Ruby_ extension you must get a `RubyExtensionRegistry` class instead of `JavaExtensionRegistry`. [source] .Register a Ruby extension in Java ---- RubyExtensionRegistry rubyExtensionRegistry = this.asciidoctor.rubyExtensionRegistry(); // <1> rubyExtensionRegistry.loadClass(Class.class.getResourceAsStream(""/YellRubyBlock.rb"")).block(""rubyyell"", ""YellRubyBlock""); // <2> String content = asciidoctor.convertFile(new File( ""target/test-classes/sample-with-ruby-yell-block.ad""), options().toFile(false).get()); ---- <1> `rubyExtensionRegistry` method is called to get a rubyExtensionRegistry instance. <2> Ruby file containing a class implementing a Block extension is loaded inside the Ruby runtime. Then the block is registered with a name (rubyyell), and we pass the name of the class to be instantiated. [source,ruby] .YellBlock.rb ---- require 'asciidoctor' require 'asciidoctor/extensions' class YellRubyBlock < Asciidoctor::Extensions::BlockProcessor option :contexts, [:paragraph] option :content_model, :simple def process parent, reader, attributes lines = reader.lines.map {|line| line.upcase.gsub(/\\.( |$)/, '!\\\\1') } Asciidoctor::Block.new parent, :paragraph, :source => lines, :attributes => attributes end end ---- == Logs handling API [NOTE] ==== This API is inspired by Java Logging API (JUL). If you are familiar with `java.util.logging.*` you will see familiar analogies with some of its components. ==== AsciidoctorJ (v1.5.7+) offers the possibility to capture messages generated during document rendering. These messages correspond to logging information and are organized in 6 severity levels: . DEBUG . INFO . WARN . ERROR . FATAL . UNKNOWN The easiest way to capture messages is registering a `LogHandler` through the `Asciidoctor` instance. [source,java] .Registering a LogHandler ---- Asciidoctor asciidoctor = Asciidoctor.Factory.create(); asciidoctor.registerLogHandler(new LogHandler() { // <1> @Override public void log(LogRecord logRecord) { System.out.println(logRecord.getMessage()); } }); ---- <1> Use `registerLogHandler` to register one or more handlers. The `log` method in the `org.asciidoctor.log.LogHandler` interface provides a `org.asciidoctor.log.LogRecord` that exposes the following information: [horizontal] Severity severity:: Severity level of the current record. Cursor cursor:: Information about the location of the event, contains: * LineNumber: relative to the file where the message occurred. * Path: source file simple name, or `` value when converting from a String. * Dir: absolute path to the source file parent directory, or the execution path when converting from a String. * File: absolute path to the source file, or `null` when converting from a String. + These will point to the correct source file, even when this is included from another. String message:: Descriptive message about the event. String sourceFileName:: Contains the value `